question_id
int64 25
74.7M
| answer_id
int64 332
74.7M
| title
stringlengths 20
150
| question
stringlengths 23
4.1k
| answer
stringlengths 20
4.1k
|
|---|---|---|---|---|
439,580
| 1,445,301
|
best way to programmatically modify excel spreadsheets
|
I'm looking for a library that will allow me to programatically modify Excel files to add data to certain cells. My current idea is to use named ranges to determine where to insert the new data (essentially a range of 1x1), then update the named ranges to point at the data. The existing application this is going to integrate with is written entirely in C++, so I'm ideally looking for a C++ solution (hence why this thread is of limited usefulness). If all else fails, I'll go with a .NET solution if there is some way of linking it against our C++ app.
An ideal solution would be open source, but none of the ones I've seen so far (MyXls and XLSSTREAM) seem up to the challenge. I like the looks of Aspose.Cells, but it's for .NET or Java, not C++ (and costs money). I need to support all Excel formats from 97 through the present, including the XLSX and XLSB formats. Ideally, it would also support formats such as OpenOffice, and (for output) PDF and HTML.
Some use-cases I need to support:
reading and modifying any cell in the spreadsheet, including formulas
creating, reading, modifying named ranges (the ranges themselves, not just the cells)
copying formatting from a cell to a bunch of others (including conditional formatting) -- we'll use one cell as a template for all the others we fill in with data.
Any help you can give me finding an appropriate library would be great. I'd also like to hear some testimonials about the various suggestions (including the ones in my post) so I can make more informed decisions -- what's easy to use, bug-free, cheap, etc?
|
I ended up using Aspose.Cells as I mentioned in my original post, since it seemed like the easiest path. I'm very happy with the way it turned out, and their support is very good. I had to create a wrapper around it in C# that exported a COM interface to my C++ application.
|
439,704
| 441,182
|
What is the best ORB for Java/C++ interoperation using CORBA?
|
I have a client-server application written in Java using CORBA for the communication. The ORB used is orbd, the one provided by the Java6 platform. I have to replace the Java server implementation with another one written in C++. So the question is, of the free source implementations of CORBA libraries, which one better interoperates with this ORB? Should I replace the Java ORB and also use the ORB provided by the C++ library?
The objective is to have an easy and smooth transition when replacing an already functioning server with the new C++ implementation. Is there anything else that I should take into account?
|
It's a long time I didn't use CORBA for Java and C++ interoperability, so maybe my answer will be a bit outdated.
What I found to work very well together was omniORB (C++) and JacORB (Java). You may search for those libraries on google and see if they are still supported.
I also remember I have had big problems with "native" Java CORBA (there are many bugs in Sun Bugs Parade, open for many years...) but that was at JDK1.4 time, hopefully things are a bit better now...
|
439,840
| 440,868
|
Cannot execute program if using boost (C++) libraries in debug-version on WinXP
|
I'm using boost for several C++ projects. I recently made a upgrade (1.33.1 to 1.36, soon to 1.37), since then I cannot run any debug-builds anymore.
To be sure that no other project issues remain, I've created a minimum test-project, which only includes boost.thread, and uses it to start one method. The release build can be started, the debug build cannot, although the Dependency Walker shows that all required libraries are found (this also means that the required MS Debug CRT is found in the SxS directory).
On startup I only get:
Die Anwendung konnte nicht richtig initialisiert werden (0xc0150002).
Klicken Sie auf "OK", um die Anwendung zu beenden.
Which means nothing more than "failed to initialize app". An internet research primarily lead to an MS Office installation problem, which recommends to perform a repair of WinXP.
So, beside the repair setup (which I think will not help as I'm talking about debug-dll issues), any ideas?
Ah, before I forget: Absolutely the same source-code leads to no errors on the build-machine (i.e., DLLs can be registered, means executed). So it's obviously an installation problem, but as the DLLs are there, and dependency-walker finds it, what else have I forgotten?
(edit) Well, I have not yet resolved my problem, but thanks to deemok I'm a step further. For the sake of reducing misunderstandings I give some clarifications below:
The program fails to run on the developer-machine
I am working with an installed VS2005 (it's a VC++8 project)
I used the boost-setup from BoostPro, compiled all possible build-versions, and I double-checked that they are there (otherwise I'd already get linker-errors during build).
and I double-checked any corner of include/lib/bin configuration I can think of -- as boost uses auto-linking on windows, with a special naming convention, the build or start-up would have failed, with a much more comprehensible error-message.
I cannot use static linking, as boost.thread requires dynamic linking for DLL projects (I maybe could mess around here, but as this problem seems to happen only on my machine, I do not want to mess with this, as I'm sure the boost-guys had a reason to place that check in there in the first place)
As I wrote, I checked with Dependency Walker, and it says everything is just fine.
Currently it seems to be an error in the boost-dll (maybe incorrect Manifest), will check that.
|
So you are using the pre-built libraries from BoostPro? If so, your environment might somehow be slightly different to the one they were built in (TR1 feature pack or not, etc). Perhaps best to try building Boost yourself in your specific environment.
|
439,915
| 440,010
|
UTF-8 From File to TextBox VC++ 6.0
|
How do I get an old VC++ 6.0 MFC program to read and display UTF8 in a TextBox or MessageBox? Preferably without breaking any of the file reading and displaying that is currently written in there (fairly substantial).
I read a line into CString strStr, then used this code:
int nLengthNeeded = MultiByteToWideChar(CP_UTF8,0,strStr,1024,0,0);
wchar_t * pWCMessage = new wchar_t[ nLengthNeeded ];
MultiByteToWideChar(CP_UTF8,0,strStr,1024,pWCMessage,nLengthNeeded);
nLengthNeeded = MultiByteToWideChar(CP_UTF8,0,"Error Title",50,0,0);
wchar_t * pWCTitle = new wchar_t[ nLengthNeeded ];
MultiByteToWideChar(CP_UTF8,0,"Error Title",50,pWCTitle,nLengthNeeded);
MessageBoxW(NULL,pWCMessage,pWCTitle,MB_ICONINFORMATION);
Still not sure how I would get it into a textbox, but it turns out I don't need to do that anyway.
|
I feel like this won't be helpful, but it's a starting point... I'm assuming it doesn't 'just work', and I don't think you want to try to screw around with wacky code pages that may or may not get you what you want.
How about just using MultiByteToWideChar(CP_UTF8, ...) to convert it to utf16 and then calling the W versions of those functions (or defining UNICODE/_UNICODE for the project).
I know that will work for MessageBox, and I can't imagine the text box doesn't have unicode support.
If you need to get the output back to UTF8 - just use WideCharToMultiByte().
|
440,069
| 440,145
|
Database Access Libraries for C++
|
Background:
I have an application written in native C++ which uses the wxWidgets toolkit's wxODBC database access library which is being removed from all future versions of wxWidgets . I need to replace this with another database access method that supports the assumptions and contraints outlined below. I don't require that the replacement use native DBMS APIs or ODBC under the hood, but it must meet the contraints outlined below.
Assumptions/Constraints
The library must:
Support Native (i.e. unmanaged) C++
32-bit Windows 2000/XP/2003
Visual Studio 2005
Microsoft SQL Server 2000 and 2005
Oracle 9 and 10
Run-time Performance greater than or equal to wxODBC
Single programmer API supporting multiple DBMS (e.g. don't want to write different code for using different DBMS)
Nice but Optional:
64-bit Windows operating systems
32-bit and/or 64-bit Linux operating systems
Microsoft SQL Server 2008
Oracle 11
MySQL
Any additional DBMS
Visual Studio 2008
Open Source
Runtime Performance near or equal to native DBMS API
Question:
What good libraries are available - either free, open source or pay - that support multiple DBMS from a single API including Oracle and Microsoft SQL Server and can be used from native C++?
Please describe any past experiences you have had - good OR bad - with a given library and why you are making your recommendation for or against a given library, especially in regards to the assumptions and contraints above.
See Also:
https://stackoverflow.com/questions/74141/good-orm-for-c-solutions
|
I use SQLAPI++. Well worth a look.
http://www.sqlapi.com/
|
440,133
| 440,240
|
How do I create a random alpha-numeric string in C++?
|
I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.
How do I do this in C++?
|
Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:
#include <ctime>
#include <iostream>
#include <unistd.h>
std::string gen_random(const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
std::string tmp_s;
tmp_s.reserve(len);
for (int i = 0; i < len; ++i) {
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
}
return tmp_s;
}
int main(int argc, char *argv[]) {
srand((unsigned)time(NULL) * getpid());
std::cout << gen_random(12) << "\n";
return 0;
}
Note that rand generates poor-quality random numbers.
|
440,161
| 440,618
|
Dll compatibility between compilers
|
Is there some way to make c++ dlls built with diffrent compilers compatible with each other? The classes can have factory methods for creation and destruction, so each compiler can use its own new/delete (since diffrent runtimes have there own heaps).
I tried the following code but it crashed on the first member method:
interface.h
#pragma once
class IRefCounted
{
public:
virtual ~IRefCounted(){}
virtual void AddRef()=0;
virtual void Release()=0;
};
class IClass : public IRefCounted
{
public:
virtual ~IClass(){}
virtual void PrintSomething()=0;
};
test.cpp compiled with VC9, test.exe
#include "interface.h"
#include <iostream>
#include <windows.h>
int main()
{
HMODULE dll;
IClass* (*method)(void);
IClass *dllclass;
std::cout << "Loading a.dll\n";
dll = LoadLibraryW(L"a.dll");
method = (IClass* (*)(void))GetProcAddress(dll, "CreateClass");
dllclass = method();//works
dllclass->PrintSomething();//crash: Access violation writing location 0x00000004
dllclass->Release();
FreeLibrary(dll);
std::cout << "Done, press enter to exit." << std::endl;
std::cin.get();
return 0;
}
a.cpp compiled with g++
g++.exe -shared c.cpp -o c.dll
#include "interface.h"
#include <iostream>
class A : public IClass
{
unsigned refCnt;
public:
A():refCnt(1){}
virtual ~A()
{
if(refCnt)throw "Object deleted while refCnt non-zero!";
std::cout << "Bye from A.\n";
}
virtual void AddRef()
{
++refCnt;
}
virtual void Release()
{
if(!--refCnt)
delete this;
}
virtual void PrintSomething()
{
std::cout << "Hello World from A!" << std::endl;
}
};
extern "C" __declspec(dllexport) IClass* CreateClass()
{
return new A();
}
EDIT:
I added the following line to the GCC CreateClass method, the text was correctly printed to the console, so its defenatly the function call thats killing it.
std::cout << "C.DLL Create Class" << std::endl;
I was wondering, how does COM manage to maintain binary compatibility even across languages, since its basicly all classes with inheritence (although only single) and therefore virtual functions. I'm not massivly bothered if I cant have overloaded operators/functions as long as I can maintain the basic OOP stuff (ie classes and single inheritence).
|
You should be able to mix modules built with different compilers if you lower your expectations and stick to simple functions.
The way classes and virtual functions behave is defined by the C++ standard, but the way that's implemented is up to the compiler. In this case, I know that VC++ builds objects which have virtual functions with a "vtable" pointer in the first 4 bytes of the object (I'm assuming 32-bit), and that points to a table of pointers to the method entry points.
So the line: dllclass->PrintSomething();
is actually equivalent to something like:
struct IClassVTable {
void (*pfIClassDTOR) (Class IClass * this)
void (*pfIRefCountedAddRef) (Class IRefCounted * this);
void (*pfIRefCountedRelease) (Class IRefCounted * this);
void (*pfIClassPrintSomething) (Class IClass * this);
...
};
struct IClass {
IClassVTable * pVTab;
};
(((struct IClass *) dllclass)->pVTab->pfIClassPrintSomething) (dllclass);
If the g++ compiler is implementing the virtual function tables in any way differently from MSFT VC++ -- as it is free to do and still be conformant to the C++ standard -- this will just crash as you've demonstrated. The VC++ code expects the function pointers to be in particular places in memory (relative to the object pointer).
It gets more complicated by inheritance, and really, really, complicated with multiple inheritance and virtual inheritance.
Microsoft has been very public about the way VC++ implements classes, so you can write code that depends on it. For example, a lot of COM object headers distributed by MSFT have both C and C++ bindings in the header. The C bindings expose their vtable structure like my code above does.
On the other hand, GNU -- IIRC -- has left open the option of using different implementations in different releases, and just guaranteeing the programs built with it's compiler (only!) will conform to the standard behaviour,
The short answer is to stick to simple C-style functions, POD structures (Plain Old Data; i.e., no virtual functions), and pointers to opaque objects.
|
440,167
| 440,183
|
C++ file handling (structures)
|
Following code, when compiled and run with g++,
prints '1' twice, whereas I expect '1' to be printed
only once, since I am dumping a single structure to
the file, but while reading back it seems to be
reading two structures. Why?
#include <iostream.h>
#include <fstream.h>
int main(){
struct student
{
int rollNo;
};
struct student stud1;
stud1.rollNo = 1;
ofstream fout;
fout.open("stu1.dat");
fout.write((char*)&stud1,sizeof(stud1));
fout.close();
ifstream filin("stu1.dat");
struct student tmpStu;
while(!filin.eof())
{
filin.read((char*)&tmpStu,sizeof(tmpStu));
cout << tmpStu.rollNo << endl;
}
filin.close();
}
|
eof only gets set after a read fails, so the read runs twice, and the second time, it doesn't modify the buffer.
Try this:
while(filin.read((char*)&tmpStu,sizeof(tmpStu)))
{
cout << tmpStu.rollNo << endl;
}
Or
while(!filin.read((char*)&tmpStu,sizeof(tmpStu)).eof())
{
cout << tmpStu.rollNo << endl;
}
Read returns a reference to filin when called, which will evaluate to true if the stream is still good. When read fails to read any more data, the reference will evaluate to false, which will prevent it from entering the loop.
|
440,200
| 440,332
|
How do I create a strong password string in C++?
|
Would like to create a strong password in C++. Any suggestions?
I assume it should use alpha (upper
and lower), numeric, special
characters.
It would be good to be able to
specify a minimum length.
It would be great to avoid characters
that are hard to visually distinguish
like "O" and "O"
It would be great to void all
characters same, dictionary words,
reversed words, names.
Any other tips? Where could I find code like this?
|
APG (Automated Password Generator) implements all but your last requirement (no dictionary words / usernames / repeated characters). It includes both pronounceable and fully random password generation algorithms. Pronounceable passwords look something like this:
yevGaijra
clishahopp
jewnAms8
RacMevOm
Duheamch&
raicsant~
It's written in C and is available under a BSD-like license.
Cryptographically speaking, I'm not sure that your last requirement is valid...? If the password generation is truly random, then a password of aaaaaaaa is just as likely as a password of 6-n&1jIK, and if your attacker knows your algorithm, then by disallowing passwords like aaaaaaaa, you're reducing the attacker's search space.
|
440,694
| 440,717
|
for(;true;) different from while(true)?
|
If my understanding is correct, they do exactly the same thing. Why would anyone use for the "for" variant? Is it just taste?
Edit: I suppose I was also thinking of for (;;).
|
for (;;)
is often used to prevent a compiler warning:
while(1)
or
while(true)
usually throws a compiler warning about a conditional expression being constant (at least at the highest warning level).
|
440,827
| 664,129
|
Crash writing simple WSO2/C++ web service client
|
Has any been able to successfully run with a client using the WSO2/C++ web services package? I've tried just about everything I can think of yet every time I try to run a very simple client I get a crash. Here's some sample code from one of their example programs...
#include <stdio.h>
#include <WSRESTClient.h>
#include <OMElement.h>
#include <iostream>
#include <AxisFault.h>
using namespace std;
using namespace wso2wsf;
int _tmain(int argc, _TCHAR* argv[])
{
WSRESTClient * sc = new WSRESTClient("http://localhost:9090/axis2/services/echo/echoString");
try
{
sc->initializeClient("echo_rest.log", AXIS2_LOG_LEVEL_TRACE);
}
catch (AxisFault & e)
{
cout << endl << "Error: " << e << endl;
return 0;
}
Options * op = sc->getOptions();
op->setHTTPMethod(AXIS2_HTTP_GET);
sc->setOptions(op);
{
OMNamespace * ns = new OMNamespace("http://ws.apache.org/axis2/services/echo", "ns1");
OMElement * payload = new OMElement(NULL,"echoString", ns);
OMElement * child = new OMElement(payload,"text", NULL);
child->setText("Hello World!");
cout << endl << "Request: " << payload << endl;
OMElement * response;
try
{
response = sc->request(payload, "http://ws.apache.org/axis2/c/samples/echo/soap_action");
if (response)
{
cout << endl << "Response: " << response << endl;
}
}
catch (AxisFault & e)
{
cout << endl << "Error: " << e << endl;
}
delete payload;
}
delete sc;
return 0;
}
I get a crash every time at the point of the WRESTClient object construction. It appears to be an issue somewhere in the WSO2 code but I don't get any error message indicating what the exact problem is. My next step will be to build against the source for WSO2 and step through the code which is crashing but I'm hoping someone has encountered this issue before and has some immediate feedback.
|
Have you considered putting a try/catch-all block around the WRESTClient object construction? If you're core dumping on this line then the chances are that it's throwing an exception, and if you catch it then you might be able to get more useful error information out of that exception.
Other than that, time to break out the debugger as you suggested.
|
441,067
| 441,120
|
c++ push_back, non const copy constructor
|
I have a class that i want to push_back into a deque. The problem is when i push back i need the original object to be changed thus i need a non const copy ctor. Now if i implement that my const copy ctor gets called. If i removed the const ctor i get an compile error about no available ctors. How do i implement this in a way that i can modify the original struct when i pass it in? i need to modify it bc the class destructs objects when it goes out of scope and i would like to tell it not to do so when there is another instance around. I cant use boost since my platform doesnt support it.
|
Your problem is that a fundamental requirement of standard containers is that objects are copy-constructible. That not only means that they have a copy constructor, but that also means that if you copy the object, the copy and the original are the same.
Your object, however, resembles a move-constructor semantic. That is, after a move, the new object owns the resource, and the old object is empty. That's not supported by deque as of C++03. That is, by the way, the same reason that forbids putting auto_ptr into a container.
The next C++ version, called c++0x will support those move semantics by introducing special move constructors. Until then, you will have to use an object that shares ownership when you want to put it into a standard container. That means if you copy your object, and the original goes out of scope, the owned resource is not freed until all the copies go out of scope. Consider using boost::shared_ptr for example, or wrap it into your class, if you don't want to program your own class managing that.
|
441,128
| 444,630
|
How to compile a simple Qt and c++ application using g++ on mac os x?
|
I am trying to use Qt for a project in school but am running into problems. I started following the tutorials and I am running into Makefile problems. Most of the tutorials say to run qmake -project, then qmake and finally make. But when I try this I run into the error make: *** No targets specified and no makefile found. Stop. I dont know much about Makefiles really. Could someone help point me in the right direction?
|
qmake on OS X creates Xcode project files. You can create a Makefile with:
qmake -spec macx-g++
If you don't want the Makefile to create an app bundle, you could also remove 'app_bundle' your configuration, for example by adding the following lines to your project file.
mac {
CONFIG -= app_bundle
}
|
441,203
| 441,231
|
"Proper" way to store binary data with C++/STL
|
In general, what is the best way of storing binary data in C++? The options, as far as I can tell, pretty much boil down to using strings or vector<char>s. (I'll omit the possibility of char*s and malloc()s since I'm referring specifically to C++).
Usually I just use a string, however I'm not sure if there are overheads I'm missing, or conversions that STL does internally that could mess with the sanity of binary data. Does anyone have any pointers (har) on this? Suggestions or preferences one way or another?
|
vector of char is nice because the memory is contiguious. Therefore you can use it with a lot of C API's such as berkley sockets or file APIs. You can do the following, for example:
std::vector<char> vect;
...
send(sock, &vect[0], vect.size());
and it will work fine.
You can essentially treat it just like any other dynamically allocated char buffer. You can scan up and down looking for magic numbers or patters. You can parse it partially in place. For receiving from a socket you can very easily resize it to append more data.
The downside is resizing is not terribly efficient (resize or preallocate prudently) and deletion from the front of the array will also be very ineficient. If you need to, say, pop just one or two chars at a time off the front of the data structure very frequently, copying to a deque before this processing may be an option. This costs you a copy and deque memory isn't contiguous, so you can't just pass a pointer to a C API.
Bottom line, learn about the data structures and their tradeoffs before diving in, however vector of char is typically what I see used in general practice.
|
441,306
| 441,810
|
make shared_ptr not use delete
|
in my code i would like boost::shared_ptr not to call delete but call ptr->deleteMe() instead.
Also i have a few C styled functions that return a ptr. Can i make it call lib_freeXYZ(ptr); instead of trying to delete?
|
Or how about using the stl to provide the wrapper functor - Doug T. description but without the custom caller.
boost::shared_ptr<T> ptr( new T, std::mem_fun_ref(&T::deleteMe) );
boost::shared_ptr<S> ptr( new S, std::ptr_fun(lib_freeXYZ) );
|
441,552
| 441,629
|
Scope resolution operator on enums a compiler-specific extension?
|
On this question, there's an answer that states:
You can use typedef to make Colour enumeration type accessible without specifying it's "full name".
typedef Sample::Colour Colour;
Colour c = Colour::BLUE;
That sounds correct to me, but someone down-voted it and left this comment:
Using the scope resolution operator :: on enums (as in "Colour::BLUE") is a compiler-specific extension, not standard C++
Is that true? I believe I've used that on both MSVC and GCC, though I'm not certain of it.
|
I tried the following code:
enum test
{
t1, t2, t3
};
void main()
{
test t = test::t1;
}
Visual C++ 9 compiled it with the following warning:
warning C4482: nonstandard extension
used: enum 'test' used in qualified
name
Doesn't look like it's standard.
|
441,568
| 441,683
|
When can you omit the file extension in an #include directive?
|
I'm playing around with gmock and noticed it contains this line:
#include <tuple>
I would have expected tuple.h.
When is it okay to exclude the extension, and does it give the directive a different meaning?
|
The C++ standard headers do not have a ".h" suffix. I believe the reason is that there were many, different pre-standard implementations that the standard would break. So instead of requiring that vendors change their exiting "iostream.h" (for example) header to be standards compliant (which would break their existing user's code), the standards committee decided that they'd drop the suffix (which, I believe no then existing implementation had already done).
That way, existing, non-standard programs would continue to work using the vendor's non-standard libraries. When the user wanted to make their programs standards compliant, one of the steps they would take is to change the "#include" directive to drop the ".h" suffix.
So
#include <iostream> // include the standard library version
#include <iostream.h> // include a vendor specific version (which by
// now might well be the same)
As other answers have mentioned, writers of non-standard libraries may choose either naming convention, but I'd think they would want to continue using ".h" or ".hpp" (as Boost has done) for a couple reasons:
if & when the library gets standardized, the standard version won't automatically override the previous, non-standard one (causing broken user code in all likelihood)
it seems to be a convention (more or less) that headers without a suffix are standard libraries, and those with a suffix (other than the old C headers) are non-standard.
Note that a similar problem happened when the committee went to add hash maps to the STL - they found that there are already many (different) hash_map implementations that exist, so instead of coming up with a standard one that breaks a lot of stuff out there today, they are calling the standard implementation "unordered_map". Namespaces were supposed to help prevent this type of jumping through hoops, but it didn't seem to work well enough (or be used well enough) to allow them to use the more natural name without breaking a lot of code.
Note that for the 'C' headers, C++ allows you to include either a <cxxxxxx> or <xxxxxx.h> variant. The one that starts with 'c' and has no ".h" suffix put their declarations in the std namespace (and possibly the global namespace), the ones with the ".h" suffix put the names in the global namespace (some compilers also put the names in the std namespace - it's unclear to me if that's standard compliant, though I don't see the harm).
|
441,744
| 441,778
|
Inheritance instead of typedef
|
C++ is unable to make a template out of a typedef or typedef a templated class. I know if I inherit and make my class a template, it will work.
Examples:
// Illegal
template <class T>
typedef MyVectorType vector<T>;
//Valid, but advantageous?
template <class T>
class MyVectorType : public vector<T> { };
Is doing this advantageous so that I can "fake" a typedef or are there better ways to do this?
|
C++0x will add template typedefs using the using keyword.
Your solution declares a new type, not a type "alias", e.g. you cannot initialize a MyVectorType & (reference) with a vector<T>. This might not be a problem for you, but if it is, but you don't want to reference vector in your code, you can do:
template <typename T>
class MyVectorType {
public:
typedef std::vector<T> type;
};
|
441,757
| 453,847
|
Simple option handling using Boost library (C++)
|
For instance, using the following syntax:
-I [file] -A 1 2 3
Question:
How to check if a file was specified and additionally if three (integer) values were specified.
I understand the following:
po::options_descriptions desc("Allowed options");
desc.add_options()
How to then use the specified arguments, for instance:
if (argv[3] == 1) {
...
}
Regards
|
You use the variables_map to check whether options were specified. If you added an option called "file" and your variables_map was called vm:
if(vm.count("myoption")) { ... } // Returns 0 if myoption not specified. 1 or more if it was.
Once you've used add_options to add some options, you can access them like so, assuming that you've setup a variables_map named vm:
vm["myoption"].as<int>() // Will return an int, assuming your option is an int
vm["myoption"].as<std::string>() // Will return an std::string, assuming your option is an int
In your case, you want to convert one of the specified options to a sequence of integers. You can do that like so:
vm["myoption"].as< std::vector<int> >()
Which will return a vector containing the 3 integers, which you can index and use just like any normal vector. To see if there are specifically 3, just use the size() vector member function.
The boost tutorial on this is located here.
|
441,814
| 891,027
|
Fully thread-safe shared_ptr implementation
|
Does anybody know of a fully thread-safe shared_ptr implementation? E.g. boost implementation of shared_ptr is thread-safe for the targets (refcounting) and also safe for simultaneous shared_ptr instance reads, but not writes or for read/write.
(see Boost docs, examples 3, 4 and 5).
Is there a shared_ptr implementation that is fully thread-safe for shared_ptr instances?
Strange that boost docs say that:
shared_ptr objects offer the same level of thread safety as built-in types.
But if you compare an ordinary pointer (built-in type) to smart_ptr, then simultaneous write of an ordinary pointer is thread-safe, but simultaneous write to a smart_ptr isn't.
EDIT: I mean a lock-free implementation on x86 architecture.
EDIT2: An example use case for such a smart pointer would be where there are a number of worker threads which update a global shared_ptr with a their current work item and a monitor thread that takes random samples of the work items. The shared-ptr would own the work item until another work item pointer is assigned to it (thereby destroying the previous work item). The monitor would get ownership of the work item (thereby preventing the work item to be destroyed) by assigning it to its own shared-ptr. It can be done with XCHG and manual deletion, but would be nice if a shared-ptr could do it.
Another example is where the global shared-ptr holds a "processor", and is assigned by some thread, and used by some other thread. When the "user" thread sees that the processor shard-ptr is NULL, it uses some alternative logic to do the processing. If it's not NULL, it prevents the processor from being destroyed by assigning it to its own shared-ptr.
|
Adding the necessary barriers for such a fully thread-safe shared_ptr implementation would likely impact performance. Consider the following race (note: pseudocode abounds):
Thread 1:
global_ptr = A;
Thread 2:
global_ptr = B;
Thread 3:
local_ptr = global_ptr;
If we break this down into its constituent operations:
Thread 1:
A.refcnt++;
tmp_ptr = exchange(global_ptr, A);
if (!--tmp_ptr.refcnt) delete tmp_ptr;
Thread 2:
B.refcnt++;
tmp_ptr = exchange(global_ptr, B);
if (!--tmp_ptr.refcnt) delete tmp_ptr;
Thread 3:
local_ptr = global_ptr;
local_ptr.refcnt++;
Clearly, if thread 3 reads the pointer after A's swap, then B goes and deletes it before the reference count can be incremented, bad things will happen.
To handle this, we need a dummy value to be used while thread 3 is doing the refcnt update:
(note: compare_exchange(variable, expected, new) atomically replaces the value in variable with new if it's currently equal to new, then returns true if it did so successfully)
Thread 1:
A.refcnt++;
tmp_ptr = global_ptr;
while (tmp_ptr == BAD_PTR || !compare_exchange(global_ptr, tmp_ptr, A))
tmp_ptr = global_ptr;
if (!--tmp_ptr.refcnt) delete tmp_ptr;
Thread 2:
B.refcnt++;
while (tmp_ptr == BAD_PTR || !compare_exchange(global_ptr, tmp_ptr, A))
tmp_ptr = global_ptr;
if (!--tmp_ptr.refcnt) delete tmp_ptr;
Thread 3:
tmp_ptr = global_ptr;
while (tmp_ptr == BAD_PTR || !compare_exchange(global_ptr, tmp_ptr, BAD_PTR))
tmp_ptr = global_ptr;
local_ptr = tmp_ptr;
local_ptr.refcnt++;
global_ptr = tmp_ptr;
You've now had to add a loop, with atomics in it in the middle of your /read/ operation. This is not a good thing - it can be extremely expensive on some CPUs. What's more, you're busy-waiting as well. You can start to get clever with futexes and whatnot - but by that point you've reinvented the lock.
This cost, which has to be borne by every operation, and is very similar in nature to what a lock would give you anyway, is why you generally don't see such thread-safe shared_ptr implementations. If you need such a thing, I would recommend wrapping a mutex and shared_ptr into a convenience class to automate locking.
|
441,831
| 441,837
|
Calling delete on variable allocated on the stack
|
Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack?
For example:
int nAmount;
delete &nAmount;
or
class sample
{
public:
sample();
~sample() { delete &nAmount;}
int nAmount;
}
|
No, it is not safe to call delete on a stack-allocated variable. You should only call delete on things created by new.
For each malloc or calloc, there should be exactly one free.
For each new there should be exactly one delete.
For each new[] there should be exactly one delete[].
For each stack allocation, there should be no explicit freeing or deletion. The destructor is called automatically, where applicable.
In general, you cannot mix and match any of these, e.g. no free-ing or delete[]-ing a new object. Doing so results in undefined behavior.
|
441,983
| 475,381
|
dynamic cast with interfaces
|
I have a class with implements 2 interfaces and inherits 1 class. So, generally it looks like this:
class T : public A, public IB, public IC {
};
There is one point in the code where I have an IB *, but could really use an A *. I was hoping that a dynamic cast would like this:
IB *b_ptr = new T; // it's really more complicated, but serves the example
A *a_ptr = dynamic_cast<A *>(b_ptr);
unfortunately, this doesn't work. Is there a proper way to do this? Or should I implement a work around? I've thought about having both IB and IC inherit virtually from A, but IIRC last time I tried that there were some complications that made it undesirable.
Any thoughts?
EDIT: oh yea, this is part of a plugin API, so unfortunately I don't have direct access to the T type where I need the A *. My example has then next to each other, but as mentioned, it's more complicated. Basically I have 2 shared libraries. T and T1 (where I have an IB *) are both classes which implement a plugin API and are internal to the shared libraries.
To clarify: Here's a more specific example of my typical plugins (they are in separate libraries):
plugin A:
class PluginA : public QObject, public PluginInterface, public OtherInterface {
};
plugin B:
class PluginB : public QObject, public PluginInterface {
// in here, I have a PluginInterface *, but really could use a QObject *
// unfortunately, PluginB has absolutely no knowledge of the "PluginA" type
// it just so happens that my PluginInterface * pointer points to an object of type
// PluginA.
};
EDIT: I have a guess that the issue is that pluginA and pluginB are in different shared libraries. Perhaps the rtti doesn't cross module boundaries. I think this might be the case because people's examples seem to work fine in my tests. Specifically, pluginB has no "typeinfo for PluginA" if I do an "nm" on it. This may be the core of the issue. If this is the case, I'll simply have to work around it by either virtual inheritance or a virtual cast_to_qobject() function in one of my interfaces.
|
I finally figured it out, Daniel Paull was correct in that a "sideways dybnamic_cast" should be allowed. My problem was because my code is involving shared libraries. The typeinfo from PluginA was not available in PluginB. My solution was to effectively add RTLD_NOW and RTLD_GLOBAL to my load process
technically it was
loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
because I'm using Qt's plugin system but same difference. These flags force all symbols from loaded libraries to be resolved immediately and be visible to other libraries. Therefore making the typeinfo available to everyone that needed it. The dynamic_cast worked as expected once these flags were in place.
|
442,354
| 442,364
|
Commandline arguments not working - Skips over them completely
|
Alright, I'm trying to get arguments to work properly with a small test application. My code is below. I'm not too experienced at C++, so I'm not sure why when I launch test with -print (or --print) it automatically states "Not a valid option" and then finishes up.
#include <iostream>
int main(int argc, char* argv[])
{
int option;
option = 1;
char* argument;
argument = argv[option];
while (option < argc)
{
if (argument == "-print")
{
std::cout << "Printing Extra Text";
}
else
{
std::cout << "Not a valid option" << std::endl;
}
option++;
}
std::cout << "Printing normal text" << std::endl;
return 0;
}
Am I doing this right? Thanks in advance.
|
You're comparing the memory address of the string "-print" to the memory address of argument. This won't work! Use strcmp() to compare string values. Instead of:
if (argument == "-print")
do
if (strcmp(argument, "-print") == 0)
|
442,550
| 442,561
|
Why the functions doesn't execute completely?
|
When I try to debug the following function segment, the execution brakes (jumps out of the function) at line pCellTower->m_pCellTowerInfo = pCellInfo:
RILCELLTOWERINFO* pCellInfo = (RILCELLTOWERINFO*)lpData;
CCellTower *pCellTower = (CCellTower*)cbData;
if(pCellTower != NULL)
{
pCellTower->m_pCellTowerInfo = pCellInfo;
}
(the pointer pCellInfo is not set)
Then I tried to comment the line:
RILCELLTOWERINFO* pCellInfo = (RILCELLTOWERINFO*)lpData;
CCellTower *pCellTower = (CCellTower*)cbData;
if(pCellTower != NULL)
{
//pCellTower->m_pCellTowerInfo = pCellInfo;
}
and this way the function executes normally.
Does anyone know what could be wrong?
|
The most likely explanation is that pCellTower isn't set either. It could contain random bits, and end up pointing outside the memory allocated to your app. The OS cannot allow your program to write outside the space allocated to it, so it sends the program some kind of message (Windows:exception, Unix/Linux:signal) that the write was rejected.
|
442,593
| 442,674
|
Porting Windows library using Qt to MacOSX, event loops
|
I'm inserting a hook in the MFC message loop so that the Qt events are treated, without running ->exec() on qApp (because it's blocking):
LRESULT CALLBACK myHookFn(int ncode, WPARAM wparam, LPARAM lparam) {
if (qApp) qApp->sendPostedEvents();
return CallNextHookEx(0, ncode, wparam, lparam);
}
and
int argc = 0;
new QApplication(argc, NULL);
SetWindowsHookEx(WH_GETMESSAGE, myHookFn, 0, threadId);
My question is:
What are the mechanisms equivalent to the MFC hook insertion that can be used under MacOSX so that sendPostedEvents could also be called?
|
This should happen automatically with Qt Mac 4.5 (both Carbon and Cocoa ports) - since Qt's registered as a CFRunLoopSource in CFRunLoop and the callback will invoke sendPostedEvents. See also qeventdispatcher_mac.mm in src/gui/kernel of Qt 4.5
|
442,699
| 442,785
|
Returning a variable sized array of doubles from C++ to C# - a simpler way?
|
I have the following C++ method :
__declspec(dllexport) void __stdcall getDoubles(int *count, double **values);
the method allocates and fills an array of double and sets *count to the size of the array.
The only way i managed to get this to work via pinvoke is :
[System.Runtime.InteropServices.DllImportAttribute("xx.dll")]
public static extern void getDoubles(ref int count, ref System.IntPtr values);
and usage is :
int count = 0;
IntPtr doubles = new IntPtr();
Nappy.getDoubles(ref count, ref doubles);
double[] dvs = new double[count];
for(int i = 0;i < count;++{
dvs[i] = (double)Marshal.PtrToStructure(doubles, typeof(System.Double));
doubles = new IntPtr(doubles.ToInt64()+Marshal.SizeOf(typeof(System.Double)));
}
the values end up in the dvs array.
Is there a better way ti do this not invloving pointer arithmetic in a managed language...
|
I think you can use
Marshal.Copy( source, destination, 0, size );
|
442,735
| 442,973
|
How can I embed unicode string constants in a source file?
|
I'm writing some unit tests which are going to verify our handling of various resources that use other character sets apart from the normal latin alphabet: Cyrilic, Hebrew etc.
The problem I have is that I cannot find a way to embed the expectations in the test source file: here's an example of what I'm trying to do...
///
/// Protected: TestGetHebrewConfigString
///
void CPrIniFileReaderTest::TestGetHebrewConfigString()
{
prwstring strHebrewTestFilePath = GetTestFilePath( strHebrewTestFileName );
CPrIniFileReader prIniListReader( strHebrewTestFilePath.c_str() );
prIniListReader.SetCurrentSection( strHebrewSubSection );
CPPUNIT_ASSERT( prIniListReader.GetConfigString( L"דונדארןמע" ) == L"דונהשךוק") );
}
This quite simply doesnt work. Previously I worked around this using a macro which calls a routine to transform a narrow string to a wide string (we use towstring all over the place in our applications so it's existing code)
#define UNICODE_CONSTANT( CONSTANT ) towstring( CONSTANT )
wstring towstring( LPCSTR lpszValue )
{
wostringstream os;
os << lpszValue;
return os.str();
}
The assertion in the test above then became:
CPPUNIT_ASSERT( prIniListReader.GetConfigString( UNICODE_CONSTANT( "דונדארןמע" ) ) == UNICODE_CONSTANT( "דונהשךוק" ) );
This worked OK on OS X but now I'm porting to linux and I'm finding that the tests are all failing: it all feels rather hackish as well. Can anyone tell me if they have a nicer solution to this problem?
|
A tedious but portable way is to build your strings using numeric escape codes. For example:
wchar_t *string = L"דונדארןמע";
becomes:
wchar_t *string = "\x05d3\x05d5\x05e0\x05d3\x05d0\x05e8\x05df\x05de\x05e2";
You have to convert all your Unicode characters to numeric escapes. That way your source code becomes encoding-independent.
You can use online tools for conversion, such as this one. It outputs the JavaScript escape format \uXXXX, so just search & replace \u with \x to get the C format.
|
442,784
| 442,798
|
destructors: triviality vs implicit definition
|
As I understand the standard, a trivial destructor is one which is implicitly declared and whose class has only base and non-static members with trivial destructors.
Given the recursivity of this definition, it seems to me that the only "recursion-stopping" condition is to find a base or non-static member with a non-implicitly declared destructor (i.e. user declared).
If that's right, that should mean that a trivial destructor is one which "doesn't have to do anything" and hence it will be declared (implicitly) but not defined.
Saying it in another way: is it correct to say that an implicitly defined destructor (that is "it does something") cannot be trivial as per the standard definition?
Sorry for the kind of silly question, but I'd like to clarify things a bit in my head...
|
No. An implicitly defined, trivial destructor is by definition trivial :) The difference between the declare and define thingy is that in order for the compiler to even see that a destructor is available, there must always a declaration. So if you don't provide one, it will implicitly provide one.
But now, it will also define one, if that is needed (if an object of that class type is destroyed). In any case, it has to do something: It needs to call the destructors of all its members and base classes. A simple example which illustrates the effect of implicitly defining a destructor:
struct a {
private:
~a();
};
struct bug {
// note: can't be destructed
a a_;
};
As soon as you try to create a local object of bug, the compiler will signal an error, because it yields a definition of a destructor for bug, which tries to call the not accessible destructor of a.
Now, i think triviality of destructors/constructors are mostly used to put constraints on your program. Objects having non-trivial versions of them can't be put in unions, for example. On the other side, you can delete an object having incomplete type, provided it has a trivial destructor. Note that if your program can't decide whether or not a trivial destructor was actually defined, the compiler is allowed to omit defining it. That's the so-called as-if rule. The compiler has to behave as-if it's Standard compliant - optimizations do not matter as long as they don't change the meaning of a program.
|
443,090
| 443,184
|
What are the major differences between C and C++ and when would you choose one over the other?
|
For those of you with experience with both, what are the major differences? For a newcomer to either, which would be better to learn? Are there situations where you might choose C but then other situations where you would choose C++? Is it a case of use the best tool for the job or one is significantly better than the other. I know C++ is an "enhancement" of C, but it was created in '83 and hasn't completely replaced C so there must be something more to it.
I know this question is subjective and I am not trying to start any religious war, so please try to be as objective as possible. Clear strengths and weaknesses and comparisons.
|
While C is a pure procedural language, C++ is a multi-paradigm language. It supports
Generic programming: Allowing to write code once, and use it with different data-structures.
Meta programming: Allowing to utilize templates to generate efficient code at compile time.
Inspection: Allows to inspect certain properties at compile time: What type does an expression have? How many parameters does a function have? What type does each one have?
Object oriented programming: Allowing the programmer to program object oriented, with sophisticated features such as multiple inheritance and private inheritance.
Procedural programming: Allows the programmer to put functions free of any classes. Combined with advanced features such as ADL allows writing clean code decoupled from specifics of certain classes.
Apart from those, C++ has largely kept compatibility with C code, but there are some differences. Those can be read about in Annex D of the C++ Standard, together with reasons and possible fixed to make C code valid C++ code.
|
443,095
| 443,484
|
Questions about COM/ActiveX objects
|
I have good knowledge on the working of a "traditional" .dll. Also the differences between dynamic loading and static loading, etc.
But I have the following doubts about the working of COM objects,
Is it mandatory to register COM objects with regsvr32?
can I have two versions of a registered COM object lying in the same/different directory?
besides being packaged inside a .dll file is there anything in common between a "traditional" .dll and a COM object?
|
1) No - it is NOT necessary to register COM objects. Registration is needed to create new COM objects. There are many interfaces (COM or native functions) that want a COM object. Their API tells you which interface your COM object should support. Since you pass in an existing COM object, they don't need registration information to create your COM object. A variation of this scenario is the RUnning Object Table, in which you can register created COM objects. Those objects are also created by you, and you don't need the registration info.
Example interface: IQueryCancelAutoplay.
2) A COM object exists in memory. You're probably thinking about a COM class, implemented in a DLL together with its COM factory. COM classes are registered by their GUID. You can have multipe classes=GUIDs per DLL, but only one DLL per class. Remember, the caller asks COM for an instance of your class. Which DLL would COM load if there would be two DLLs implementing the same class?!
Of course, there can be two DLLs each implementing one class, where the two classes share some interfaces. They will always share IUnknown, for instance, often IDispatch, but rarely IAcmeCorpFooBarv2
3) A COM DLL is a normal DLL which (a) exposes some COM-specific functions and (b) is registered so the COM framewrok can call LoadLibrary on it. The DLL may also expose other non-COM functions. As a result, you can call LoadLibrary on a COM DLL yourself. This can occasionally be useful to reduce the latency involved in creating your first COM object.
|
443,141
| 443,271
|
Visual Studio 6 VC++ Project version - how do I increment it?
|
I am making changes to an old program written in VC++6. the project resources include a 'version' set which include the following:
Block Header
Comments
Company Name
File Version
Product Version
Both FileVersion and ProductVersion are at 1.0.0.97 (where the 97 is a build number and increments each time I build the project)
My changes are such that I ought to increment one of the other numbers. It should probably go to 1.0.1. but even though I can edit these strings, as soon as I build the project, the 1st three numbers revert to 1.0.0. Does anyone know where these numbers are really held and how to change them?
These numbers and settings also go into the executable file's 'properties'. The build date is held in the 'Comments' resource string which I think is crap and would like to have it automatically generated as well: I am not going to remember to check it before every build!
Any suggestions gratefully received.
--- Alistair.
|
Those are in an rc .file
Open the resource editor and look in the version tab/section.
If you make the changes and save it then they should remain that way. I would check to see if there is any other task or something that is overwriting those.
Note that one of the fields (I forget which) is a "slave" of another one. Post up the resource file (or at least the section with the version info)
You can use a #include for the version info so that you have only one place for the version information.
|
443,147
| 443,192
|
C++ mix new/delete between libs?
|
If I use the new keyword in my library (which is built differently than my main app), when I delete it in my main app with delete, is there a chance that I may get a crash/error?
|
yes indeedy. In particular you see problems with debug/release heaps being different, also if your library uses placement new, or any custom heap you'll have a problem. The Debug/Release issue is by far the most common though.
|
443,295
| 444,054
|
Caching policies and techniques for matrices
|
as explained before, I'm currently working on a small linear algebra library to use in a personal project. Matrices are implemented as C++ vectors and element assignment ( a(i,j) = v; ) is delegated to the assignment to the vector's elements. For my project I'll need to solve tons of square equation systems and, in order to do that, I implemented the LU factorization (Gaussian Elimination) for square matrices. In the current implementation I'm avoiding to recalculate each time the LU factorization by caching the L and U matrices, the problem is that since I'm delegating the element assignment to vector, I can't find a way to say if the matrix is being changed and whether to recalculate the factorization. Any ideas on how to solve this?
Thank you
|
template<class T>
class matrix {
public:
class accessor {
public:
accessor(T& dest, matrix& parent) : dest(dest), parent(parent) { }
operator T const& () const { return dest; }
accessor& operator=(T const& t) { dest = t; parent.invalidate_cache(); return *this; }
private:
T& dest;
matrix& parent;
};
// replace those with actual implementation..
accessor operator()(int x, int y) {
static T t; return accessor(t, *this);
}
T const& operator()(int x, int y) const {
static T t; return t;
}
private:
void invalidate_cache() { cout << "Cache invalidated !!\n"; }
vector<T> impl;
};
thanks go to to ##iso-c++ @ irc.freenode.net for some helpful corrections
|
443,642
| 443,715
|
What is the best unit testing tool for a mix of managed and unmanaged C++?
|
I am going to start implementing some unit tests for a codebase that is a mix of managed and unmanaged C++. Can NUnit hack it with unmanaged code? Is there a better alternative?
|
It's possible to use NUnit to test unmanaged code, example:
// Tests.h
#pragma once
#include <cmath>
using namespace System;
using namespace NUnit::Framework;
namespace Tests {
[TestFixture]
public ref class UnitTest
{
public:
UnitTest(void) {}
[Test]
void TestCos()
{
Assert::AreEqual(1, cos(0.0));
}
};
}
|
443,809
| 489,355
|
How to know if a MFC message loop is already running?
|
Is there any way to know whether a MFC message loop is already running?
EDIT: Context: A library (with event handling) needs to know whether its event filtering has to attach to an existing MFC message loop or create its own message loop: in case a main message loop already exists it must not create its own loop because it would be blocking.
|
There is no way to do it without waiting some time, for instance while trying to send an event and wait for it, or wait 5 sec using a special MFC function which is dedicated to detect stalled applications (which one? I can't remember its name...).
If you need to do it, find another way, make other assumptions. Sorry.
|
444,322
| 444,347
|
C++ Question about default constructor
|
What does it mean to call a class like this:
class Example
{
public:
Example(void);
~Example(void);
}
int main(void)
{
Example ex(); // <<<<<< what is it called to call it like this?
return(0);
}
Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?
Thanks for all answers.
|
Currently you are trying to call the default constructor like so.
Example ex();
This is not actually calling the default constructor. Instead you are defining a function prototype with return type Example and taking no parameters. In order to call the default constructor, omit the ()'s
Example ex;
|
444,726
| 444,742
|
Efficient way to handle COM related errors (C++)
|
Efficient way to handle COM related errors in C++.
For instance:
switch (HRESULT_CODE(hresult)) {
case NOERROR:
cout << "Object instantiated and "
"pointer to interface IS8Simulation "
"obtained" << endl;
break;
//Specifed Class not registered
case REGDB_E_CLASSNOTREG:
cerr << "Specified Class not registered." << endl;
exit (EXIT_FAILURE);
break;
case CLASS_E_NOAGGREGATION:
cerr << "The Class does not support aggregation "
"(or class object is remote)." << endl;
exit (EXIT_FAILURE);
break;
//Interface not supported - exit with error
case E_NOINTERFACE:
cerr << "No such interface supported." << endl;
exit (EXIT_FAILURE);
break;
case E_UNEXPECTED:
default:
cerr << "Catastrophic failure." << endl;
exit (EXIT_FAILURE);
break;
}
Compared to, the former:
if (SUCCEEDED(hresult))
{
cout << "The COM library was initialised"
" successfully on this thread" << endl;
} else {
cerr << "Fatal Error: COM library was not"
" initialised" << endl;
exit (EXIT_FAILURE);
}
Question:
Any other method more applicable?
Regards
|
Use FormatMessage to get the error text -- it already knows how to look up the localized text for most HRESULTs and Win32 result codes.
Use the FAILED and SUCCEEDED macros to work out if something has worked or not.
exit takes 32-bit numbers. You can use an HRESULT as your process exit code:
HRESULT hr;
if (FAILED(hr = p->QueryInterface(...)))
{
cerr << MessageFromHResult(hr); // left as an exercise for the reader
exit(hr);
}
|
444,746
| 444,755
|
Passing an array as a function parameter in C++
|
In C++, arrays cannot be passed simply as parameters. Meaning if I create a function like so:
void doSomething(char charArray[])
{
// if I want the array size
int size = sizeof(charArray);
// NO GOOD, will always get 4 (as in 4 bytes in the pointer)
}
I have no way of knowing how big the array is, since I have only a pointer to the array.
Which way do I have, without changing the method signature, to get the size of the array and iterate over it's data?
EDIT: just an addition regarding the solution. If the char array, specifically, was initialized like so:
char charArray[] = "i am a string";
then the \0 is already appended to the end of the array. In this case the answer (marked as accepted) works out of the box, so to speak.
|
Without changing the signature? Append a sentinel element. For char arrays specifically, it could be the null-terminating '\0' which is used for standard C strings.
void doSomething(char charArray[])
{
char* p = charArray;
for (; *p != '\0'; ++p)
{
// if '\0' happens to be valid data for your app,
// then you can (maybe) use some other value as
// sentinel
}
int arraySize = p - charArray;
// now we know the array size, so we can do some thing
}
Of course, then your array itself cannot contain the sentinel element as content.
For other kinds of (i.e., non-char) arrays, it could be any value which is not legal data. If no such value exists, then this method does not work.
Moreover, this requires co-operation on the caller side. You really have to make sure that the caller reserves an array of arraySize + 1 elements, and always sets the sentinel element.
However, if you really cannot change the signature, your options are rather limited.
|
445,015
| 445,026
|
Suppressing Linking Errors in G++ 3.4.6
|
Don't ask why, but is there any way to suppress a failed linking error?
Such as:
undefined reference to BLANK
This is in GCC 3.4.6
|
No, because they are errors and not warnings. By definition this means that the function was referenced someplace but not defined... that's not something you can just ignore.
|
445,127
| 445,135
|
Passing "this" to a function from within a constructor?
|
Can I pass "this" to a function as a pointer, from within the class constructor, and use it to point at the object's members before the constructor returns?
Is it safe to do this, so long as the accessed members are properly initialized before the function call?
As an example:
#include <iostream>
class Stuff
{
public:
static void print_number(void *param)
{
std::cout << reinterpret_cast<Stuff*>(param)->number;
}
int number;
Stuff(int number_)
: number(number_)
{
print_number(this);
}
};
void main() {
Stuff stuff(12345);
}
I thought this wouldn't work, but it seems to. Is this standard behavior, or just undefined behavior going my way?
|
When you instantiate an object in C++, the code in the constructor is the last thing executed. All other initialization, including superclass initialization, superclass constructor execution, and memory allocation happens beforehand. The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.
Of course, you still need to beware of uninitialized member variables, if you haven't already initialized them in your constructor code.
|
445,139
| 452,595
|
How to get Program Files folder path (not Program Files (x86)) from 32bit WOW process?
|
I need to get the path to the native (rather than the WOW) program files directory from a 32bit WOW process.
When I pass CSIDL_PROGRAM_FILES (or CSIDL_PROGRAM_FILESX86) into SHGetSpecialFolderPath it returns the WOW (Program Files (x86)) folder path.
I'd prefer to avoid using an environment variable if possible.
I want to compare some values I read from the registry, if the values point to the path of either the WOW or native version of my app then my code does something, if not it does something else.
To figure out where the native and WOW versions of my app are expected to be I need to get the paths to "Program Files (x86)" and "Program Files".
|
I appreciate all the help and, especially, the warnings in this thread. However, I really do need this path and this is how I got it in the end:
(error checking removed for clarity, use at your own risk, etc)
WCHAR szNativeProgramFilesFolder[MAX_PATH];
ExpandEnvironmentStrings(L"%ProgramW6432%",
szNativeProgramFilesFolder,
ARRAYSIZE(szNativeProgramFilesFolder);
|
445,295
| 576,411
|
Why does OpenCV reject cvLoadImage("string.ext"), but accept cvLoadImage(argv[1])?
|
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
int main(int argc, char* argv[]){
cvNamedWindow("Window1", CV_WINDOW_AUTOSIZE);
IplImage* image = 0;
->->image = cvLoadImage(argv[1]);<-<-
if(!image) printf("Unable to load image!");
cvShowImage("Window1", image);
char c = cvWaitKey(0);
cvReleaseImage(&image);
cvDestroyWindow("Window1");
return 0;
}
If I replace the indicated line with cvLoadImage("247.png") I get a blank window and image remains equal to zero
If I run the exe and give it 247.png as an argument, it's just dandy. If I put the "247.png" right into the code and build and run it Visual Studio 2008, it fails. If I build and run from the command prompt, it works.
Why is this? I'm a little bit weary of moving forwards without getting this down.
|
Under Project->Properties->Configuration Properties->Debugging there is a field "Working Directory". Set that to the directory you want to execute in and that should fix the problem.
|
445,301
| 500,505
|
Avoiding UAC in vista
|
im writing an application that downloads and installs addons for programs which needs to save the data to program files (for the programs in question). Now this works fine on xp and vista with uac disabled however it is failing on normal vista due to the virtual folders.
How would one get around this with out needing to request admin rights every time the app started?
P.s. Program is written in c++, vis 2005
Edit: File system virtual folders: http://www.codeproject.com/KB/vista-security/MakingAppsUACAware.aspx
|
I got around uac by making a windows service that does the work i need and only runs while the app is running.
|
445,315
| 445,348
|
Why is snprintf faster than ostringstream or is it?
|
I read somewhere that snprintf is faster than ostringstream. Has anyone has any experiences with it? If yes why is it faster.
|
std::ostringstream is not required to be slower, but it is generally slower when implemented. FastFormat's website has some benchmarks.
The Standard library design for streams supports much more than snprintf does. The design is meant to be extensible, and includes protected virtual methods that are called by the publicly exposed methods. This allows you to derive from one of the stream classes, with the assurance that if you overload the protected method you will get the behavior you want. I believe that a compiler could avoid the overhead of the virtual function call, but I'm not aware of any compilers that do.
Additionally, stream operations often use growable buffers internally; which implies relatively slow memory allocations.
|
445,382
| 447,380
|
How to get process info programmatically in C/C++ from a Solaris system?
|
Is there a C/C++ library, and documentation about how to collect system and process information on Solaris?
Although I could parse command-line tools, I'd rather use a library that makes the task easier to do.
Thanks
Edit: It has been suggested to use the /proc virtual directory to collect information, however its not much better than parsing command-line tools, in the sense that I'll need to implement some sort of custom parsing for every piece of data I need.
I'm looking for something along the lines of c libraries for Windows or MacOS that provides this information through a c-based systems API, however I'm having no luck with Google.
|
You can get this kind of information with kstat API.
man -s 3KSTAT kstat
You can see how it is used in OpenSolaris vmstat and iostat source.
For information about processus, I'd look at ps.
|
445,570
| 445,591
|
When can't an object be converted to a reference?
|
I want to compile the following line of code from http://code.google.com/p/enhsim:
enh::eout << enh::setw(26);
gcc gives the following error:
error: no match for 'operator<<' in 'enh::eout << enh::setw(26)'
But the EnhSimOutput class (of which enh::eout is an instance) does declare:
EnhSimOutput& operator<< (setw& p);
This problem goes away if I implement a version of the operation that accepts the object by value:
EnhSimOutput& operator<< (setw p);
or if I create the enh::setw object as a local, i.e.:
enh::setw wValue(26);
enh::eout << wValue;
My question is this: why does gcc not select the "by-reference" version of the operator to begin with?
The developers who wrote this code clearly made it compile, yet default gcc refuses to do it. Why is there a difference between an object declared separately as a local variable and a local created inline?
|
The value enh::setw(26); is an rvalue . Actually, temporaries like that are rvalues. Rvalues have special properties. One of them is that their address can't be taken (&enh::setw(26); is illegal), and they can't generally bind to references to non-const (some temporaries can bind to references to non-const, but these undergo special rules: Calling member functions on temporary objects and catching exception objects by reference to non-const. In the latter case, the temporary even is an lvalue).
There are two kind of expressions: lvalues that denote objects (that in turn may store an value) or functions, and rvalues which are meant to represent values read out of an object or represented by temporaries, numeral literals and enumerator constants. In C++03, to be able to pass such values to a function that accepts its value by-reference, there is a rule that they can be accepted by reference-to-const: setw const& p would accept it. That is, you would have to declare your operator like this:
EnhSimOutput& operator<< (setw const& p);
That's a bit unfortunate, because you can't disambiguate constant lvalues (objects you created on the stack using const enh::setw e(26); for example) and non-const or const rvalues (like enh::setw(26); which is a non-const temporary). Also, if you go by that, the parameter can't have called non-const member functions on it, because it's a reference-to-const. For that reason, C++1x, the next C++ version, introduce a new kind of reference, so-called rvalue-references which fixes that.
The Microsoft Visual C++ compiler binds rvalues to references to non-const, but gives out a warning when doing that (you have to use at least warning level 4 for it to show up). That's unfortunate, because problems rise up when porting to other compilers that are more strict in Standard compliance.
|
445,702
| 445,724
|
Template class with "typename"
|
I have a template class where I want to use objects of that class (along with the parameterized type) inside a map. So far this is the solution that I've been able to arrive at:
class IStatMsg;
template <typename T>
class ITier
{
public:
// Methods
ITier(TierType oType) : o_Type(oType){};
virtual ~ITier(){};
typename ITier<T> ParamITier; // line 60
ITier* Get(T oKey)
{
std::map<T, ParamITier*>::iterator it = map_Tiers.find(oKey); // line 64
if (it != map_Tiers.end())
return it->second;
return NULL;
}
void Set(T oKey, ITier* pTier)
{
map_Tiers.insert(pair<T, ParamITier*>(oKey, pTier)); // line 74
}
TierType GetType() { return o_Type; }
protected:
// Methods
// Attributes
std::map<T, ParamITier*> map_Tiers; // line 83
TierType o_Type;
private:
// Methods
// Attributes
};
But when I try to compile this code I get a long list of errors:
/home/gayanm/street/src/QueryServer_NEW/ITier.h:60:
error: expected nested-name-specifier
/home/gayanm/street/src/QueryServer_NEW/ITier.h:60:
error: ITier<T>' specified as
declarator-id
/home/gayanm/street/src/QueryServer_NEW/ITier.h:60:
error: perhaps you wantITier'
for a constructor
/home/gayanm/street/src/QueryServer_NEW/ITier.h:60:
error: two or more data types in
declaration of ITier<T>'
/home/gayanm/street/src/QueryServer_NEW/ITier.h:60:
error: expected;' before
"ParamITier"
/home/gayanm/street/src/QueryServer_NEW/ITier.h:83:
error: ParamITier' was not declared
in this scope
/home/gayanm/street/src/QueryServer_NEW/ITier.h:83:
error: template argument 2 is invalid
/home/gayanm/street/src/QueryServer_NEW/ITier.h:83:
error: template argument 4 is invalid
/home/gayanm/street/src/QueryServer_NEW/ITier.h:83:
error: ISO C++ forbids declaration of
map_Tiers' with no type
/home/gayanm/street/src/QueryServer_NEW/ITier.h:
In member function ITier<T>*
ITier<T>::Get(T)':
/home/gayanm/street/src/QueryServer_NEW/ITier.h:64:
error:ParamITier' undeclared (first
use this function)
/home/gayanm/street/src/QueryServer_NEW/ITier.h:64:
error: (Each undeclared identifier is
reported only once for each function
it appears in.)
/home/gayanm/street/src/QueryServer_NEW/ITier.h:64:
error: template argument 2 is invalid
/home/gayanm/street/src/QueryServer_NEW/ITier.h:64:
error: template argument 4 is invalid
/home/gayanm/street/src/QueryServer_NEW/ITier.h:64:
error: expected ;' before '::' token
/home/gayanm/street/src/QueryServer_NEW/ITier.h:66:
error:it' undeclared (first use this
function)
/home/gayanm/street/src/QueryServer_NEW/ITier.h:66:
error: request for member end' in
((ITier)this)->ITier::map_Tiers',
which is of non-class type int'
/home/gayanm/street/src/QueryServer_NEW/ITier.h:
In member functionvoid
ITier::Set(T, ITier)':
/home/gayanm/street/src/QueryServer_NEW/ITier.h:74:
error: request for member insert' in
((ITier*)this)->ITier::map_Tiers',
which is of non-class type int'
/home/gayanm/street/src/QueryServer_NEW/ITier.h:74:
error:pair' undeclared (first use
this function)
/home/gayanm/street/src/QueryServer_NEW/ITier.h:74:
error: expected primary-expression
before ',' token
/home/gayanm/street/src/QueryServer_NEW/ITier.h:74:
error: ParamITier' undeclared (first
use this function)
/home/gayanm/street/src/QueryServer_NEW/ITier.h:74:
error: expected primary-expression
before '>' token
/home/gayanm/street/src/QueryServer_NEW/ITier.h:
At global scope:
/home/gayanm/street/src/QueryServer_NEW/ITier.h:93:
error: baseITier' with
only non-default constructor in class
without a constructor
/home/gayanm/street/src/QueryServer_NEW/ITier.h:109:
error: expected class-name before '{'
token
Could you please point out how to fix these?
Thank You.
|
Line 60 does not access a depending name. What you use is ITier<T> of which the compiler knows it's a template given an argument. Instead of typename you want to use typedef ;)
Line 64 does access the depending name iterator which is a type-name, so you have to put typename before std::map. I put the two disambiguations, template and typename on this answer: Disambiguations of dependent names.
Line 74 would be right, if you fix the bug in Line 60, as far as i can see.
Line 83 is alright in itself as far as i can see.
|
445,905
| 446,011
|
XML Schema to C++ Classes
|
I have to write a C++ Application (using the Qt Framework for the GUI) that can edit data stored in xml files described by a xsd schema file. Is there a tool to convert the xsd schema into C++ Classes?
|
Sounds to me like CodeSynthesis is exactly what you are looking for. It's open source and c++.
|
446,000
| 449,733
|
Resizing a Webbrowser control hosted by an Explorer Bar in IE
|
I have a custom explorer bar (a band object) that hosts a webbrowser control. I can initialize the WebBrowser control properly and have it display web pages.
However, I've noticed that when I resize the explorer bar, the webbrowser control doesn't resize appropriately to the size of the bar:
Before Resize:
After Resize:
I'm not sure what events I need to handle and what can resize the browser control. I have some experience in .NET programming, and none really in Windows programming.
I've also included my source code here if you would like to poke aorund it more.
|
Typically, when a container hosting an OLE control is resized, it queries the embedded object for its IOleInPlaceObject interface, and uses the SetObjectRects() on that interface to tell the control its new size.
|
446,205
| 446,295
|
Can I continue to use an iterator after an item has been deleted from std::multimap<>?
|
Can I continue to use an multimap iterator even after a call to multimap::erase()? For example:
Blah::iterator iter;
for ( iter = mm.begin();
iter != mm.end();
iter ++ )
{
if ( iter->second == something )
{
mm.erase( iter );
}
}
Should this be expected to run correctly, or is the iterator invalidated following the call to erase? Reference sites like http://www.cplusplus.com/reference/stl/multimap/erase.html are strangely quiet on this topic of the lifespans of iterators, or the effects of constructive/destructive methods on iterators.
|
http://www.sgi.com/tech/stl/Multimap.html
Multimap has the important property that inserting a new element
into a multimap does not invalidate iterators that point to existing
elements. Erasing an element from a multimap also does not invalidate
any iterators, except, of course, for iterators that actually point to
the element that is being erased.
So it should look like this:
Blah::iterator iter;
for ( iter = mm.begin();iter != mm.end();)
{
if ( iter->second == something )
{
mm.erase( iter++ );
// Use post increment. This increments the iterator but
// returns a copy of the original iterator to be used by
// the erase method
}
else
{
++iter; // Use Pre Increment for efficiency.
}
}
Also see:
What happens if you call erase() on a map element while iterating from begin to end?
and
delete a specific entry in the map,but the iterator must point to the next element after the deletion
|
446,296
| 446,327
|
Where can I get a "useful" C++ binary search algorithm?
|
I need a binary search algorithm that is compatible with the C++ STL containers, something like std::binary_search in the standard library's <algorithm> header, but I need it to return the iterator that points at the result, not a simple boolean telling me if the element exists.
(On a side note, what the hell was the standard committee thinking when they defined the API for binary_search?!)
My main concern here is that I need the speed of a binary search, so although I can find the data with other algorithms, as mentioned below, I want to take advantage of the fact that my data is sorted to get the benefits of a binary search, not a linear search.
so far lower_bound and upper_bound fail if the datum is missing:
//lousy pseudo code
vector(1,2,3,4,6,7,8,9,0) //notice no 5
iter = lower_bound_or_upper_bound(start,end,5)
iter != 5 && iter !=end //not returning end as usual, instead it'll return 4 or 6
Note: I'm also fine using an algorithm that doesn't belong to the std namespace as long as its compatible with containers. Like, say, boost::binary_search.
|
There is no such functions, but you can write a simple one using std::lower_bound, std::upper_bound or std::equal_range.
A simple implementation could be
template<class Iter, class T>
Iter binary_find(Iter begin, Iter end, T val)
{
// Finds the lower bound in at most log(last - first) + 1 comparisons
Iter i = std::lower_bound(begin, end, val);
if (i != end && !(val < *i))
return i; // found
else
return end; // not found
}
Another solution would be to use a std::set, which guarantees the ordering of the elements and provides a method iterator find(T key) that returns an iterator to the given item. However, your requirements might not be compatible with the use of a set (for example if you need to store the same element multiple times).
|
446,411
| 446,615
|
remote procedure calls
|
Does any one know a good way to do remote procedure calls in windows (non .net) environmental?
I cant find much information on how to do it and the msdn only has the .net version.
.
Edit:
Thanks for the answers so far. What i need it for is to communicate with a service on the same computer which will send progress reports back to the "client". The reason im intersted in rpc is because of vistas uac and how services cant talk to normal apps unless they use rpc or pipes. Looking into pipes, they seem to be entirely text based and i was under the impression that rpc can pass strongly typed values across.
I will look into DCOM as well.
|
If you are only interested in talking between processes on the same machine, boost::interprocess is a cool way of getting a channel for them to talk through.
More windows specific solutions is a shared memory mapped file and system global mutexes/signals or named pipes.
boost::serialize and google protocol buffers are ways of converting the data you send between the processes to binary strings that are less dependent on structure packing and other things that may differ between different executables.
boost::interprocess, boost::serialize and protocol buffers should be platform independent so technically it could work on Linux/Mac as well!
|
446,565
| 446,612
|
get stack trace when exception is thrown
|
I am now debugging a program that utilizes many different threads.
there is an exception that is thrown from time to time. the problem is that there is no way to know what thread caused the problem...
does anyone know an easy way to get the stack trace after the exception is thrown? I thought about simply writing a debug messages but it is going to be a huge :-) i guess there are much better techniques than this one ...
I'm using visual studio 2008 - native c++ project....
|
Unless I'm very much mistaken, you need to know which thread triggered the exception in order to use the Visual Studio debugger's call stack view, which is obviously the catch-22 situation you're in at the moment.
One thing I would try is to see if you can get the debugger to break when the exception is thrown (using Debug > Exceptions). You'll have to explicitly enable this, but if you know what type of exception is thrown, this might allow you to work out where it's thrown.
Other than that, putting a breakpoint in the constructor of the exception (if it's one of your own) should also allow you to work out where it's triggered from.
If those methods don't work for you I'd be looking at the debug messages as you already suggested.
|
446,758
| 446,768
|
How to use existing C++ code in .NET (C#)
|
I would like to create a C# project and implement the existing native (C++) code. Does anyone know about any good tutorial about it?
Thanks!
|
You can use P/Invoke and you can call unmanaged methods.
I'll post you some examples:
This is a reference to MSDN official documentation.
This is a community mantained website with most of the common Windows unmanaged libraries along with method signatures and examples
|
446,866
| 446,880
|
Boost::multi_array performance question
|
I am trying to compare the performance of boost::multi_array to native dynamically allocated arrays, with the following test program:
#include <windows.h>
#define _SCL_SECURE_NO_WARNINGS
#define BOOST_DISABLE_ASSERTS
#include <boost/multi_array.hpp>
int main(int argc, char* argv[])
{
const int X_SIZE = 200;
const int Y_SIZE = 200;
const int ITERATIONS = 500;
unsigned int startTime = 0;
unsigned int endTime = 0;
// Create the boost array
typedef boost::multi_array<double, 2> ImageArrayType;
ImageArrayType boostMatrix(boost::extents[X_SIZE][Y_SIZE]);
// Create the native array
double *nativeMatrix = new double [X_SIZE * Y_SIZE];
//------------------Measure boost----------------------------------------------
startTime = ::GetTickCount();
for (int i = 0; i < ITERATIONS; ++i)
{
for (int y = 0; y < Y_SIZE; ++y)
{
for (int x = 0; x < X_SIZE; ++x)
{
boostMatrix[x][y] = 2.345;
}
}
}
endTime = ::GetTickCount();
printf("[Boost] Elapsed time: %6.3f seconds\n", (endTime - startTime) / 1000.0);
//------------------Measure native-----------------------------------------------
startTime = ::GetTickCount();
for (int i = 0; i < ITERATIONS; ++i)
{
for (int y = 0; y < Y_SIZE; ++y)
{
for (int x = 0; x < X_SIZE; ++x)
{
nativeMatrix[x + (y * X_SIZE)] = 2.345;
}
}
}
endTime = ::GetTickCount();
printf("[Native]Elapsed time: %6.3f seconds\n", (endTime - startTime) / 1000.0);
return 0;
}
I get the following results:
[Boost] Elapsed time: 12.500 seconds
[Native]Elapsed time: 0.062 seconds
I can't believe multi_arrays are that much slower. Can anyone spot what I am doing wrong?
I assume caching is not an issue since I am doing writes to memory.
EDIT: This was a debug build. Per Laserallan's suggest I did a release build:
[Boost] Elapsed time: 0.266 seconds
[Native]Elapsed time: 0.016 seconds
Much closer. But 16 to 1 still seems to high to me.
Well, no definitive answer, but I'm going to move on and leave my real code with native arrays for now.
Accepting Laserallan's answer because it was the biggest flaw in my test.
Thanks to all.
|
Are you building release or debug?
If running in debug mode, the boost array might be really slow because their template magic isn't inlined properly giving lots of overhead in function calls. I'm not sure how multi array is implemented though so this might be totally off :)
Perhaps there is some difference in storage order as well so you might be having your image stored column by column and writing it row by row. This would give poor cache behavior and may slow down things.
Try switching the order of the X and Y loop and see if you gain anything.
There is some info on the storage ordering here:
http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/user.html
EDIT:
Since you seem to be using the two dimensional array for image processing you might be interested in checking out boosts image processing library gil.
It might have arrays with less overhead that works perfectly for your situation.
|
446,987
| 447,098
|
Windows service to control access to a file in "All Users\Application Data"
|
Here is my situation:
I have an application that use a configuration file. The configuration file applies to all users of the system and all users can make change to the configuration.
I decided to put the configuration file in "All Users\Application Data" folder.
The problem is that the file is writable only by the user who created it.
Here is my temporary solution:
When creating the file, the application set its security options so that it can be written by all users of the system.
However, I think this is a hack and I think I have to create a service that will manage access to the file.
My application is written in C++ (MFC) and I'm not an expert with all the .Net stuff. So my first idea is to write a Windows C++ service with COM interfaces that will be called by the application.
My questions:
Is my idea a good idea or someone knows a better way to do?
Is there any new more up to date way to do a service in Windows than plain C++ and COM?
EDIT:
I know it's easy to set write permission to all users.
Back with Windows XP it was also easy to write files under "Program Files" and registry keys under "HKLM" with a limited user. But now, if you want an application to have the Vista logo certification, you must not write to these location (event if Virtual Stores can 'save' you).
Maybe my final solution will be the "make it writable to all users" one, but my question really is : "Is my solution good or do you have another easier solution that does not rely hacking a behavior fixed by Microsoft".
I'm really sorry to not have made it clear from the beginning.
Thanks a lot,
Nic
|
I wouldn't even bother with COM. Named pipes to your service work fine, too, and it's a lot easier to secure those with ACLs. The service will be so simple I wouldn't even bother with MFC or .NET, pure C++ should be fine. All the heavy lifting is done by your real app; the service just checks if the request piped in are reasonable. (ie. not too big etc.)
|
447,206
| 447,307
|
C++ IsFloat function
|
Does anybody know of a convenient means of determining if a string value "qualifies" as a floating-point number?
bool IsFloat( string MyString )
{
... etc ...
return ... // true if float; false otherwise
}
|
If you can't use a Boost library function, you can write your own isFloat function like this.
#include <string>
#include <sstream>
bool isFloat( string myString ) {
std::istringstream iss(myString);
float f;
iss >> noskipws >> f; // noskipws considers leading whitespace invalid
// Check the entire string was consumed and if either failbit or badbit is set
return iss.eof() && !iss.fail();
}
|
447,352
| 447,450
|
How to know whether we are in a console or a windowed app?
|
Context : programming a c/c++ win32-mfc library
How to know whether we are in a console or a windowed app?
|
You can determine if there is a console currently attached to the process by calling the win32 function GetConsoleWindow. If it returns NULL then there is no console attached to the process. However this will not necessarily tell you if you are running in a windowed app or not. For example I could have a windowed app that uses AllocConsole on start-up to allocate a console for debug output in which case you would have both at the same time. The other problem I can see with what you describe is an application might have no windows and no console attached (A windows service for example).
I'm going to have to agree with litb and Martin on this one as well. If your library needs to know this then it probably isn't decoupled enough. If you are using this to determine where to send debug output for example the best approach would be to use cout or cerr and let the application that is using the library deal with redirecting the stream to where it wants it.
|
447,379
| 447,404
|
What is the use of "delete this"?
|
Today, I have seen some legacy code. In the destructor there is a statement like "delete this". I think, this call will be recursive. Why it is working?
I made some quick search on Y!, I found that if there is a need to restrict the user to create the stack object, we can make destructor private and provide an interface to delete the instance. In the interface provided, we have to call delete on this pointer.
Are there any other situations for using such statements?
|
"delete this" is commonly used for ref counted objects. For a ref counted object the decision of when to delete is usually placed on the object itself. Here is an example of what a Release method would look like [1].
int MyRefCountedObject::Release() {
_refCount--;
if ( 0 == _refCount ) {
delete this;
return 0;
}
return _refCount;
}
ATL COM objects are a prime example of this pattern.
[1] Yes I realize this is not thread safe.
|
447,520
| 457,130
|
What's the recommended workaround if numeric_limits<double>::has_infinity is false?
|
I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with std::numeric_limits<double>::infinity(). However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and std::numeric_limits<double>::has_infinity is false there.
What workaround would you recommend for those platforms?
|
Ok, I have now resorted to using the INFINITY and NAN macros on that particular machine - seems to work fine. They come from math.h.
|
447,854
| 448,050
|
Delete or update a dataset in HDF5?
|
I would like to programatically change the data associated with a dataset in an HDF5 file. I can't seem to find a way to either delete a dataset by name (allowing me to add it again with the modified data) or update a dataset by name. I'm using the C API for HDF5 1.6.x but pointers towards any HDF5 API would be useful.
|
According to the user guide:
HDF5 does not at this time provide an easy mechanism to remove a dataset from a file or to reclaim the storage space occupied by a deleted object.
So simple deletion appears to be out of the question. But the section continues:
Removing a dataset and reclaiming the space it used can be done with the H5Ldelete function and the h5repack utility program. With the H5Ldelete function, links to a dataset can be removed from the file structure. After all the links have been removed, the dataset becomes inaccessible to any application and is effectively removed from the file. The way to recover the space occupied by an unlinked dataset is to write all of the objects of the file into a new file. Any unlinked object is inaccessible to the application and will not be included in the new file. Writing objects to a new file can be done with a custom program or with the h5repack utility program.
|
447,871
| 448,780
|
Cross-thread exception throwing
|
I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is to shut the application down and restart, potentially losing their work. I'd like to add some means where the user, when he realizes that his code is in an infinite loop, can hit a special key, like F10 or something, and the code will break out of the loop. But I'd like to do it without implementing a ton of checks within the script runtime. Optimally, I'd like to have a separate "debugger" thread that's mostly idle, but as one of its tasks it listens for that F10 key, and when it gets the F10 key, it will cause the script runtime thread to throw an exception, so that it will stop executing the script. So my question is, is there a way to have one thread cause another thread to throw an exception? My application is written in C++.
|
It's possible. Detect the keystroke in a separate thread, a hidden window and WM_HOTKEY for example. Call SuspendThread() to freeze the interpreter thread. Now use GetThreadContext() to get the CPU registers of the interpreter thread. Modify CONTEXT.Eip to the address of a function and call SetThreadContext(). Have that function call RaiseException() or throw a C++ exception. ResumeThread() and boom.
|
448,056
| 448,068
|
C++ singleton GetInstance() return
|
When implementing a singleton in C++, is it better for GetInstance() to return a pointer to the singleton object, or a reference? Does it really matter?
|
I prefer a reference. I use reference instead of a pointer whenever I want to document that:
It can't be null
It won't be changed (to point to something else)
It mustn't be deleted
|
448,258
| 448,272
|
Calling virtual method in base class constructor
|
I know that calling a virtual method from a base class constructor can be dangerous since the child class might not be in a valid state. (at least in C#)
My question is what if the virtual method is the one who initializes the state of the object ? Is it good practice or should it be a two step process, first to create the object and then to load the state ?
First option: (using the constructor to initialize the state)
public class BaseObject {
public BaseObject(XElement definition) {
this.LoadState(definition);
}
protected abstract LoadState(XElement definition);
}
Second option: (using a two step process)
public class BaseObject {
public void LoadState(XElement definition) {
this.LoadStateCore(definition);
}
protected abstract LoadStateCore(XElement definition);
}
In the first method the consumer of the code can create and initialize the object with one statement:
// The base class will call the virtual method to load the state.
ChildObject o = new ChildObject(definition)
In the second method the consumer will have to create the object and then load the state:
ChildObject o = new ChildObject();
o.LoadState(definition);
|
(This answer applies to C# and Java. I believe C++ works differently on this matter.)
Calling a virtual method in a constructor is indeed dangerous, but sometimes it can end up with the cleanest code.
I would try to avoid it where possible, but without bending the design hugely. (For instance, the "initialize later" option prohibits immutability.) If you do use a virtual method in the constructor, document it very strongly. So long as everyone involved is aware of what it's doing, it shouldn't cause too many problems. I would try to limit the visibility though, as you've done in your first example.
EDIT: One thing which is important here is that there's a difference between C# and Java in order of initialization. If you have a class such as:
public class Child : Parent
{
private int foo = 10;
protected override void ShowFoo()
{
Console.WriteLine(foo);
}
}
where the Parent constructor calls ShowFoo, in C# it will display 10. The equivalent program in Java would display 0.
|
448,457
| 448,483
|
How to use multiple versions of GCC
|
We have a new application that requires glibc 2.4 (from gcc 4.1). The machine we have runs on has gcc 3.4.6. We can not upgrade, and the application must be run on this machine.
We installed gcc 4.1, however, when it comes to compile time it is using all the includes, etc, from 3.4.6.
How do we get around this?
Any suggestions on using 4.1 for just this application?
|
Refer "How to install multiple versions of GCC" here in the GNU GCC FAQ.
There's also a white paper here.
|
448,671
| 448,730
|
Convert System::DateTime to _timeb
|
I have a legacy C++-based application that timestamps incoming network traffic using the CRT _ftime() function. The _ftime() function returns a _timeb structure, which has a 32-bit and a 64-bit implementation. We are using the 32-bit implementation, which looks like this:
struct _timeb {
long time; // 4 bytes
unsigned short millitm; // 2 bytes
short timezone; // 2 bytes
short dstflag; // 2 bytes
};
From the MSDN documentation, here is how each field is interpreted:
dstflag - nonzero if daylight savings time is currently in effect for the local time zone (see _tzset for an explanation of how daylight savings time is determined.)
millitm - fraction of a second in milliseconds
time - time in seconds since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC).
timezone - difference in minutes, moving westward, between UTC and local time. The value of timezone is set from the value of the global variable _timezone (see _tzset).
I am re-working the portion of the code that does the timestamping to use C# in .NET 3.5. Timestamps are now generated using the System.DateTime structure, but I still need to convert them back to the _timeb structure so the legacy C++ code can operate on them. Here is how I am doing that in my managed C++ bridge library:
DateTime dateTime = DateTime::UtcNow;
DateTime baseTime(1970, 1, 1, 0, 0, 0, DateTimeKind::Utc);
TimeSpan delta = dateTime - baseTime;
_timeb timestamp;
timestamp.time = delta.TotalSeconds;
timestamp.millitm = dateTime.Millisecond;
timestamp.dstflag = TimeZoneInfo::Local->IsDaylightSavingTime(dateTime) ? 1 : 0;
timestamp.timezone = TimeZoneInfo::Local->BaseUtcOffset.TotalMinutes * -1;
From what I can tell, this appears to reconstruct the _timeb structure as if I had called _ftime() directly, and that's good. The thing is, timestamps are a critical piece of our application, so this has to be right.
My question is two-fold.
Is my algorithm flawed somehow? Does anyone see anything obvious that I've missed? Are there boundary conditions where this won't work right?
Is there a better way to do the conversion? Does .NET have a way to do this in a more straightforward manner?
|
You're aware of the Y2K38 problem? I assume you checked the sign of .timezone. Avoid the cleverness of using dateTime.Millisecond, that just confuses the next guy. Looks good otherwise.
|
448,828
| 449,008
|
Quickest way to build a bunch of DLL files with the same settings in VS 2008
|
I'm currently porting a POSIX C++ application to run on Windows without Cygwin or anything. No problem so far. Now, the application (ZNC, an IRC bouncer, in case you're interested) supports loading modules from .so shared library files on Linux/BSD etc.
I ported the main executable without much of a problem, all wrapped into a VS 2008 project file and stuff. Now, said modules are all separate .cpp files which can't be linked into the executable as they all export symbols like GetVersion(). And it isn't feasible anyway.
So, to cut a long story short, I want to (have to) compile all the modules (over 20) into separate DLL files. I don't want to create a single VS project for each however. Which means I'll probably have to create a makefile? Or something the like? I've never done that before on Windows, so that's my question. What is the best approach to compile a bunch of .cpps into separate DLL files (with the same settings, all stored conveniently in one place/file)?
Thanks in Advance!
I.R.
|
As far as I know there is no built in way to do this. So here is what I would do:
Convert one of the modules into a DLL, make sure it works and everything is kosher.
Write a script to generate the other 20 vcproj's from the one reference vcproj that works. I don't know the details of your module system so i'm not sure how strait forward that will be.
Add them into the solution.
Hopefully that works.
|
449,436
| 449,823
|
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
|
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:
SomeBaseClass &SomeClass::GetInstance()
{
static SomeClass instance;
return instance;
}
I see following positive sides of this approach:
The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.
The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.
What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?
|
In C++11 it is thread safe:
§6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
In C++03:
Under g++ it is thread safe.
But this is because g++ explicitly adds code to guarantee it.
One problem is that if you have two singletons and they try and use each other during construction and destruction.
Read this:
Finding C++ static initialization order problems
A variation on this problem is if the singleton is accessed from the destructor of a global variable. In this situation the singleton has definitely been destroyed, but the get method will still return a reference to the destroyed object.
There are ways around this but they are messy and not worth doing. Just don't access a singleton from the destructor of a global variable.
A Safer definition but ugly:
I am sure you can add some appropriate macros to tidy this up
SomeBaseClass &SomeClass::GetInstance()
{
#ifdef _WIN32
Start Critical Section Here
#elif defined(__GNUC__) && (__GNUC__ > 3)
// You are OK
#else
#error Add Critical Section for your platform
#endif
static SomeClass instance;
#ifdef _WIN32
END Critical Section Here
#endif
return instance;
}
|
449,485
| 449,501
|
C++ SQL Sanitization Libraries or Query Builders Offering Sanitization
|
In a project I am working on, I need to insert data into a SQLite3 database via C++. In order to avoid a "little Bobby Tables" incident, I need to sanitize my database inputs. I would like to find a library that does this in C++ rather than rolling my own since that usually leads to issues. Since the application will be inserting ID3 data from MP3's into the database, the need for this is paramount since many artist, album, and song titles include invalid characters.
I found a SO post earlier (can't seem to find it now...) that detailed different query builder libraries for C++, but none of those libraries come straight out and say that they offer sanitization functionality. I'd hate to start implementing one to find out it doesn't have this functionality. There has to be a library out there that does this, but my searches have failed me.
My question is, what libraries are available that will sanitize database input in C++? I don't mind rolling my own, but I'd like to avoid it at all costs. Thanks everyone!
|
Short answer: do not sanitise your input. Use parameterised queries instead. They are safer and faster.
|
449,827
| 449,832
|
Virtual functions and performance - C++
|
In my class design, I use abstract classes and virtual functions extensively. I had a feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?
|
A good rule of thumb is:
It's not a performance problem until you can prove it.
The use of virtual functions will have a very slight effect on performance, but it's unlikely to affect the overall performance of your application. Better places to look for performance improvements are in algorithms and I/O.
An excellent article that talks about virtual functions (and more) is Member Function Pointers and the Fastest Possible C++ Delegates.
|
449,851
| 449,862
|
Why do we need to use `int main` and not `void main` in C++?
|
Why do we need to use int main and not void main in C++?
|
The short answer, is because the C++ standard requires main() to return int.
As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished. Returning a value from main() provides one way for the programmer to specify this value.
|
449,940
| 582,236
|
Is there already some std::vector based set/map implementation?
|
For small sets or maps, it's usually much faster to just use a sorted vector, instead of the tree-based set/map - especially for something like 5-10 elements. LLVM has some classes in that spirit, but no real adapter that would provide a std::map like interface backed up with a std::vector.
Any (free) implementation of this out there?
Edit: Thanks for all the alternative ideas, but I'm really interested in a vector based set/map. I do have specific cases where I tend to create huge amounts of sets/maps which contain usually less than 10 elements, and I do really want to have less memory pressure. Think about for example neighbor edges for a vertex in a triangle mesh, you easily wind up with 100k sets of 3-4 elements each.
|
I just stumbled upon your question, hope its not too late.
I recommend a great (open source) library named Loki.
It has a vector based implementation of an associative container that is a drop-in replacement for std::map, called AssocVector.
It offers better performance for accessing elements (and worst performance for insertions/deletions).
The library was written by Andrei Alexandrescu author of Modern C++ Design.
It also contains some other really nifty stuff.
|
450,107
| 450,129
|
Why does compiling a VCC .sln run in the background with no stdout?
|
I'm trying to compile a project from the command line, like this:
devenv.exe myproj.sln /build release
It looks like the code compiles well, but that's not all I need:
I want to be able to capture the output (e.g. warnings, errors) from the compiler as they occur. Unfortunately as soon as I issue the above command I am returned to the command prompt.
When I look at process-explorer or taskmgr.exe I can see that the devenv.exe process (and a few other sub-processes) working away. If I look in the output folder I can see all of my files gradually appearing.
Is there a way of making VCC work a little bit more like GCC - when I issue a build command or make a project using a Makefile, I get a stream of messages and the console blocks until the process has completed.
Update: Thanks, two excellent solutions. I can confirm that it works.
|
devenv uses this interesting dispatcher that switches between command line mode and windowed mode. There's actually a devenv.com in addition to devenv.exe, and since *.com takes precedence over *.exe, it gets invoked first. devenv.com analyzes the command line and decides what to invoke.
In other words, change your command line to:
devenv myproj.sln /build release
And you should be ok.
|
450,136
| 450,145
|
C++ Custom GUI Button Question
|
I am designing a graphical application for which I've decided to write my own menu. I would like this menu to be platform independent. For the time being, my menu will mostly consist of a number of buttons. My issue involves the handling of events when a button is clicked. My dilemma is with a button "knowing" about the context in which it exists. It seems to me that if there is some larger piece of code that creates buttons and handles mouse events, the need for some type of switch statement might arise. The switch statement would have to invoke the appropriate action based on whatever uniquely defined the button that was clicked.
I would like to avoid this switch statement. My first idea was to have each button maintain a function pointer that it uses to blindly initiate the correct action when it is clicked. This would eliminate any button-specific code. Yet, it bugs me that a button should contain any context-specific information (such as a function pointer). I am fairly inexperienced and I am wondering if this is considered bad design. Regardless, how can I design my menu in a manner which eliminates the need for some type of switch statement and is considered good OOP design? I would like to hear what your preferred solutions are.
Thanks in advance!
|
You can take a look at the
Command Pattern.
You can associate a command to a menu item, the command would contain the code to be executed.
|
450,415
| 450,528
|
Visual Studio: breakpoint excluding calls from a specific function
|
I want to set a breakpoint in unmanaged C++, in Visual Studio 2005, but I would like to ignore this breakpoint if the call stack is in a specific function. Is there a way to do this?
|
If you have a commercial edition of Visual Studio, you should be able to set a breakpoint early in the calling routine, then change its "When Hit..." behaviour to "Run a macro". You'll need to write a macro that programmatically disables the breakpoint in the called function -- use this as the macro to run. (Hopefully someone else can describe how such a macro can be written.) Then set other breakpoints on all exit points of the calling function, and change their behaviour to reenable the breakpoint in the called function.
If you have an Express Edition, you'll find that the "Run a macro" checkbox is greyed out unfortunately. In this case, if you have access to the source code for the calling function, I suggest the following:
Make a global int variable, bp_enabled, initially set to 1.
--bp_enabled on the first line of calling_function().
++bp_enabled at all exit points of calling_function().
Change the "Condition..." properties of the breakpoint in the called function to break only when bp_enabled == 1. (Go to Debug | Windows | Breakpoints, then right-click the breakpoint.)
A bit of a hack, but it gets the job done.
[EDIT: Fixed to work properly even if calling_function() happens to call itself recursively (either directly or indirectly)...]
|
450,471
| 450,531
|
Unknown crash in a C++ Memory Pointers Exercise
|
I recently wrote a program to help me understand the basics of memory pointers in C++, I chose a simple prime number finder.
I finally got it to work. (yay for debugging!)
And I let it run to see how far it goes, it gets to prime #815389 with my verbose tells me is the 65076th prime, I get an app crash. The one thing I could think of was my ints overflowing so I changed them to longs, it gets stuck at the same place.
Would someone be able to help explain what limitation is causing this?
comp: WinVista 64-bit Home Premium, 6GB ram AMD 4800+ X2
program crashes at 4,664K memory usage
Source:
#include <cstdlib>
#include <iostream>
\\\\(Backslashes added for readability)
using namespace std;
long number;
long numnum;
class num;
class num {
public:
long i;
void check();
bool nxt;
num* nxtnum;
};
void num::check() {
if (number % i != 0) {
if (nxt == true) {
(*nxtnum).check();
} else {
nxtnum = new num();
(*nxtnum).i = number;
numnum++;
cout << numnum << ":" << number << ", ";
nxt = true;
};
};
};
int main(long argc, char *argv[]){
numnum = 1;
cout << numnum << ":" << 2 << ", ";
num two;
two.i = 2;
for (number = 3; 1<=1000001; number++) {
two.check();
};
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
};
(Nevermind the username it's just an alias I use so I can keep track of all my posts with google)
|
Sean is right, two.nxt is never initialised. In fact, num.nxt is never initialised for any instance of num. The member nxt is unnecessary if the class is made more robust. The nxt pointer can be used instead:
class num
{
private:
long i;
num *nxtnum;
public:
num (long value) : i (value), nxtnum (0) { }
void check ()
{
if (number % i != 0)
{
if (nxtnum)
{
nxtnum->check ();
}
else
{
nxtnum = new num (number);
cout << ++numnum << ":" << number << ", ";
}
}
};
Of course, the recursive nature is probably the main culprit, the initialisation issue was hidden as you were probably running a debug build. Converting the recursive form to the iterative form is left as an exercise.
|
450,488
| 450,745
|
A Good C++ Library for SOAP
|
What are the alternatives for SOAP development in C++? Which one do you prefer and is most supported/modern?
|
Check out Apache Axis. That is my all times favorite SOAP implementation. It's SOAP done right! Exists for C++ and Java.
http://ws.apache.org/axis/
And in best traditions of Apache Foundation, it is FREE and OPENSOURCE.
So, enjoy!
|
450,558
| 450,582
|
Simplified algorithm for calculating remaining space in a circular buffer?
|
I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?
int remaining = (end > start)
? end-start
: bufferSize - start + end;
|
If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this:
int remaining = (end - start) + (-((int) (end <= start)) & bufferSize);
But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current technique, which is much more readable.
|
450,561
| 450,578
|
How best to implement BCD as an exercise?
|
I'm a beginner (self-learning) programmer learning C++, and recently I decided to implement a binary-coded decimal (BCD) class as an exercise, and so I could handle very large numbers on Project Euler. I'd like to do it as basically as possible, starting properly from scratch.
I started off using an array of ints, where every digit of the input number was saved as a separate int. I know that each BCD digit can be encoded with only 4 bits, so I thought using a whole int for this was a bit overkill. I'm now using an array of bitset<4>'s.
Is using a library class like this overkill as well?
Would you consider it cheating?
Is there a better way to do this?
EDIT: The primary reason for this is as an exercise - I wouldn't want to use a library like GMP because the whole point is making the class myself. Is there a way of making sure that I only use 4 bits for each decimal digit?
|
Just one note, using an array of bitset<4>'s is going to require the same amount of space as an array of long's. bitset is usually implemented by having an array of word sized integers be the backing store for the bits, so that bitwise operations can use bitwise word operations, not byte ones, so more gets done at a time.
Also, I question your motivation. BCD is usually used as a packed representation of a string of digits when sending them between systems. There isn't really anything to do with arithmetic usually. What you really want is an arbitrary sized integer arithmetic library like GMP.
|
450,585
| 450,697
|
Debugging a crash after exiting? (After main returned)
|
This is a fairly involved bug, and I've tried looking around to find other sources of help, but for reasons I don't understand, "Program Crashes in Vista" is not the most helpful query.
The issue I'm having is that the program I'm working on - a graphical, multithreaded data visualization software that uses OpenGL and the Windows API - is crashing after WinMain() returns. I've tried stepping through the shutdown routine as well as looking at a stack trace, and the last bit of code that's not assembly is _crtExitProcess, where it crashes in the actual ExitProcess(0) call. After that, the stack trace shows kernel32.dll and four ntdll.dll, which is where it actually crashes.
This bug only occurs on Vista, and the same exact code when run on XP exits normally. I really can't think of anything that would help me debug this problem, and debugging this issue is something I've never really learned. Any help would be appreciated.
|
I've done a little digging around, and I've found a couple of posts around that suggest you're not the only one suffering from this:
http://developer.nvidia.com/forums/index.php?showtopic=318
http://objectmix.com/xml-soap/115379-problem-latest-ms-patches-msxml4-vista.html
Particularly, the second one is of interest, where Tom Chm mentions:
We believe we have identified the root
cause of our crash, and adding a
virtual destructor to our interface
class wrapper seems to resolve our
problem. But we would like to know the
exact cause of the crash to verify
that we didn't just sweep the actual
problem under the rug.
The problem may be with a destructor somewhere, or lack thereof. If you have a way of attaching a debugger and stepping through the shutdown process, it might be of help.
You might want to read through the whole thread and see if there's something you can learn. That is, if you haven't already found these posts in your searching, of course.
|
450,630
| 450,785
|
Visual C++ 2005 hangs during qt builds
|
At my shop, the main product app is a mongrel built on MFC, QT and other random things devs have thrown in over the years.
In the current stack, Qt toolkit is on the way out, but still features heavily.
If I have SQL 2005 Management studio open and have to do a full build, it usually hangs a CPU (even after the offending process is taken out back and shot...) during the qt specific parts of the build (Moc'ing and UIC'ing)
has anyone seen anything like this? any ideas what the problem could be?
|
In my experience, some of these tools are capable of looping forever (qt4: lupdate/lrelease for sure).
|
450,832
| 451,220
|
How do I make Microsoft VCC crash out on the first build-error?
|
My automated build process uses a command-line to build something like this:
devenv.exe myproj.sln /build release
It is a very long build-process which integrates components made by a team of developers. It takes about half an hour to run in release mode. Usually if one thing goes wrong then plenty of other dependancies will go wrong, so I occasionally get a message like:
---------------------- Done ----------------------
Rebuild All: 18 succeeded, 6 failed, 0 skipped
Actually I want the build to abort as soon as the first error is found. If there are any errors at all the build has failed. I need to know this as soon as possible and not wait to see all the other stuff fail.
Is there a way to change the build-process so that instead of running through the whole thing it dies as soon as something goes wrong?
I'm using Visual Studio .Net 2003 (yes I know it's old).
|
I use the following macro in Visual Studio 2005 to do this, but it should also work in 2003. Add this to the EnvironmentEvents module in the Macros IDE:
Private Sub BuildEvents_OnBuildProjConfigDone(ByVal Project As String, ByVal ProjectConfig As String, ByVal Platform As String, ByVal SolutionConfig As String, ByVal Success As Boolean) Handles BuildEvents.OnBuildProjConfigDone
If Success = False Then
DTE.ExecuteCommand("Build.Cancel")
End If
End Sub
This will cause the build to cancel when any single project fails to build.
This page has further details on the macros involved.
|
451,102
| 451,129
|
How to work with the data in Binary in C/C++
|
I have to do some work work with integers, but I am interested in treat them as binary data, in a way that for example I can take the 4 most significant bits of an 32 bit value. What I am trying to do is, I have several 32 bit value I want to take for example, in the first one 4 bits, the second one 6 bits and the last one 22 bits, and after concatenate them and get another 32 bits value.
Can anyone please recommend any library or any othe way to do this?. Thank you.
|
It seems that you don't need a library for that. Just bit shifting, logical and, or and xor should be sufficient for what you want to do.
EDIT: Just to give an example. Suppose a is a 32-bit int, and you want to take the first 4 bit and store it in the lowest bit positions in another integer b, you could do this:
b = (a & (0xf << (31-4))) >> (31-4)
|
451,126
| 451,212
|
How to define an object whose address is null?
|
I am wondering how I can define an object in C whose reference will be null?
// definition of foo
...
void * bar = &foo; // bar must be null
There is some ways I could find to do it, but none fit my needs.
__attribute__((weak)) extern int foo; //not working with cygwin/gcc 3.4
__attribute__((at(0))) int foo; //only with rvds
#define foo (*(int*) 0) //cannot be embedded in a macro
Actually, I would prefer a standard compliant solution (c99), but anything working
will be ok.
Edited: The reason to do this is that bar will not always be null. Here is a more relevant example:
// macro that will define foo to a real object or to *null
DECL(foo);
int * bar = &foo;
if(bar) {
// we can call func
func(bar);
} else {
// bar undefined
exit(-1);
}
Of course this is still not very relevant, because I can use #if in my condition. The project involves in fact big structures, a lot of files, a few compilers, some cpu targets, and many programmers who generate bugs with a probability exponential to the complexity of the syntax they use. It is why I would like a simple macro to declare my foo object.
|
You are trying to create a symbol with an address of zero. Your last example is probably the only way of doing this within the C compiler / language.
The approach that is most likely to solve your problem is to look at the input file to the linker program. Most linkers allow you to define the label foo as zero.
In a unix ld script this is just:
foo = 0 ;
|
451,475
| 451,553
|
How to print out dash or dot using fprintf/printf?
|
As of now I'm using below line to print with out dot's
fprintf( stdout, "%-40s[%d]", tag, data);
I'm expecting the output would be something like following,
Number of cards..................................[500]
Fixed prize amount [in whole dollars]............[10]
Is this a high winner prize?.....................[yes]
How to print out dash or dot using fprintf/printf?
|
A faster approach:
If the maximum amount of padding that you'll ever need is known in advance (which is normally the case when you're formatting a fixed-width table like the one you have), you can use a static "padder" string and just grab a chunk out of it. This will be faster than calling printf or cout in a loop.
static const char padder[] = "......................"; // Many chars
size_t title_len = strlen(title);
size_t pad_amount = sizeof(padder) - 1 - title_len;
printf(title); // Output title
if (pad_amount > 0) {
printf(padder + title_len); // Chop!
}
printf("[%d]", data);
You could even do it in one statement, with some leap of faith:
printf("%s%s[%d]", title, padder + strlen(title), data);
|
451,534
| 454,545
|
Good logging library for managed/unmanaged application?
|
What logging library or approach would you recommend for this case:
We want to be able to log both from managed and unmanaged code
For the unmanaged code, the implementation should not cross back into managed code, because this could cause our unmanaged threads to get 'caught' during a garbage collection.
Performance is a concern
NLog provides a "C" api, but implements it in terms of its managed implementation.
Many of the C logging libraries out there (rlog, glog) are reliant on macros + preprocessing and are not amenable to wrapping with .NET without extensive modification.
I guess I'm looking for something with a native/unmanaged logging core, but a decent .NET managed api as well. Does this exist? If this doesn't exist, what comes the closest?
Followup - Thanks for the responses mentioning log4net. I think Log4Net and NLog both perform ok in a pure managed application, -but-... The app I've been asked to build has unmanaged I/O on a background thread that absolutely cannot afford to be stopped by a garbage collection. If unmanaged c++ code has to call "up" into a managed logger, it stands a chance of being frozen for 200 or even 2000 milliseconds while the garbage collection occurs. That's why I'm looking for a library that is unmanaged at its core. - Dave
|
Pantheios might meet your requirements. It's open-source.
|
451,595
| 451,669
|
Blocking the standard error output of a programmatically run system command
|
I have this program in c++:
#include <iostream>
using namespace std;
int main()
{
char buf[50];
cin.getline(buf,49);
system(buf);
return 0;
}
When I run and compile it and type for example "helo", my program prints the error:
"helo" not found.
Can I stop this error from being displayed? Is there any way to disable the error from the system command?
|
You can't change the way system displays errors. C and C++ put very little to no requirements on implementations in that regard, so that large parts of it are left unspecified, to allow them to be as flexible as possible.
If you want more precise control, you should use the functions of your runtime library or operation system interface. Try execvp (see man execvp) in linux/unix or the CreateProcess function for windows systems, which uses the Windows API that allows great control over error handling and other stuff.
|
451,749
| 451,888
|
Is there a TRACE statement for basic win32 C++?
|
In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?
|
_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.
Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. Thanks to Thomas Rizos for the original:
// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873
#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#ifdef _DEBUG
#define TRACEMAXSTRING 1024
char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
va_list args;
va_start(args,format);
int nBuf;
nBuf = _vsnprintf(szBuffer,
TRACEMAXSTRING,
format,
args);
va_end(args);
_RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
&strrchr(__FILE__,'\\')[1],__LINE__); \
_RPT0(_CRT_WARN,szBuffer); \
TRACE
#else
// Remove for release mode
#define TRACE ((void)0)
#define TRACEF ((void)0)
#endif
#endif // __TRACE_H__850CE873
|
451,884
| 514,311
|
Similar String algorithm
|
I'm looking for an algorithm, or at least theory of operation on how you would find similar text in two or more different strings...
Much like the question posed here: Algorithm to find articles with similar text, the difference being that my text strings will only ever be a handful of words.
Like say I have a string:
"Into the clear blue sky"
and I'm doing a compare with the following two strings:
"The color is sky blue" and
"In the blue clear sky"
I'm looking for an algorithm that can be used to match the text in the two, and decide on how close they match. In my case, spelling, and punctuation are going to be important. I don't want them to affect the ability to discover the real text. In the above example, if the color reference is stored as "'sky-blue'", I want it to still be able to match. However, the 3rd string listed should be a BETTER match over the second, etc.
I'm sure places like Google probably use something similar with the "Did you mean:" feature...
* EDIT *
In talking with a friend, he worked with a guy who wrote a paper on this topic. I thought I might share it with everyone reading this, as there are some really good methods and processes described in it...
Here's the link to his paper, I hope it is helpful to those reading this question, and on the topic of similar string algorithms.
|
I can't mark two answers here, so I'm going to answer and mark my own. The Levenshtein distance appears to be the correct method in most cases for this. But, it is worth mentioning j_random_hackers answer as well. I have used an implementation of LZMA to test his theory, and it proves to be a sound solution. In my original question I was looking for a method for short strings (2 to 200 chars), where the Levenshtein Distance algorithm will work. But, not mentioned in the question was the need to compare two (larger) strings (in this case, text files of moderate size) and to perform a quick check to see how similar the two are. I believe that this compression technique will work well but I have yet to study it to find at which point one becomes better than the other, in terms of the size of the sample data and the speed/cost of the operation in question. I think a lot of the answers given to this question are valuable, and worth mentioning, for anyone looking to solve a similar string ordeal like I'm doing here. Thank you all for your great answers, and I hope they can be used to serve others well too.
|
451,983
| 451,997
|
Why won't cout << work with overloaded * operator?
|
I'm creating my first class, mainly guided by Overland's C++ Without Fear. I've made the overloaded friend ostream operator<<, which works fine. I've also overloaded the * operator, and that works fine. What doesn't work is when I try to output the result of the * operator directly:
BCD bcd(10); //bcd is initialised to 10
BCD bcd2(15); //bcd2 is initialised to 15
cout << bcd; //prints 10
bcd2 = bcd2 * 2; //multiplies bcd2 by 2
cout << bcd2; //prints 30
cout << bcd * 2 //SHOULD print 20, but compiler says
//main.cpp:49: error: no match for 'operator<<' in 'std::cout << BCD::operator*(int)(2)'
For info, here are my prototypes:
BCD operator*(int z);
friend ostream &operator<<(ostream &os, BCD &bcd);
As far as I can tell, operator* returns a BCD, so operator<< should be able to print it. Help please!
|
What's happening is that bcd * 2 is generating a temporary BCD, which cannot bind to a BCD &. Try replacing the << operator with one of these:
friend ostream &operator<<(ostream &os, const BCD &bcd);
or
friend ostream &operator<<(ostream &os, BCD bcd);
or even
friend ostream &operator<<(ostream &os, const BCD bcd);
The first one works, since binding a temporary variable to a constant reference is explicity allowed, unlike binding to a non-const reference. The other ones work by making a copy of the temporary variable.
Edit:
As noted in the comments - prefer the const & version in most cases, since modifying an object in a streaming operator will be surprising to anyone using your class. Getting this to compile may require adding const declarations to your classes member function where appropriate.
|
452,390
| 452,417
|
Best way to organize a class hierarchy including an overridable "Update" function
|
I have a base class "Foo" that has an Update() function, which I want to be called once per frame for every instance of that class. Given an object instance of this class called "foo", then once per frame I will call foo->Update().
I have a class "Bar" derived from my base class, that also needs to update every frame.
I could give the derived class an Update() function, but then I would have to remember to call its base::Update() function - nothing enforces my requirement that the base::Update() function is called because I have overriden it, and could easily just forget to (or choose not to) call the base:Update function.
So as an alternative I could give the base class a protected OnUpdate() function, which could be made overrideable, and call it from the base::Update() function. This removes the onus on me to remember to call base::Update() from the derived update function because I'm no longer overriding it. A Bar instance called "bar" will have bar->Update() called on it; this will first call the base class' Update() method, which will in turn call the overriden OnUpdate() function, performing the derived class' necessary updates.
Which solves everything. Except. What if I want to derive yet another updatable class, this time from the "Bar" class.
Baz (which derives from Bar) also has update requirements. If I put them in Baz's OnUpdate() function, I'm back to the original problem in that I'd have to remember to tell Baz's OnUpdate() function to call Bar's OnUpdate() function, otherwise Bar's OnUpdate() function wouldn't get called.
So really, I'd want Bar's OnUpdate() function to be non-overridable, and instead for it to call an overridable function after it has done whatever it needed to do, perhaps called OnUpdate2()...
And if I wanted to derive yet another class? OnUpdate3? OnUpdate4? AfterUpdate?
Is there a Better Way?
Further Info:
My specific problem domain is a 3d world. I've decided my base class is a "Locator" (an object with a location and orientation).
My first derived class is a "PhysicsObject" - a Locator that also has mass, velocity, collision information, etc.
My next derived class is a "Camera" - which derives from PhysicsObject. As well as position, and velocity, it also has information about the viewport, depth of field, etc.
MattK suggests simplifying the hierarchy - if a Locator is never referred to, incorporate it into PhysicsObject.
I'm also thinking about how I would go about turning the layout upside down and using composition instead of inheritance.
Perhaps a Camera HAS physics properties.
Perhaps a PhysicsObject HAS a location.
I'll have to think some more about this problem.
I like Uri's approach: "Observe the contract." Here's the rule - please follow it. Uri is right in that whatever kind of safeguards I try to put in, anyone could circumvent them, so perhaps in this case, the simplest solution is best. All my update() functions are going to have the requirement of calling their base::update() function.
Thanks for the help everyone!
|
That's a great question, I've encountered it many many times.
Unfortunately, there are at present no language mechanisms that I am familiar with for mainstream languages like C++ to do that, though I expect (at least in the future) for Java to have something with annotations.
I've used a variety of techniques including what you've suggested, each with pros and cons. Convulted approaches are not always worth the cost.
My view today is that if you really need to use inheritance (rather than composition), as it sounds here, then it is better to go for the elegant solution and observe the written contract. I admit, it's dangerous, but there are risks to the other approaches as well.
Generally speaking people are more careful reading the documentation of an overridden method than they are of a method they are using. In other words, while you would want to avoid "surprising" the user of your class, and can't count on him reading docs, you can count a little more on that in the case of inheritance, especially if you are the only user.
If you are presenting an API function and you expect many other individuals to override your subclass, you could put all kinds of sanity checks to ensure that the method was called, but in the end, you have to rely on the contract, just as so many standard library classes do.
|
452,435
| 452,456
|
Is there a way to programmatically hide an carbon application on osx?
|
I have a carbon C++ application and I would like to programmatically do the equivalent of Command-H (to hide the application) which is available in the Application menu for my app. I have explored the carbon API for TransitionWindow and HideWindow and while these can hide my window, they do not do the equivalent of Command-H. I looked into the AppleEvent reference on the offhand I needed to create an AppleEvent but I didn't see one for hide application. Any thoughts?
|
Sorry to answer my own question but the ShowHideProcess() API seems to do what I want. If there are better solutions I would love to hear them.
|
452,498
| 453,327
|
When are constructors called?
|
If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined?
If I define another instance of a class globally within the file does that constructor get called when executable is first loaded? What if multiple threads are accessing the .dll?
Finally is you answer going to be the same in .dll, .so, .exe and linux executables?
|
If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined?
Such variables have local scope. Their constructor is called when they're defined. For local statics, the constructor is only called once, since the statics will survive multiple function calls and returns. The order is important, and is the order of definition:
void foo() {
....
if(cond) {
...
// called here: first for f, then for b
static Foo f;
static Bar b;
}
...
Foo f; // not static: called here, in every invocation of foo.
}
If I define another instance of a class globally within the file does that constructor get called when executable is first loaded?
Yes, such variable is said to have static storage duration, and namespace scope. Its constructor is called at program start. The order is the order it is defined in the file. That is, a variable defined later will have its ctor called later. The order in which variables defined in different translation units is not defined (look-out for the static initialization order fiasco). But they are all called at program start.
What if multiple threads are accessing the .dll?
All bets are off. The variable is only constructed once. After that, when you start threads and access it, the variable has to be thread safe, or the threads has to do proper locking when accessing the variable.
|
452,771
| 452,789
|
Create an array of class objs
|
Consider following class
class test
{
public:
test(int x){ cout<< "test \n"; }
};
Now I want to create array of 50 objects of class test . I cannot change class test.
Objects can be created on heap or stack.
Creating objs on stack is not possible in this case since we dont have default constructor in class
test objs(1)[50]; /// Error...
Now we may think of creating objs on heap like this..
test ** objs = NULL;
objs = (test **) malloc( 50 * sizeof (test *));
for (int i =0; i<50 ; ++ i)
{
objs[i] = new test(1);
}
I dont want to use malloc .Is there any other way??
If you guys can think of some more solutions , please post them...
|
You cannot create an array of objects, as in Foo foo [N], without a default constructor. It's part of the language spec.
Either do:
test * objs [50];
for() objs[i] = new test(1).
You don't need malloc(). You can just declare an array of pointers.
c++decl> explain int * objs [50]
declare objs as array 50 of pointer to int
But you probably ought to have some sort of automatic RAII-type destruction attached.
OR subclass test publicly:
class TempTest : public test
{
public:
TempTest() : test(1) {}
TempTest(int x) : test(x) {}
TempTest(const test & theTest ) : test(theTest) {}
TempTest(const TempTest & theTest ) : test(theTest) {}
test & operator=( const test & theTest ) { return test::operator=(theTest); }
test & operator=( const TempTest & theTest ) { return test::operator=(theTest); }
virtual ~TempTest() {}
};
and then:
TempTest array[50];
You can treat every TempTest object as a test object.
Note: operator=() & copy constructor are not inherited, so respecify as necessary.
|
453,045
| 453,072
|
Service Crash loading dll
|
I have made a new windows service which works fine using barebone code (just the basic framework for a service), however, when i link it against my dlls, lib file to use the functionality in the dll it crashes on start up with a 0xc0000034 error.
Is there a special place to put the dlls for a service or a special way to do this?
.
Edit: i have all dlls it needs in the same folder as the exe but i will try moving them to the system32 folder. I think it might be a conflict caused by my memory leak detector (vld) and the service, will have to do some more debugging and trial and error.
.
Edit 2:
Found out what was causing it. It was missing dbghelp.dll (used dependency walker to work it out). Thanks for the input.
|
0xc0000034 stands for STATUS_OBJECT_NAME_NOT_FOUND, which suggests a missing file.
Are you placing the dlls in correct path?
EDIT: I think, as it is win service, path to the dll that it loads should be absolute path or it should be in PATH environmental variable(COM servers works like that)
Just copy the dlls to the System32 directory and check whether it fixes the problem.
|
453,099
| 453,104
|
Size of static array
|
I declare a static char array, then I pass it to a function. How to get the no. of bytes in the array inside the function?
|
You would have to pass it to the function. You can use sizeof() to get the size of an array.
const char foo[] = "foobar";
void doSomething( char *ptr, int length)
{
}
doSomething(foo, sizeof(foo));
This MSDN page has explains more about sizeof and has a bigger example.
Edit: * see j_random_hacker's answer for an intriguing technique using templates... *
|
453,293
| 454,448
|
c++; things to take care in multicore environment
|
What are all the things one needs to be careful about when coding in a multicore environment?
For example, for a singleton class, it is better to create a global object and then return its reference than a static object.
i.e
Rather than having
MyClass & GetInstance()
{
static Myclass singleMyclass;
return singleMyclass;
}
It is better to have
Myclass singleMyclass;
MyClass & GetInstance()
{
return singleMyclass;
}
GetInstance() might be called by many threads simultaneously.
Edit:
My question was about the hidden constructs of c++ one must be aware of while using them in multithreaded program. In above case static is not thread safe as compiler adds some instructions for static objects, which is not thread safe. I am looking for similar constructs one should be aware of.
|
My first answer addressed your example of singleton initialisation, but as you emphasised in an edit to your question, you are after more general pit falls of C++ as we move to multi-core and multi-threaded applications. The following is a real surprise when you first encounter it. Though not C++ specific, it definitely affects C++ code.
Out of order execution and Memory Barriers (or fences):
One gotcha is out of order execution. It is possible for threads to see operations of other threads executing on different cores out of order due to modern hardware allowing out of order execution optimisation. As a result, multi-threaded coded that runs correctly on a single-core machine may in fact be incorrect on a multi-core machine.
A naive solution to such problems is to increase the scope of critical sections. Another is to use memory barriers or lock-free algorithms.
|
453,372
| 453,387
|
Writing function definition in header files in C++
|
I have a class which has many small functions. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like:
string Foo::method() const{
return "A";
}
I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small, I am thinking about putting it in the header file itself. I have the following questions:
Is there any performance or other issues if I put these function definition in header file? I will have many functions like this.
My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?
|
If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same address for every compilation unit:
headera.h:
inline string method() {
return something;
}
Member functions are implicit inline provided they are defined inside their class. The same stuff is true for them true: If they can be put into the header without hassle, you can indeed do so.
Because the code of the function is put into the header and visible, the compiler is able to inline calls to them, that is, putting code of the function directly at the call site (not so much because you put inline before it, but more because the compiler decides that way, though. Putting inline only is a hint to the compiler regarding that). That can result in a performance improvement, because the compiler now sees where arguments match variables local to the function, and where argument doesn't alias each other - and last but not least, function frame allocation isn't needed anymore.
My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?
Yes, that is correct. The function will be defined in every place where you include its header. The compiler will care about putting only one instance of it into the resulting program, by eliminating the others.
|
453,407
| 453,595
|
What do *you* use C++ ABC constructors for?
|
What do people here use C++ Abstract Base Class constructors for in the field? I am talking about pure interface classes having no data members and no non-pure virtual members.
Can anyone demonstrate any idioms which use ABC constructors in a useful way? Or is it just intrinsic to the nature of using ABCs to implement interfaces that they remain empty, inline and protected?
|
Can anyone demonstrate any idioms which use ABC constructors in a useful way?
Here's an example, although it's a contrived, uncommon example.
You might use it to keep a list of all instances:
class IFoo
{
private:
//static members to keep a list of all constructed instances
typedef std::set<IFoo*> Set;
static Set s_set;
protected:
//new instance being created
IFoo()
{
s_set.insert(this);
}
public:
//instance being destroyed
virtual ~IFoo()
{
s_set.remove(this);
}
... plus some other static method and/or property
which accesses the set of all instances ...
};
Or is it just intrinsic to the nature of using ABCs to implement interfaces that they remain empty, inline and protected?
More usually they're just not declared at all! There's no reason to declare them:
Empty and inline => why bother to declare it?
Protected => the ABC probably already has some pure virtual methods and therefore already can't be instantiated except as a subclass.
|
453,432
| 453,462
|
Difference in initializing and zeroing an array in c/c++?
|
In c (or maybe c++) , what's the difference between
char myarr[16]={0x00};
and
char myarr[16];
memset(myarr, '\0', sizeof(myarr));
??
edit: I ask this because in vc++ 2005 the result is the same..
edit more :
and
char myarr[16]={0x00,}; ?
maybe can get more comprehensive answer and not ambiguous as some answers below refer to this kind of code,ie.
put comma just before closing curly braces. Also the result is the same in vc++ 2005.
|
The important difference is that the first default initializes the array in an element-specific manner: Pointers will receive a null pointer value, which doesn't need to be 0x00 (as in all-bits-zero), booleans will be false. If the element type is a class type that's not a so-called POD (plain old data-type), then you can only do the first one, because the second one only works for the simplest cases (where you don't have virtual functions, user defined constructors and so on). In contrast, the second way using the memset sets all elements of the array to all-bits-zero. That is not always that what you want. If your array has pointers for example, they won't be set to null-pointers necessarily.
The first will default initialize the elements of the array, except for the first one, which is set to 0 explicitly. If the array is local and on the stack (that is, not a static), the compiler internally often does a memset to clear the array out. If the array is non-local or static, the first version can be considerably more efficient. The compiler can put the initializers already, at compile time, into the generated assembler code, making it require no runtime code at all. Alternatively, the array can be laid out on a section that is automatically zero'd out (also for pointers, if they have a all-bits-zero representation) when the program starts in a fast manner (i.e page-wise).
The second does a memset explicitly over the whole array. Optimizing compilers will usually replace a memset for smaller regions with inline machine code that just loops using labels and branches.
Here is assembler-code generated for the first case. My gcc stuff isn't much optimized, so we got a real call to memset (16 bytes at the stack-top are always allocated, even if we got no locals. $n is a register number):
void f(void) {
int a[16] = { 42 };
}
sub $29, $29, 88 ; create stack-frame, 88 bytes
stw $31, $29, 84 ; save return address
add $4, $29, 16 ; 1st argument is destination, the array.
add $5, $0, 0 ; 2nd argument is value to fill
add $6, $0, 64 ; 3rd argument is size to fill: 4byte * 16
jal memset ; call memset
add $2, $0, 42 ; set first element, a[0], to 42
stw $2, $29, 16 ;
ldw $31, $29, 84 ; restore return address
add $29, $29, 88 ; destroy stack-frame
jr $31 ; return to caller
The gory details from the C++ Standard. The first case above will default-initialize remaining elements.
8.5:
To zero-initialize storage for an object of type T means:
if T is a scalar type, the storage is set to the value of 0 (zero) converted to T;
if T is a non-union class type, the storage for each nonstatic data member and each base-class subobject is zero-initialized;
if T is a union type, the storage for its first data member is zero-initialized;
if T is an array type, the storage for each element is zero-initialized;
if T is a reference type, no initialization is performed.
To default-initialize an object of type T means:
if T is a non-POD class type, the default constructor for T is called
if T is an array type, each element is default-initialized;
otherwise, the storage for the object is zero-initialized.
8.5.1:
If there are fewer initializers in the list than there are members in the aggregate,
then each member not explicitly initialized shall be default-initialized (8.5).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.