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
1,482,908
1,482,916
Confusion in exception handling
Consider the following program #include <iostream> #include<cstdlib> using namespace std; class E { public: const char* error; E(const char* arg) : error(arg) { } }; void my_terminate() { cout << "Call to my_terminate" << endl; } struct A { A() { cout << "In constructor of A" << endl; } ~A(){ cout << "In destructor of A" << endl; throw E("Exception thrown in ~A()"); } }; struct B { B() { cout << "In constructor of B" << endl; } ~B() { cout << "In destructor of B" << endl; } }; int main() { set_terminate(my_terminate); try { cout << "In try block" << endl; A a; B b; throw E("Exception thrown in try block of main()"); // Line 36 } catch (E& e) { cout << "Exception: " << e.error << endl; } catch (...) { cout << "Some exception caught in main()" << endl; } cout << "Resume execution of main()" << endl; } Output: In try block In constructor of A In constructor of B In destructor of B In destructor of A Call to my_terminate Disallowed system call: SYS_kill In line 36 an exception is thrown from the try block in main. Now why is this exception not caught by the handler? Rather the 'stack unwinding' process continues.The destructor of A throws an exception too which is again not caught by any handler,instead a call to my_terminate is made, why? Why is the handler not called in the two cases?
The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. You throw an exception in A's destructor, which is something you are not supposed to do.
1,482,998
1,483,079
Best way to deal with object that can't instantiate itself?
I guess I've asked a few similar questions before, but I was beating around the bush. I think this is the real problem that I can't quite lay to rest. I'm dealing with a third party library, and there's an object that can't create itself, b2Body. The b2World has to instantiate it. I personally don't like this design pattern very much; I think the b2Body should be able to exist independently of the world, and then be added to the world when needed. Anyway, I've wrapped b2Body with my own class class, Body, because I need to add some extra stuff to it anyway. Similarly, I have a World wrapper. Now I figure I have 3 options: Have Body's constructor takes a pointer to World so that it can be fully instantiated (calls b2World::CreateBody somewhere inside) -- i.e. have a constructor like Body *b = new Body(world_ptr) Pass Body to some World::CreateBody method like how the library already does it -- i.e. Body *b = world.CreateBody(params); Duplicate all the data in b2Body so that you can use it however you want, and then after you add it to the world it will 'switch over' to use the b2Body data -- i.e. Body b and later world.addBody(b). (1) and (2) mean that you can't have a Body without a World, which I probably won't need, but it might be nice to have that option [so that I can use it as a template for other objects and such]. Not sure what other pros and cons there are. (3) seems nicer, but it's a lot more work to implement, and it means I have to duplicate most of the data that's already contained in b2Body. What are your thoughts? I'll CW this just so no one frets. I still can't lay this to rest. This is what each of the options would look like: Option 1: (what I prefer) World w; Body b; Fixture f; b.addFixture(f); w.addBody(b); Option 2: (somewhere in the middle) World w; Body b(w); Fixture f(b); Option 3: (how Box2D does it) World *w = new World; Body *b = w->CreateBody(args); Fixture *f = b->CreateFixture(args); Options 2 and 3 aren't so different, but it changes who has control over is creating the objects. How would I actually implement option 3 though? World::CreateBody() has to call b2World::CreateBody(args) which calls b2Body::b2Body() and returns b2Body but never calls Body::Body(args) which is a problem. The b2Body would get fully initialized, but my wrapper has no place to do it's thing... More specifically, how would I write World::CreateBody(const BodyDef &bd)? Assuming BodyDef inherited from b2BodyDef, Body from b2Body, World from b2World, etc.
I think, if you're going to use a third-party library, you should only fight its design if you have a much better reason than oh, I don't like that design pattern much. Your library has a way of doing things — apparently, by using a factory object — and fighting that will increase your code complexity, possibly substantially.
1,483,068
1,483,578
How to get a CString object from a file with CFile::Read() in Unicode?
The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards. I write the string into a file with CFile::Write() method: int nLen = strSample.GetLength()*sizeof(TCHAR); file.Write(strSample.GetBuffer(), nLen); Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it? Thank you very much!
UINT nBytes = (UINT)file.GetLength(); int nChars = nBytes / sizeof(TCHAR); nBytes = file.Read(strSample.GetBuffer(nChars), nBytes); strSample.ReleaseBuffer(nChars);
1,483,344
1,483,369
How to use double buffer in this case?
Let's say i have three control A, B, C. They are all inherited from CDialog, A is a main dialog , A contains B, and B contains C. and each time i use mouse mouse drag C, B and C will move together. This is a image:http://img507.imageshack.us/img507/7039/31709956.jpg We know this will cause B and C to redraw themselves. and it might cause flicker. And my question is whether not there is a method to double buffer these two dialogs B and C? I know that in XP and vista, there is a attribute WS_EX_COMPOSITED that will help, but i don't want to use this. someone might suggest me to use memDC, but my problem is how can i merge the actions in B's ondraw and C's ondraw function into a buffer ? Hope someone know what i said. Thanks in advance!
what helpes flickering a lot is to overload the erasebackground method. This method fills the entire background with a solid color. The paint than paints all items on it. By removing the erasebackground, the paint will just paint over stuff which is already there, thus removing flickering.
1,483,403
1,483,441
Are standard output streams in C++ thread-safe (cout, cerr, clog)?
I know that there is no concept of threads in current C++, but this article is saying: A typesafe, threadsafe, portable logging mechanism ..... The fprintf() function is threadsafe, so even if this log is used from different threads, the output lines won't be scrambled. What about cout, cerr and clog? I think this question is applicable to all kind of stream types in C++ also, like fstream and stringstream.
The article makes a claim about the POSIX standard for the fprintf API. It says nothing about C++ streams. And this is quite correct, as there are no such guarantees on those stream. Note that although the logging class in that article uses C++ stream syntax, it does this via a std::ostringstream object that is created and destroyed for every logging event, and so is not shared between threads. It uses fprintf to actually write the content to the console. The Microsoft C library makes some claims to be POSIX compliant, and so the code in the article probably is quite widely portable (as many other popular operating systems are POSIX compliant). But this doesn't mean that standard C++ streams are thread-safe.
1,483,491
1,483,498
C++: Including header-file fails compilation but including source cpp file compiles
This is probably really simple, but it's hindering me on my way down c++ road. I am currently reading through accelerated c++ and I decided to overkill one of the exercises. It all worked well and my code ran fine until I split it into a header and separate source file. When I import my .cpp source file containing some functions I wrote, everything runs fine. But when I try to import the functions through a header file it fails horribly and I get the following error. I am compiling with gcc from Geany, it's all worked fine until now. Thanks for any help. error: g++ -Wall -o "quartile" "quartile.cpp" (in directory: /home/charles/Temp) Compilation failed. /tmp/ccJrQoI9.o: In function `main': quartile.cpp:(.text+0xfd): undefined reference to `quartile(std::vector<double, std::allocator<double> >)' collect2: ld returned 1 exit status "stats.h": #ifndef GUARD_stats_h #define GUARD_stats_h #include <vector> std::vector<double> quartile(std::vector<double>); #endif "stats.cpp": #include <vector> #include <algorithm> #include "stats.h" using std::vector; using std::sort; double median(vector<double> vec){ //code... } vector<double> quartile(vector<double> vec){ //code and I also reference median from here. } "quartile.cpp": #include <iostream> #include <vector> #include "stats.h" //if I change this to "stats.cpp" it works using std::cin; using std::cout; using std::vector; int main(){ //code and reference to quartile function in here. }
Compilation fails, because you have only declared this function. Its definition is in different compilation unit, and you're not linking those two together. Do g++ -Wall -o quartile quartile.cpp stats.cpp and it'll work.
1,483,566
1,483,602
Activating an application as a child/popup of another application
Under Windows XP, is it possible to execute a 3rd party application, so its main window will be a child/popup window of my VC++ MFC application? I want to control it's Z-Order like any other window in my app I don't want it be be visible in the taskbar I want to catch its WM_CLOSE and handle it in my app In general, I want my users to feel that this is just another dialog in my application.
Here is an example on hosting other applications in your application: Hosting .exe applications into a dialog Also you may want to check out hooks and specifically the WH_CALLWNDPROC if you want to monitor all messages.
1,483,941
1,483,967
C++ class to access bytes/words of an unsigned integer
union LowLevelNumber { unsigned int n; struct { unsigned int lowByte : 8; unsigned int highByte : 8; unsigned int upperLowByte : 8; unsigned int upperHighByte : 8; } bytes; struct { unsigned int lowWord : 16; unsigned int highWord : 16; } words; }; This union allows me to access the unsigned integer byte or word-wise. However, the code looks rather ugly: var.words.lowWord = 0x66; Is there a way which would allow me to write code like this: var.lowWord = 0x66; Update: This is really about writing short / beautiful code as in the example above. The union solution itself does work, I just don't want to write .words or .bytes everytime I access lowWord or lowByte.
union LowLevelNumber { unsigned int n; struct { unsigned int lowByte : 8; unsigned int highByte : 8; unsigned int upperLowByte : 8; unsigned int upperHighByte : 8; }; struct { unsigned int lowWord : 16; unsigned int highWord : 16; }; }; Note the removed bytes and words names.
1,483,990
1,484,003
read words from line in C++
I was wondering if there was a way to read all of the "words" from a line of text. the line will look like this: R,4567890,Dwyer,Barb,CSCE 423,CSCE 486 Is there a way to use the comma as a delimiter to parse this line into an array or something?
Yes, use std::getline and stringstreams. std::string str = "R,4567890,Dwyer,Barb,CSCE 423,CSCE 486"; std::istringstream iss(str); std::vector<std::string> words; while (std::getline(iss, str, ',')) words.push_back(str);
1,484,021
1,484,037
Is a bit field any more efficient (computationally) than masking bits and extracting the data by hand?
I have a numerous small pieces of data that I want to be able to shove into one larger data type. Let's say that, hypothetically, this is a date and time. The obvious method is via a bit field like this. struct dt { unsigned long minute :6; unsigned long hour :5; unsigned long day :5; unsigned long month :4; unsigned long year :12; }stamp; Now let's pretend that this thing is ordered so that things declared first are at bits of higher significance than things declared later so if I represent the bits by the first letter of the variable it would look like: mmmmmm|hhhhh|ddddd|mmmm|yyyyyyyyyyyy Finally, let's pretend that I simply declare an unsigned long and split it up using masks and shifts to do the same things. unsigned long dateTime; Here is my question: Are the following to methods of accessing minutes, hours, etc. equivalent in terms of what the computer needs to do? Or is there some tricksy method that the compiler/computer uses with the bit fields. unsigned minutes = stamp.minutes; //versus unsigned minutes = ((dateTime & 0xf8000000)>>26; and unsigned hours = stamp.hours; //versus unsigned hours = ((dateTime & 0x07C00000)>>21; etc.
The compiler generates the same instructions that you would explicitly write to access the bits. So don't expect it to be faster with bitfields. In fact, strictly speaking with bitfields you don't control how they are positioned in the word of data (unless your compiler gives you some additional guarantees. I mean that the C99 standard doesn't define any). Doing masks by hand, you can at least place the two most often accessed fields first and last in the series, because in these two positions, it takes one operation instead of two to isolate the field.
1,484,052
1,484,062
Should I expose iterators and adaptor methods or a whole container in C++?
Consider the piece of code: class Foo { // ... std::vector<Bar> bars; }; Should I expose the whole container, or should I expose typedef'd iterator class and write adaptor methods (begin(), end(), size(), and whatever I need)? If the answer is it depends, how should one make a decision?
You only expose iterators or iterator-ranges (and typedefed iterator types) unless you absolutely need to expose the container. This avoids breaking other code when changing the implementation details and also follows the guide-lines of information hiding / encapsulation.
1,484,140
1,484,149
How do you get an unsigned long out of a string?
What's the safest and best way to retrieve an unsigned long from a string in C++? I know of a number of possible methods. First, converting a signed long taken from atol. char *myStr; // Initalized to some value somehow. unsigned long n = ((unsigned)atol(myStr)); The obvious problem with this is, what happens when the value stored in myStr is larger than a signed long can contain? What does atol retrieve? The next possibility is to use strtoul. char *myStr; // Initalized to some value somehow. unsigned long n = strtoul(myStr, 0, 10); However, this is a little over complicated for my needs. I'd like a simple function, string in, unsigned long base 10 out. Also, the error handling leaves much to be desired. The final possibility I have found is to use sscanf. char *myStr; // Initalized to some value somehow. unsigned long n = 0; if(sscanf(myStr, "%lu", n) != 1) { //do some error handling } Again, error handling leaves much to be desired, and a little more complicated than I'd like. The remaining obvious option is to write my own either a wrapper around one of the previous possibilities or some thing which cycles through the string and manually converts each digit until it reaches ULONG_MAX. My question is, what are the other options that my google-fu has failed to find? Any thing in the C++ std library that will cleanly convert a string to an unsigned long and throw exceptions on failure? My apologies if this is a dupe, but I couldn't find any questions that exactly matched mine.
One way to do it: stringstream(str) >> ulongVariable;
1,484,237
1,484,239
Platform-independent way to obtain maximum C++ float value
What’s the best, platform-independent way to obtain the maximum value that can be stored in a float in C++?
std::numeric_limits    
1,484,350
1,484,363
Validating a user's input to make sure it's in binary (C++)
I'm working on a c++ program and I need to take in a binary number from 0-255, inclusive, as a string(it has to be a string). What can I write in a while(input invalid) loop to check that the string is between 00000000 to 11111111, inclusive. Thanks so much
Assuming you use std::string: while( str.length()==8 && str.find_first_not_of("01")==std::string::npos ) that is, if you really want it to be always 8 characters. Adjust to suit your taste (for what I can tell by your comment, you want str.length()<=8 or (!str.empty()) && str.length()<=8.
1,484,462
1,484,476
How to require certain concepts in C++ code?
How do I require and check that an argument is a certain concept in C++? For example, the random_shuffle function in the algorithm header requires that its arguments are RandomAccessIterators: template<typename _RandomAccessIterator> inline void random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); if (__first != __last) for (_RandomAccessIterator __i = __first + 1; __i != __last; ++__i) std::iter_swap(__i, __first + (std::rand() % ((__i - __first) + 1))); } I guess I can't use these __glibcxx_function_requires etc. in my own code? How do they work? Do you check things like that in your code?
Boost has a library for this. It's probably easier and more well documented than figuring out how to use the version your STL implementer has hacked together. http://www.boost.org/doc/libs/1_40_0/libs/concept_check/concept_check.htm
1,484,518
1,484,668
getrusage() get system time, user time. Unix programming help
I am writing a shell where I need to launch several child processes at once and record the system time and user time. So far I am able to do it. The only problem is that I am using wait4 to grab the system resources used by the child program and put it in my rusage structure called usage. How can I launch all the processes at the same time and keep track of the user and system times? I can remove the wait4() system call and use it outside to loop so I can make the parent wait, but if I do that then I can only record the times for the last process and not all of them. Do you have any idea how I can fix this? execute(commandPipev,"STANDARD",0); wait4(pid,&status,0,&usage); printf("Child process: %s\t PID:%d\n", commandPipev[0], pid); printf("System time: %ld.%06ld sec\n",usage.ru_stime.tv_sec, usage.ru_stime.tv_usec); printf("User time: %ld.%06ld sec\n\n",usage.ru_utime.tv_sec, usage.ru_utime.tv_usec);
A convoluted answer. In a POSIX environment, launch the children, then use waitid() with the WNOWAIT option to tell you that some child has exited. The option leaves the child in a waitable state - that is, you can use another wait-family call to garner the information you need. You can then use the non-POSIX wait4() system call to garner the usage information for the just exited child, and deal with the accounting you need to do. Note that you might find a different process has terminated between the waitid() and wait4() calls; you need to use a loop and appropriate flags and tests to collect all the available corpses (dead child processes) before going back to the waitid() call to find out about the other previously incomplete child processes. You also have to worry about any of the wait-family of functions returning the information for a process that was previously started in the background and has now finished. The Linux man page for wait4(2) suggests that WNOWAIT might work directly with wait4(2), so you may be able to do it all more cleanly - if, indeed, you need the option at all. Consider whether you can use process groups to group the child processes together, to make waiting for the members of the process group easier.
1,484,543
1,484,560
Is it safe to use fastcall in a shared library?
For example, let's say I have a function that will swap bytes in a 32 bit value for you: uint32_t byte_swap(uint32_t in); Well it seems silly to push that 32-bit value onto the stack and pop it off again, especially if we're going to be calling this function a lot, so let's pass it in through ECX: #if __FASTCALL_SUPPORTED_ /* Whatever this may be */ #define FASTCALL __attribute__((fastcall)) #else #define FASTCALL #endif uint32_t FASTCALL byte_swap(uint32_t in); Now my question is, is it safe to compile that function into a shared library for distribution? If the user uses a different compiler to compile their program and links against this, will the function still be called properly?
__attribute__((fastcall)) is a gcc extension; as such, it may not be usable if the caller is not using gcc as well. Moreover, in the sample you gave, if __FASTCALL_SUPPORTED_ is not defined, you'll end up with a call with the wrong calling convention - bad idea. One way to deal with this may be using a fallback wrapper. In your .c file: #include "foo.h" uint32_t FASTCALL byte_swap(uint32_t in) { /* code ... */ } uint32_t byte_swap__slowcall(uint32_t in) { return byte_swap(in); } And in your .h file: #if __FASTCALL_SUPPORTED_ /* Whatever this may be */ #define FASTCALL __attribute__((fastcall)) #else #define FASTCALL #define byte_swap byte_swap__slowcall #endif uint32_t FASTCALL byte_swap(uint32_t in); Also, note that on Linux, a fast byteswap implementation is available in <byteswap.h> as bswap_32. On x86 machines, it will compile down to inline assembler, and a single instruction on high enough -march= settings.
1,484,641
1,484,665
C++ override/overload problem
I'm facing a problem in C++ : #include <iostream> class A { protected: void some_func(const unsigned int& param1) { std::cout << "A::some_func(" << param1 << ")" << std::endl; } public: virtual ~A() {} virtual void some_func(const unsigned int& param1, const char*) { some_func(param1); } }; class B : public A { public: virtual ~B() {} virtual void some_func(const unsigned int& param1, const char*) { some_func(param1); } }; int main(int, char**) { A* t = new B(); t->some_func(21, "some char*"); return 0; } I'm using g++ 4.0.1 and the compilation error : $ g++ -W -Wall -Werror test.cc test.cc: In member function ‘virtual void B::some_func(const unsigned int&, const char*)’: test.cc:24: error: no matching function for call to ‘B::some_func(const unsigned int&)’ test.cc:22: note: candidates are: virtual void B::some_func(const unsigned int&, const char*) Why do I must specify that the call of some_func(param1) in class B is A::some_func(param1) ? Is it a g++ bug or a random message from g++ to prevent special cases I don't see ?
The problem is that in the derived class you are hiding the protected method in the base class. You can do a couple of things, either you fully qualify the protected method in the derived object or else you bring that method into scope with a using directive: class B : public A { protected: using A::some_func; // bring A::some_func overloads into B public: virtual ~B() {} virtual void some_func(const unsigned int& param1, const char*) { A::some_func(param1); // or fully qualify the call } };
1,484,739
1,484,906
how to properly delete a pointer to array
I'm new to C++, and I'm confused about arrays and pointers. Could someone tell me how I can properly delete a pointer. Like for example, int *foo; foo = new int[10]; delete foo; or delete [] foo; Thanks.
The requirement to match new[] with delete[] is technically correct. Much better, however (at least in my opinion), would be to forget that you ever even heard of new[], and never use it again. I'm pretty sure it's been (at least) 10 years since the last time I used new[], and if I'd understood the situation very well, I'd have stopped even sooner than that. Pretty nearly any time you'd even consider using new[], an std::vector (or possibly std::deque) will be a better choice. If you're trying to create something roughly equivalent to a vector or deque yourself, you don't normally want to use new[] for that either. They way they (at least normally, though it's possible to change this via a custom Allocator class) is to allocate "raw" storage with operator new (which is pretty much like malloc--you just give it a size, and it gives you that many bytes of storage). Then you use the placement new operator to create objects in that space, and explicitly invoke the object's destructor to destroy objects in that space. To give one example, this is what allows std::vector to support reserve, which allows you to allocate extra space, which won't be turned into objects until you call something like push_back or emplace_back to create an actual object in the space you allocated. When you use new[], it has to create objects of the specified type filling all the space you allocate. You can't create something like push_back that adds a new object to the collection, because the collection is always already "full". All you can do is allocate a new collection that's larger than the old one (so every addition to the collection is O(N) instead of the amortized O(1) supported by std::vector--a huge loss of efficiency).
1,484,744
1,484,883
Calling WinSock functions using LoadLibrary and GetProcAddress
Basically I have a header file like this: #if WIN32 typedef DWORD (WSAAPI *SocketStartup) (WORD wVersionRequested, LPWSADATA lpWSAData); typedef SOCKET (WINAPI *MakeSocket)(IN int af, IN int type, IN int protocol, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN GROUP g, IN DWORD dwFlags ); typedef DWORD (WINAPI *SocketSendFunc) (IN SOCKET s,__in_bcount(len) const char FAR * buf, IN int len,IN int flags); typedef DWORD (WINAPI *GetLastSocketErrorFunc)(); typedef DWORD (WINAPI *ShutdownSocketFunc)(SOCKET hSocket, int how); typedef DWORD (WINAPI *CloseSocketFunc)(SOCKET hSocket); #endif and then I do something like this: SocketStartup* start = (SocketStartup*)GetProcAddress(socketLib,"WSAStartup"); getLastSocketError = (GetLastSocketErrorFunc*)GetProcAddress(socketLib,"WSAGetLastError"); closeSocket = (CloseSocketFunc*)GetProcAddress(socketLib,"closesocket"); shutdownSocket = (ShutdownSocketFunc*) GetProcAddress(socketLib,"shutdown"); socketSend = (SocketSendFunc*) GetProcAddress(socketLib, "send"); if(start == 0 || getLastSocketError == 0 || closeSocket == 0 || shutdownSocket == 0 || socketSend == 0) { printf("[!] Failed to find entry points in Ws2_32.dll. Error Code: %d\n", GetLastError()); CloseLibraries(); ErrorExit(); } WSADATA wsdata; //ZeroMemory(&wsdata,sizeof(wsdata)); printf("error: %d\n", GetLastError()); WORD test = MAKEWORD(1,1); int result = (*start)(test, &wsdata); return result == 0; However, when I call this function (the line with (*start)(test, &wsdata)) I get this error message: Unhandled exception at 0x7868146a in sockets.exe: 0xC0000005: Access violation. I tried changing the calling convention (__cdecl, WINAPI, WSAAPI) but it always ends with the same error message.
Solved! Thank you all for your help. To fix it I just changed the typedef as follows: typedef int (WSAAPI SocketStartup)( IN WORD wVersionRequested, OUT LPWSADATA lpWSAData ); Basically I copy and pasted from Winsock2.h :P
1,484,882
1,484,917
Why use an object instance rather than class::staticFunction?
Why should I use an object instance to access member functions rather than class::staticFunction? ( or why not? )
You're allowed to use the object.function() notation for a static function, but I'd advise against it -- it gives the misleading impression that the function is associated with the specific object, like with a non-static member function. Using the classname::function() syntax portrays the situation clearly and accurately.
1,484,950
1,484,991
Using cin in QtCreator
For school, we use C++ as the language of choice. I am currently using QtCreator as an IDE, and for its GUI library, it is wonderful. The school is using Visual Studio. However, most of the programs we are writing make use of cin and cout for input/output. cout works fine as output, as you can see what it puts out in the application output, but there is no way to provide to cin as if it were on a console, like Visual Studio uses for its C++. An example: #include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter name: "; cin >> name; cout << "Your name is " << name << endl; } Is there a way to use a console or provide input to cin like in Visual Studio? I am currently running OS X Leopard, if it matters.
In Preferences, under the Environment section, set the "Terminal" option to /Applications/Utilities/Terminal.app, as pointed out by Alex Martelli. Then, in the Projects tab, under Run Settings, check the box marked "Run in Terminal". Now, QtCreator will use Apple's built-in Terminal.app instead of Qt's console, allowing for interactive input.
1,485,044
1,485,064
Folding away assertions in C++ class?
So, in a non-class type of situation, I can do something like this: int val_to_check = 0; int some_func(int param) { assert(val_to_check == 0); return param*param+param; } int main() { printf("Val: %i\n", some_func(rand())); return 0; } If val_to_check is declared const instead, the assertion can be folded away by the compiler. I'm curious if it's possible to get a similar constant folding with a member variable of a class. For example, can I do something like: class Test { public: Test(int val) : val_(val) {} int some_func(int param) { assert(val_ == 0); return param*param+param; } private: const int val_; }; So val_ must be known when the class is defined, a-la: Test my_test(0); printf("Val: %i\n", my_test.some_func(rand())); (I know these are contrived examples). It seems like it should be possible to fold the assertions away sometimes, but the simple examples I've tested don't seem to do it. The best I've gotten is moving the assertion code to the end of the function (when compiling w/ -O3)
In the class example you provided, there's no way for the compiler to assume the constant is zero because you have two runtime variables: Your const int val_ is only constant for each instance of the class so it can never optimise the class's function code since it must cater for every case. The example instantiation doesn't provide a literal constant, it provides the result of rand() which is variable. It may be possible for it to optimise it out if it knows the ONLY val_ ever being provided to all instances of that class is zero. Have you tried providing a constant to the constructor to see if it optimises it out?
1,485,239
1,695,675
QtCreator build returns collect2: ld returned exit status 1
While building several different projects in QtCreator, I have run across the following build error: collect2: ld returned 1 exit status After only changing a few things (that should not change anything significant in the build), it will go away if it has already appeared, or it will appear if it's not there. In my current program for a school project, I am trying to compile rock03.cpp. It's the only file in the build, and has the main() method. I had just run it successfully, and went back to change the order of some if()s, now, I get only two relevant warnings: overriding commands for target 'rock03.o' and ignoring old commands for target 'rock03.o' along with the error in question. Does anyone know why this would happen? I cannot seem to reproduce the error with any reasonable certainty, and QtCreator is not complaining about any thing before I build. Thanks
Checking the "Compile Output" pane reveals that the .pro file was trying to link the same .cpp file twice.
1,485,435
1,485,714
Force relink when building in QT Creator
I have a subdirs project which wraps a couple libraries and a main application. When I change something in one of the libraries the main application does not relink with them.. does anyone have a trick for getting an application to relink with its statically linked libs automatically when using QtCreator?
There is a workaround for this and also an interesting discussion on the subject (qmake seems to be the problem here) on the Qt Creator mailing list. The workaround is to add a PRE_TARGETDEPS command to your main applications .pro file, e.g.: PRE_TARGETDEPS += /path/to/your/lib.a This forces the relink.
1,485,697
1,488,082
CreateProcessWithLogonW and mmc.exe
I wrote a program, that should work like RunAs. It works fine, but i have one problem with it. If i want to run for example compmgmt.msc, then i should run mmc.exe and compmgmt.msc as it's parameter. Computer Management will open, but not under the user as i want to run it. It will run under that username who is logged in. Can someone tell me why is that, and how can i correct it? Here is my code : void createproc( wchar_t * user, wchar_t * domain, wchar_t * pass, wchar_t * applicationname) { int errorcode; char cmd[Buf_Size]; STARTUPINFO StartInfo; PROCESS_INFORMATION ProcInfo; memset(&ProcInfo, 0, sizeof(ProcInfo)); memset(&StartInfo, 0 , sizeof(StartInfo)); StartInfo.cb = sizeof(StartInfo); StartInfo.wShowWindow = SW_HIDE; int bFuncRetn = CreateProcessWithLogonW ( user, domain, pass, LOGON_NETCREDENTIALS_ONLY, L"C:\\Windows\\System32\\mmc.exe", //applicationname, L" compmgmt.msc", CREATE_UNICODE_ENVIRONMENT, NULL, NULL, (LPSTARTUPINFOW)&StartInfo, &ProcInfo ); errorcode = GetLastError(); if ( bFuncRetn == 0 ) { CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); printf("\nGetLastError :: %d CreateProcessWithLogonW Failed!", errorcode); printf("\nFor more information type :: Net Helpmsg %d", errorcode); getch(); exit(1); } CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); }//createproc Thanks for your help! kampi
Have you looked at the online MSDN docs? http://msdn.microsoft.com/en-us/library/ms682431(VS.85).aspx Have a look at the sample code. Seems pretty straightforward.
1,485,978
1,486,006
Arranging global/static objects sequentially in memory
In C++, is it possible to force the compiler to arrange a series of global or static objects in a sequential memory position? Or is this the default behavior? For example, if I write… MyClass g_first (“first”); MyClass g_second (“second”); MyClass g_third (“third”); … will these objects occupy a continuous chunk of memory, or is the compiler free to place them anywhere in the address space?
The compiler can do as it pleases when it comes to placing static objects in memory; if you want better control over how your globals are placed, you should consider writing a struct that encompasses all of them. That will guarantee that your objects will all be packed in a sequential and predictable order.
1,485,983
1,486,279
Calling C++ member functions via a function pointer
How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write: class Dog : Animal { Dog (); void bark (); } … Dog* pDog = new Dog (); BarkFunction pBark = &Dog::bark; (*pBark) (pDog); … Also, if possible, I’d like to invoke the constructor via a pointer as well: NewAnimalFunction pNew = &Dog::Dog; Animal* pAnimal = (*pNew)(); Is this possible, and if so, what is the preferred way to do this?
Read this for detail : // 1 define a function pointer and initialize to NULL int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL; // C++ class TMyClass { public: int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;}; int DoMore(float a, char b, char c) const { cout << "TMyClass::DoMore" << endl; return a-b+c; }; /* more of TMyClass */ }; pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore // Calling Function using Function Pointer (*this.*pt2ConstMember)(12, 'a', 'b');
1,485,985
1,486,862
Can a nested C++ class inherit its enclosing class?
I’m trying to do the following: class Animal { class Bear : public Animal { // … }; class Giraffe : public Animal { // … }; }; … but my compiler appears to choke on this. Is this legal C++, and if not, is there a better way to accomplish the same thing? Essentially, I want to create a cleaner class naming scheme. (I don’t want to derive Animal and the inner classes from a common base class)
You can do what you want, but you have to delay the definition of the nested classes. class Animal { class Bear; class Giraffe; }; class Animal::Bear : public Animal {}; class Animal::Giraffe : public Animal {};
1,486,141
1,486,163
Best way to store constant data in C++
I have an array of constant data like following: enum Language {GERMAN=LANG_DE, ENGLISH=LANG_EN, ...}; struct LanguageName { ELanguage language; const char *name; }; const Language[] languages = { GERMAN, "German", ENGLISH, "English", . . . }; When I have a function which accesses the array and find the entry based on the Language enum parameter. Should I write a loop to find the specific entry in the array or are there better ways to do this. I know I could add the LanguageName-objects to an std::map but wouldn't this be overkill for such a simple problem? I do not have an object to store the std::map so the map would be constructed for every call of the function. What way would you recommend? Is it better to encapsulate this compile time constant array in a class which handles the lookup?
If the enum values are contiguous starting from 0, use an array with the enum as index. If not, this is what I usually do: const char* find_language(Language lang) { typedef std::map<Language,const char*> lang_map_type; typedef lang_map_type::value_type lang_map_entry_type; static const lang_map_entry_type lang_map_entries[] = { /*...*/ } static const lang_map_type lang_map( lang_map_entries , lang_map_entries + sizeof(lang_map_entries) / sizeof(lang_map_entries[0]) ); lang_map_type::const_iterator it = lang_map.find(lang); if( it == lang_map.end() ) return NULL; return it->second; } If you consider a map for constants, always also consider using a vector. Function-local statics are a nice way to get rid of a good part of the dependency problems of globals, but are dangerous in a multi-threaded environment. If you're worried about that, you might rather want to use globals: typedef std::map<Language,const char*> lang_map_type; typedef lang_map_type::value_type lang_map_entry_type; const lang_map_entry_type lang_map_entries[] = { /*...*/ } const lang_map_type lang_map( lang_map_entries , lang_map_entries + sizeof(lang_map_entries) / sizeof(lang_map_entries[0]) ); const char* find_language(Language lang) { lang_map_type::const_iterator it = lang_map.find(lang); if( it == lang_map.end() ) return NULL; return it->second; }
1,486,203
1,495,731
how to draw namespace/package scope method/variable in UML?
I'm currently trying to draw a class diagram of a couple of namespaces in C++. Right now, some variables and methods inside the namespace(free, not part of classes) are part of the namespace API, others are the external part of some classes API (like operator<< and those). I'm only willing to represent those methods/vars that expose namespace API, but I can't find a way of doing that with standard UML tools, and can't find any relevant info in the Internet. any hint?
UML is for modelling Object Oriented designs, it is not intended to model implementation idioms. Apply the Principle of a Single Responsibility Principle to determine where the function should exist, either in the core class or a handler class.
1,486,324
1,486,344
Is it possible for programmer to analyze unknown code fast?
I got a task related to ANCIENT C++ project which hasn't any documentation, comments at all and all code/variables is written in foreign language. Do I have a chance to analyze this code in a 1 working day and make a design/UML to create new features? I have been sitting around for 3 hours already and I feel so frustrated... Maybe somebody also had same problem? Any advice? BR,
I suspect the biggest issue may be the fact that it's in a foreign language. You can use various static code analysis tools to try and understand what's going on, but if everything is presented in an unfamiliar language then that's still no use. Your first step (I believe) is to find someone who can speak this language and get them to translate as you go...
1,486,402
1,486,425
c++ need help on how to use callback functions
The function header is defined below: /** * \fn int fx_add_buddylist(const char* name, EventListener func, void *args) * \brief rename the group. * * \param name The group name which you want to add. * \param func The send sms operate's callback function's address, and the operate result will pass to this function. * \param args The send_sms operate's callback function's args. * * \return 0 if fail immediately, or can get the result from func. */ FX_EXPORT int fx_add_buddylist(const char* name, EventListener func, void *args); /** * \defgroup cb_func Event CallBack Function * @{ */ /** * \var typedef void (*EventListener) (int message, WPARAM wParam, LPARAM lParam, void* args) * brief the callback function of fetion event. * * * \param message The fetion event type. * \sa events */ typedef void (*EventListener) (int message, WPARAM wParam, LPARAM lParam, void* args); /** @} end of cb_func */ I don't know how to use EventListener to get the result of fx_add_buddylist() (eg if i failed to add buddy or not).
EventListener defines the interface of a function you have to write and pass as argument to fx_add_buddylist. Do something like this: void MyEventListener(int message, WPARAM wParam, LPARAM lParam, void* args) { printf("Callback called!\n"); } ... fx_add_buddylist("SomeName", MyEventListener, NULL); ... You can use the args argument to pass extra data you need in the callback function.
1,486,492
1,486,544
Qt tr does not seem to work on static constant members?
I'm working on translating our Qt gui at the moment. I have the following code: // header file static const QString Foo; // cpp file const QString FooConstants::Foo = "foo"; // another cpp file editMenu->addAction(tr(FooConstants::Foo)); This doesn't seem to work though. That is, there is no entry in the .ts file for the above constant. If I do this then it works: // another cpp file editMenu->addAction(tr("foo")); However, this constant is used in many places, and I don't want to have to manually update each string literal. (if it were to change in the future) Can anyone help?
Wrap your literal in the QT_TR_NOOP macro: // cpp file const QString FooConstants::Foo = QT_TR_NOOP("foo"); From the guide: If you need to have translatable text completely outside a function, there are two macros to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). They merely mark the text for extraction by the lupdate tool. The macros expand to just the text (without the context).
1,486,545
1,486,805
Qt GUI app: warning if QObject::connect() failed?
I recently migrated my Qt project from Linux to Vista, and now I'm debugging signals blindly. On Linux, if QObject::connect() fails in a debug build, I get a warning message on stderr. On Windows, there is no console output for GUI applications, only an OutputDebugString call. I already installed DebugView, and it catches my own qDebug() output nicely, but still no warning on failed signals. One possible solution would be to use QtCreator's autocomplete for signals, but I like Eclipse, and using both is a PITA. Any ideas on how to get signal/slot info at runtime? Edit: I just realized connect() returns bool, which solves the immediate problem, ugly as it may be. However, this doesn't solve the cases where QMetaObject::connectSlotsByName() fails, and this one runs automatically with widgets.
Call the static function QErrorMessage::qtHandler(). As per the documentation, this 'installs a message handler using qInstallMsgHandler() and creates a QErrorMessage that displays qDebug(), qWarning() and qFatal() messages'. Alternatively, install a message handler with qInstallMsgHandler(). Another alternative (described in a qt-interest post) is something like this: #ifdef _DEBUG #define connect( connectStmt ) Q_ASSERT( connect( connectStmt ) ) #endif ...and for what it's worth, here are some signals and slots debugging suggestions I compiled: http://samdutton.wordpress.com/2008/10/03/debugging-signals-and-slots-in-qt/
1,486,740
1,487,093
How do I get the default check box images?
I'm trying to build an owner-drawn check box using CButton, but since I only want to change the text color, I'd like the check-box marks to remain the same. Is there a command that allows me to retrieve the default check box bitmaps for the platform where the program is running? (alternatively: how could I change only the text color, preserving the check box marks?)
I use UxTheme.dll to draw my custom checkbox. First I draw the check-box marks using: DrawThemeBackground passing it a modified rect (checkboxRect.right = pCustomDraw->rc.left + 15;) And then I draw the text by myself using ::DrawText. I hope it helps.
1,486,818
1,486,849
C/C++ - Any good web server library?
Are there any open source, fast web server libraries? Thanks.
mongoose (formely shttpd, GPL v2 and commercial license), libmicrohttpd (LGPL v2.1 license).
1,486,904
1,486,931
How do I best silence a warning about unused variables?
I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables. What would be the best way of coding around the warning? An #ifdef around the function? #ifdef _MSC_VER void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal qrLeft, qreal qrTop, qreal qrWidth, qreal qrHeight) #else void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal /*qrLeft*/, qreal /*qrTop*/, qreal /*qrWidth*/, qreal /*qrHeight*/) #endif { This is so ugly but seems like the way the compiler would prefer. Or do I assign zero to the variable at the end of the function? (which I hate because it's altering something in the program flow to silence a compiler warning). Is there a correct way?
You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers. E.g. void foo(int param1, int param2) { (void)param2; bar(param1); } Or, #define UNUSED(expr) do { (void)(expr); } while (0) ... void foo(int param1, int param2) { UNUSED(param2); bar(param1); }
1,487,238
1,487,269
Copy constructor: deep copying an abstract class
Suppose I have the following (simplified case): class Color; class IColor { public: virtual Color getValue(const float u, const float v) const = 0; }; class Color : public IColor { public: float r,g,b; Color(float ar, float ag, float ab) : r(ar), g(ag), b(ab) {} Color getValue(const float u, const float v) const { return Color(r, g, b) } } class Material { private: IColor* _color; public: Material(); Material(const Material& m); } Now, is there any way for me to do a deep copy of the abstract IColor in the copy constructor of Material? That is, I want the values of whatever m._color might be (a Color, a Texture) to be copied, not just the pointer to the IColor.
Take a look at the virtual constructor idiom
1,487,318
1,487,353
Qt4 modular synth editing widget
I'm about to start writing a GUI for a modular synthesis app (like Alsa Modular Synth, Pure Data, Ingen) that will be used for patch (sound) editing. What I need to do is something like this: (source: drobilla.net) (source: mcgill.ca) So, basically, it's an area where I can draw some rectangles (boxes) that represent synth modules with input and output ports that I can connect with wires. The problem is that I can't figure out how two create a widget for the editing area: Using a simple 2D drawing context where I draw the boxes manually seems to be the only logical way to do this, but doing this I loose all the great event management that qt gives me. I'm wondering if there's the possibility of creating a custom layout that simply takes coordinates of created "boxes" and put them on the screen, so that I implement the boxes as subclasses of QWidget (and reusing qt's event handling system) and I add them to the window as I do usually. Or maybe there's a better way? Thank you
Take a look at QGraphicsScene and QGraphicsView. This way you will be able to create a scene filled with items. Each item can receive mouse events and you can manually paint it.
1,487,375
1,506,875
Qt stylesheets: QHeaderView draws header text in bold when view data is selected
I'm trying to style a QTableView with Qt Stylesheets. Everything works OK, except that all the table header texts (column headers) are drawn as bold text whenever data in the table view is selected. I've tried things like this: QTableView::section { font-weight: 400; } QTableView::section:selected { font-weight: 400; } QHeaderView { font-weight: 400; } QHeaderView::section { font-weight: 400; } to no avail. Can anyone point me in the right direction, ideally using stylesheets?
I haven't tested it, but setting the QHeaderView::highlightSections property to false should do the trick. You can get a pointer to a QHeaderView object using QTableView's verticalHeader() and horizontalHeader() methods.
1,487,387
1,487,778
Why do Boost Parameter elected inheritance rather than composition?
I suppose most of the persons on this site will agree that implementation can be outsourced in two ways: private inheritance composition Inheritance is most often abused. Notably, public inheritance is often used when another form or inheritance could have been better and in general one should use composition rather than private inheritance. Of course the usual caveats apply, but I can't think of any time where I really needed inheritance for an implementation problem. For the Boost Parameter library however, you will notice than they have chosen inheritance over composition for the implementation of the named parameter idiom (for the constructor). I can only think of the classical EBO (Empty Base Optimization) explanation since there is no virtual methods at play here that I can see. Does anyone knows better or can redirect me to the discussion ? Thanks, Matthieu.
EDIT: Ooopss! I posted the answer below because I misread your post. I thought you said the Boost library used composition over inheritance, not the other way around. Still, if its usefull for anyone... (See EDIT2 for what I think could be the answer for you question.) I don't know the specific answer for the Boost Parameter Library. However, I can say that this is usually a better choice. The reason is because whenever you have the option to implement a relationship in more than one way, you should choose the weakest one (low coupling/high cohesion). Since inheritance is stronger than composition... Notice that sometimes using private inhertiance can make it harder to implement exception-safe code too. Take operator==, for example. Using composition you can create a temporary and do the assignment with commit/rollback logic (assuming a correct construction of the object). But if you use inheritance, you'll probably do something like Base::operator==(obj) inside the operator== of the derived class. If that Base::operator==(obj) call throws, you risk your guarantees. EDIT 2: Now, trying to answer what you really asked. This is what I could understand from the link you provided. Since I don't know all details of the library, please correct me if I'm wrong. When you use composition for "implemented in terms of" you need one level of indirection for the delegation. struct AImpl { //Dummy code, just for the example. int get_int() const { return 10; } }; struct A { AImpl * impl_; int get_int() const { return impl->get_int(); } /* ... */ }; In the case of the parameter-enabled constructor, you need to create an implementation class but you should still be able to use the "wrapper" class in a transparent way. This means that in the example from the link you mentioned, it's desired that you can manipulate myclass just like you would manipulate myclass_impl. This can only be done via inheritance. (Notice that in the example the inheritance is public, since it's the default for struct.) I assume myclass_impl is supposed to be the "real" class, the one with the data, behavior, etc. Then, if you had a method like get_int() in it and if you didn't use inheritance you would be forced to write a get_int() wrapper in myclass just like I did above.
1,487,440
1,487,483
Convert hexadecimal string with leading "0x" to signed short in C++?
I found the code to convert a hexadecimal string into a signed int using strtol, but I can't find something for a short int (2 bytes). Here' my piece of code : while (!sCurrentFile.eof() ) { getline (sCurrentFile,currentString); sOutputFile<<strtol(currentString.c_str(),NULL,16)<<endl; } My idea is to read a file with 2 bytes wide values (like 0xFFEE), convert it to signed int and write the result in an output file. Execution speed is not an issue. I could find some ways to avoid the problem, but I'd like to use a "one line" solution, so maybe you can help for this :) Edit : The files look like this : 0x0400 0x03fe 0x03fe ... Edit : I already tried with the hex operator, but I still have to convert the string to an integer before doing so. // This won't work as currentString is not an integer myInt << std::hex << currentString.c_str();
Have you considered sscanf with the "%hx" conversion qualifier?
1,487,476
1,487,530
Debugging multitheaded programs
I have been a C programmer for many years and my favorite "debugger" has always been the printf() function - I only resort to visual studio's debugger when absolutely forced and so have never been very proficient in using it. Recently I have had to modify a program from C to C++ (although of course printf still works fine) and and parts of the program are now farmed out in to multiple threads (one for each core on a multicore machine) to make the program run faster. Now i will no doubt come up against awkward multi-thread related bugs like deadlocks and I wonder what debugging methodology I can turn to. Does visual studio (2008) have everything I could reasonably need to help me resolve thread related bugs? Should I take some time out now to learn how to use some third party debugger? Could I solve most problems using my good old printf? Could I for example write code which, if kept waiting on entry to a critical section would print something like "Thread X waiting to enter ... but blocked because its being used by thread Y"?
Visual Studio supports thread debugging to some extend. Via the Threads Window you can select threads, suspend and resume threads etc. When you switch between threads the Call Stack Window is updated accordingly so you can inspect what each thread is doing. You may also restrict breakpoints to specific threads. If you want an alternative WinDbg (which is part of the free Debugging Tools for Windows package from Microsoft) offers lots of options as well but with a slightly more esoteric user interface. As for using printf, there's the problem of synchronizing output. If you don't do it you output will most likely be gibberish. If you do synchronize it you basically change the concurrency of the application, which may or may not affect the problem you're trying to solve.
1,487,674
1,489,095
How to work out which widget to target with Qt stylesheets
I'm attempting to use Qt stylesheets to style a reasonably complex UI. So far things are going reasonably well, but I'm running into a difficulty: How can I work out what widget name I should be targeting for a particular part of a UI? For example, if I want to change the font size in the cells of a QTableView, do I write a style that targets QTableView? or perhaps QAbstractScrollArea? or perhaps QAbstractitemDelegate? As it turns out none of these seem to work - I assume this can be done, but it's a case of working out what the magic combination of widgets is to target the right part of the UI. The style sheet guide helps somewhat, but seems to be missing a lot of information - the example for customising QTableView only mentions customising the cell background colour, and does not mention changing font colour, size, face, grid lines etc. Am i missing something here? Perhaps Using stylesheets is the wrong way to go? I certainly hope not, since the alternative (deriving from QStyle) seems much more complicated. Cheers,
Rendering of items in an item view is done by the delegate. Since Qt 4.4, the built-in item views use a style-able delegate implementation by default (see this blog post), but it seems that you want more control that it allows you. In that case, make sure that your model's data() method returns proper values for the appearance related ItemDataRoles (I think that Qt::FontRole will be especially of interest to you). If that is not enough, or if it's not possible, you should subclass QStyledItemDelegate and reimplement its paint() method. As to grid lines, QTableView has the gridStyle property.
1,487,695
1,487,762
C++ Cross-Platform High-Resolution Timer
I'm looking to implement a simple timer mechanism in C++. The code should work in Windows and Linux. The resolution should be as precise as possible (at least millisecond accuracy). This will be used to simply track the passage of time, not to implement any kind of event-driven design. What is the best tool to accomplish this?
For C++03: Boost.Timer might work, but it depends on the C function clock and so may not have good enough resolution for you. Boost.Date_Time includes a ptime class that's been recommended on Stack Overflow before. See its docs on microsec_clock::local_time and microsec_clock::universal_time, but note its caveat that "Win32 systems often do not achieve microsecond resolution via this API." STLsoft provides, among other things, thin cross-platform (Windows and Linux/Unix) C++ wrappers around OS-specific APIs. Its performance library has several classes that would do what you need. (To make it cross platform, pick a class like performance_counter that exists in both the winstl and unixstl namespaces, then use whichever namespace matches your platform.) For C++11 and above: The std::chrono library has this functionality built in. See this answer by @HowardHinnant for details.
1,487,815
1,487,856
What could be causing this crash?
I have a C++ program (GCC) and when I add one or more int members to an abstract base class, the program starts crashing. In the case I've examined, it seems that by adding this member, a member in a derived class quits getting initialized (or gets stomped on at some point). If I add more members, it starts (not) working different. This is all really odd because the member is never used anywhere. I can comment out that one line and the program recompile just fine and runs without error. The whole program is ~3KLOC and would be very hard to strip down. I'm totally at a loss as to where to start looking. Any Ideas? Update I found the issue: free-ing malloc-ed memory and delete-ing new-ed memory is not safe in the same program.
Off the top of my head, without seeing any code (see comments on your question) I would suggest a rogue pointer which normally stomps on something you don't notice, but introducing a new member makes it stomp on something you do notice. Try adding members of different sizes, or more (unused) int members, or maybe a string in the form: const char xxx[50]; to reserve more space.
1,487,840
1,487,992
Search Hex substring in string
Well i got a socket that receives binary data and I got that data into an string, containing values and strings values too. (for example "0x04,h,o,m,e,....") How can i search for an hex substring into that string? I.e. i want to search "0x02,0x00,0x01,0x04". I'm asking for a c++ version of python 'fooString.find("\x02\x00\x01\x04")' Thanks to all :)
Good documentation for string is here: http://www.sgi.com/tech/stl/basic_string.html Hex tokens are passed just like Python (Where do you think Python got the syntax from). The character \x?? is a single hex character. #include <iostream> #include <string> int main() { std::cout << (int)'a' << "\n"; std::string x("ABCDEFGHIJKLMNOPabcdefghijklmnop"); std::string::size_type f = x.find("\x61\x62"); // ab std::cout << x.substr(f); // As pointed out by Steve below. // // The string for find is a C-String and thus putting a \0x00 in the middle // May cause problems. To get around this you need to use a C++ std::string // as the value to find (as these can contain the null character. // But you run into the problem of constructing a std::string with a null // // std::string find("\0x61\0x00\0x62"); // FAIL the string is treated like a C-String when constructing find. // std::string find("\0x61\0x00\0x62",3); // GOOD. Treated like an array. std::string::size_type f2 = x.find(std::string("\0x61\0x00\0x62",3)); }
1,487,950
1,502,908
access violation in WM_PAINT not caught
To test this problem I have written a minimal windows application. If I force an access violation in the WM_PAINT handler this exception never gets to the debugger. If started without debugger the access violation also does not show up. Usually you should get the Windows Error Reporting dialog. Digging a bit deeper it seems that something in user32.dll catches all incoming exceptions. Is this normal behavior? Can I control this somehow? Isn't catching all exceptions a security risk? At least it is annoying as hell. This is with a 32- and 64-bit application on Vista 64. On XP the exception seems to be handled as expected. Other windows messages have the same problem. Maybe all of them? The WM_PAINT handler: case WM_PAINT: hdc = BeginPaint(hWnd, &ps); *(int*)0 = 0; EndPaint(hWnd, &ps); break;
As a workaround I remove all registered exception handlers in my window procedure. Quite ugly. LRESULT CALLBACK window_proc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // get thread information block NT_TIB* tib; __asm { mov EAX, FS:[18h] mov [tib], EAX } // old exception handler list _EXCEPTION_REGISTRATION_RECORD* old_exception_handler = tib->ExceptionList; // remove all exception handler with exception of the default handler while( tib->ExceptionList->Next != (_EXCEPTION_REGISTRATION_RECORD*)-1 ) { tib->ExceptionList = tib->ExceptionList->Next; } LRESULT result = DefWindowProc( hwnd, uMsg, wParam, lParam ); // restore old exception handler tib->ExceptionList = old_exception_handler; return result; }
1,488,234
1,488,274
play video clip in windows c++ app
Im currently using wxMediaCtrl to play videos in my app. The api is unfortunately a little buggy, and doesn't playback all media types i need to support (e.g. wmv). I am wondering if there is an alternative c++ api, that will allow me to do this. I am currently just concerned with supporting windows. What do people normally use to embedd video in their apps? Also i need to be in control, i.e. tell the video, where to play in time, pause/stop, i dont need any shuttle controls, as i have my own. Thanks in advance.
wxMediaControl uses DirectShow on Windows, it should be able to play wmv files. If you can play a media file with GraphStudio, you should be able to play it with wxMediaControl. If not, you need to install the proper video codecs. Have you tried installing FFDShow? You can try Video Control, and here is a sample on how you can play a video file. If you want something without DirectShow, you can take a look at VLC ActiveX. As a word of caution regarding the use of GPL plugins (FFDShow or VLC ActiveX) in non-GPL applications you should read this.
1,488,775
1,488,815
C++ Remove new line from multiline string
Whats the most efficient way of removing a 'newline' from a std::string?
#include <algorithm> #include <string> std::string str; str.erase(std::remove(str.begin(), str.end(), '\n'), str.cend()); The behavior of std::remove may not quite be what you'd expect. A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size. See an explanation of it here.
1,489,239
1,489,315
Do threads clean-up after themselves in Win32/MFC and POSIX?
I am working on a multithreaded program using C++ and Boost. I am using a helper thread to eagerly initialize a resource asynchronously. If I detach the thread and all references to the thread go out of scope, have I leaked any resources? Or does the thread clean-up after itself (i.e. it's stack and any other system resources needed for the itself)? From what I can see in the docs (and what I recall from pthreads 8 years ago), there's not explicit "destory thread" call that needs to be made. I would like the thread to execute asynchronously and when it comes time to use the resource, I will check if an error has occured. The rough bit of code would look something like: //Assume this won't get called frequently enough that next_resource won't get promoted //before the thread finishes. PromoteResource() { current_resource_ptr = next_resource_ptr; next_resource_ptr.reset(new Resource()); callable = bind(Resource::Initialize, next_resource); //not correct syntax, but I hope it's clear boost::thread t(callable); t.start(); } Of course--I understand that normal memory-handling problems still exist (forget to delete, bad exception handling, etc)... I just need confirmation that the thread itself isn't a "leak". Edit: A point of clarification, I want to make sure this isn't technically a leak: void Run() { sleep(10 seconds); } void DoSomething(...) { thread t(Run); t.run(); } //thread detaches, will clean itself up--the thread itself isn't a 'leak'? I'm fairly certain everything is cleaned up after 10 seconds-ish, but I want to be absolutely certain.
The thread's stack gets cleaned up when it exits, but not anything else. This means that anything it allocated on the heap or anywhere else (in pre-existing data structures, for example) will get left when it quits. Additionally any OS-level objects (file handle, socket etc) will be left lying around (unless you're using a wrapper object which closes them in its destructor). But programs which frequently create / destroy threads should probably mostly free everything that they allocate in the same thread as it's the only way of keeping the programmer sane.
1,489,249
1,489,350
Center QGraphicsView in Widget
I have a QDialog that contains several dock widgets and one QGraphicsView. The widget layout is set to grid, the QGraphicsView size policy is set to fixed on the 2 axes and it the QGraphicsView is center in the empty zone of the QDialog. I would like to resize my QGraphicsView and let it at the center of the empty zone of the QDialog. I have tried this code: // resize QGraphicsView ui->mProjectView->resize(mProject->getSize() + QSize(2,2)); But QGraphicsView is adjusting its size to QDialog when resizing QDialog. I'va tried then this: // resize QGraphicsView ui->mProjectView->resize(mProject->getSize() + QSize(2,2)); // Adjust size of QDialog to fit new widget's size ui->centralWidget->adjustSize(); But this does not work. QGraphics View keeps last size... I'm sure the way to achieve it is simple but I'm missing something. Can you help please?
You could try ui->mProjectView->setFixedSize(mProject->getSize() + QSize(2,2)); instead.
1,489,255
1,489,460
architecture/design advise for a test program
I am trying to build a test program in c++ to automate testing for a specific application. The testing will involve sending requests which have a field 'CommandType' and some other fields to a server The commandType can be 'NEW', 'CHANGE' or 'DELETE' The tests can be Send a bunch of random requests with no pattern Send 100 'NEW' requests, then a huge amount of 'CHANGE' requests followed by 200 'DELETE' requests Send 'DELETE' requests followed by 'CHANGE' requests ... and so on How can I design my software (what kind of modules or layers) so that adding any new type of test case is easy and modular? EDIT: To be more specific, this test will be to only test one specific application that gets requests of the type described above and handles them. This will be a client application that will send the requests to the server.
I would not create your own framework. There are many already written that follow a common pattern and can likely accomodate your needs elegantly. The xUnit framework in all incarnations I have seen allows you to add new test cases without having to edit the code that runs the tests. For example, CppUnit provides a macro that when added to a test case will auto-register the test case with a global registry (through static initialization I assume). This allows you to add new test cases without cracking open and editing the thing that runs them. And don't let the "unit" in xUnit and CppUnit make you think it is inappropriate. I've used the xUnit framework for all different kinds of testing.
1,489,313
1,489,335
C++ std::transform() and toupper() ..why does this fail?
I have 2 std::string. I just want to, given the input string: capitalize every letter assign the capitalized letter to the output string. How come this works: std::string s="hello"; std::string out; std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper); but this doesn't (results in a program crash)? std::string s="hello"; std::string out; std::transform(s.begin(), s.end(), out.begin(), std::toupper); because this works (at least on the same string: std::string s="hello"; std::string out; std::transform(s.begin(), s.end(), s.begin(), std::toupper);
There is no space in out. C++ algorithms do not grow their target containers automatically. You must either make the space yourself, or use a inserter adaptor. To make space in out, do this: out.resize(s.length()); [edit] Another option is to create the output string with correct size with this constructor. std::string out(s.length(), 'X');
1,489,674
1,489,704
From Static Typing to Dynamic Typing
I have always worked on statically typed languages (C/C++, Java). I have been playing with Clojure and I really like it. One thing I am worried about is: say that I have a windows that takes 3 modules as arguments and along the way the requirements change and I need to pass another module to the function. I just change the function and the compiler complains everywhere I used it. But in Clojure it won't complain until the function is called. I can just do a regex search and replace but it seems there is a chance to miss a call and it will go unnoticed until that function is actually called. How do you guys deal with this?
This is one of the reasons automated testing/test driven development is even more important in dynamically typed languages. I haven't used Clojure (I mostly use Ruby), so unfortunately I can't recommend a specific testing framework.
1,489,830
1,489,873
Efficient way to determine number of digits in an integer
What is a very efficient way of determining how many digits there are in an integer in C++?
Well, the most efficient way, presuming you know the size of the integer, would be a lookup. Should be faster than the much shorter logarithm based approach. If you don't care about counting the '-', remove the + 1. #include <climits> // generic solution template <class T> int numDigits(T number) { int digits = 0; if (number < 0) digits = 1; // remove this line if '-' counts as a digit while (number) { number /= 10; digits++; } return digits; } // partial specialization optimization for 64-bit numbers template <> int numDigits(int64_t x) { if (x == INT64_MIN) return 19 + 1; if (x < 0) return digits(-x) + 1; if (x >= 10000000000) { if (x >= 100000000000000) { if (x >= 10000000000000000) { if (x >= 100000000000000000) { if (x >= 1000000000000000000) return 19; return 18; } return 17; } if (x >= 1000000000000000) return 16; return 15; } if (x >= 1000000000000) { if (x >= 10000000000000) return 14; return 13; } if (x >= 100000000000) return 12; return 11; } if (x >= 100000) { if (x >= 10000000) { if (x >= 100000000) { if (x >= 1000000000) return 10; return 9; } return 8; } if (x >= 1000000) return 7; return 6; } if (x >= 100) { if (x >= 1000) { if (x >= 10000) return 5; return 4; } return 3; } if (x >= 10) return 2; return 1; } // partial specialization optimization for 32-bit numbers template<> int numDigits(int32_t x) { if (x == INT32_MIN) return 10 + 1; if (x < 0) return numDigits(-x) + 1; if (x >= 10000) { if (x >= 10000000) { if (x >= 100000000) { if (x >= 1000000000) return 10; return 9; } return 8; } if (x >= 100000) { if (x >= 1000000) return 7; return 6; } return 5; } if (x >= 100) { if (x >= 1000) return 4; return 3; } if (x >= 10) return 2; return 1; } // partial-specialization optimization for 8-bit numbers template <> int numDigits(char n) { // if you have the time, replace this with a static initialization to avoid // the initial overhead & unnecessary branch static char x[256] = {0}; if (x[0] == 0) { for (char c = 1; c != 0; c++) x[c] = numDigits((int32_t)c); x[0] = 1; } return x[n]; }
1,490,092
1,490,142
C/C++: Force Bit Field Order and Alignment
I read that the order of bit fields within a struct is platform specific. What about if I use different compiler-specific packing options, will this guarantee data is stored in the proper order as they are written? For example: struct Message { unsigned int version : 3; unsigned int type : 1; unsigned int id : 5; unsigned int data : 6; } __attribute__ ((__packed__)); On an Intel processor with the GCC compiler, the fields were laid out in memory as they are shown. Message.version was the first 3 bits in the buffer, and Message.type followed. If I find equivalent struct packing options for various compilers, will this be cross-platform?
No, it will not be fully-portable. Packing options for structs are extensions, and are themselves not fully portable. In addition to that, C99 §6.7.2.1, paragraph 10 says: "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined." Even a single compiler might lay the bit field out differently depending on the endianness of the target platform, for example.
1,490,100
1,490,140
How to efficiently copy istringstream?
Or ostringstream? istringstream a("asd"); istringstream b = a; // This does not work. I guess memcpy won't work either.
istringstream a("asd"); istringstream b(a.str()); Edit: Based on your comment to the other reply, it sounds like you may also want to copy the entire contents of an fstream into a strinstream. You don't want/have to do that one character at a time either (and you're right -- that usually is pretty slow). // create fstream to read from std::ifstream input("whatever"); // create stringstream to read the data into std::istringstream buffer; // read the whole fstream into the stringstream: buffer << input.rdbuf();
1,490,225
1,490,263
C++: Copy constructor: Use getters or access member vars directly?
I have a simple container class with a copy constructor. Do you recommend using getters and setters, or accessing the member variables directly? public Container { public: Container() {} Container(const Container& cont) //option 1 { SetMyString(cont.GetMyString()); } //OR Container(const Container& cont) //option 2 { m_str1 = cont.m_str1; } public string GetMyString() { return m_str1;} public void SetMyString(string str) { m_str1 = str;} private: string m_str1; } In the example, all code is inline, but in our real code there is no inline code. Update (29 Sept 09): Some of these answers are well written however they seem to get missing the point of this question: this is simple contrived example to discuss using getters/setters vs variables initializer lists or private validator functions are not really part of this question. I'm wondering if either design will make the code easier to maintain and expand. Some ppl are focusing on the string in this example however it is just an example, imagine it is a different object instead. I'm not concerned about performance. we're not programming on the PDP-11
Do you anticipate how the string is returned, eg. white space trimmed, null checked, etc.? Same with SetMyString(), if the answer is yes, you are better off with access methods since you don't have to change your code in zillion places but just modify those getter and setter methods.
1,490,286
1,490,340
"Pinnacle" of Encapsulation - Question Regarding Advice from Effective C++
Item 23 of Effective C++ states: Prefer non-member non-friend functions to member functions. The whole purpose of the item was to encourage encapsulation, as well as package flexibility and functional extensibility, but my question is how far do you go when it comes to taking this advice? For example, you could have your class, your private data members, and then take a minimalist approach by reducing public functions to only accessors and/or mutators for your private data members. Then, every single other function could be a non-member function. However, would you be willing to increase encapsulation at the possible sacrifice of code clarity with accessors and mutators all over the place? Where is the line drawn?
First, not everyone agrees with this advice. I don't think I've seen anyone but Meyers (edit: and Herb Sutter) give this advice, and I've only seen it given within the context of C++. For example, creating "non-member non-friend functions" in Java or C# isn't really possible, since Java and C# have no free functions, and Ruby developers (for example) prefer "humane interfaces" that intentionally create member functions that do the same thing non-members could, just to make life easier on those functions' callers. And even if you do accept Meyers' advice, that you should prefer non-member non-friend functions to member functions (and I think it's good advice, it certainly helped me apply encapsulation better to think of encapsulating a class's implementation even from its member functions), that's only one axis of design to consider. The key concept of object-oriented design is that objects do something. An object isn't simply a bag of setters and getters that other code does stuff to. Instead, it should have behavior attached - that is, it should have methods that do things - and it should encapsulate the details of how it does those things. If you follow this approach to OO, then carrying Meyers' advice to the extreme as you did hurts encapsulation rather than helping it: you end up exposing all of the class's internal implementation variables via getters and setters instead of hiding them so that only the class's methods (the code responsible for doing stuff on behalf of the class, which is the only reason you have a class to begin with) can get to it. So to answer your question of how far to take Meyers' advice: Don't needlessly turn functions into member functions if they could reasonably be implemented as non-friend non-member functions using a class's public interface, but don't damage a class's public interface and violate its encapsulation by exposing implementation just to avoid making something a member. And make sure you balance encapsulation against other concerns and other approaches (including, if your team decides to go that route, the pros and cons of a full-blown humane interface).
1,490,339
1,490,343
Best Type for UTF-8 data?
What is the best type, in C++, for storing UTF-8 string? I'd like to avoid rolling my own class if possible. My original thought was std::string — however, this uses char as the underlying type. char may be unsigned or signed — it varies. On my system, it's signed. UTF-8 code units, however, are unsigned octets. This seems to indicate that it's the wrong type. This leads us to std::basic_string<unsigned char> - which seems to fit the bill: unsigned, 8-bit (or larger) chars. However, most things seem to use char. glib, for example, uses char. C++'s ostream's use char. Thoughts?
I'd just use std::string, as it is consistent with the UTF-8 ideal of treating data just as you would null-terminated ASCII strings unless you actually need their unicode-ness. I also like GTKmm's Glib::ustring, but that only works if you're writing a GTKmm (or at least Glibmm) application.
1,490,593
1,491,828
Mixing RTTI flags in C++
If I have multiple linked C++ statically linked libraries in C++, is it possible for them to share (pass to and from functions) class objects if they have been compiled with differing values of enabled/disabled run time type information (RTTI)? --edit: Thanks for the responses, the specific things I was worried about was 1. Does enabling RTTI change the behaviour of sizeof for static (non polymorphic types)? and, 2. If I create a class in an RTTI enabled library and pass it to another non RTTI enabled library, do virtual methods work properly. (and vice versa) and lastly 3. If I create a class in an RTTI enabled library, I expect to be able to use dynamic_cast with it, if I pass that object to a non-RTTI enabled library, can I still use it on that object. ... I would assume not, and it seems like a bad idea anyway... I'm just curious.
How RTTI information is stored is an implementation detail and thus not portable across different compilers. Also most compilers do not even guarantee that objects compiled with different flags will use the same ABI for their methods. This is most prominently shown with release and debug libraries but other flags can cause differences as well. Not only may the ABI for functions/methods change but flags can affect the padding used by the compiler between elements in structures thus even objects without virtual methods may be incompatible when compiled with different flags. When using most IDS you can see the effects. Debug/Release binaries are built into separate directories and only linked against the same kind of binary (also any user defined build will be built into a separate unique directory as a difference in flags may cause incompatibilities). If you change certain flags on a build then the whole project is usually forced to re-build.
1,490,877
1,490,889
Structs in C++ can be modified? or there is a restriction?
I have this class which has a double list template of a struct of two chars and another struct typedef struct KeyC{ char K[5]; char C[9]; } TKeyC; typedef struct Bin{ char Car; char Cad[9]; TKeyC *KC; } TBin; class Bo { private: TDoubleList<TBin> *Ent; public: ... } I have a method to create nodes. No problem with this, but when I call other method to modify the direction of the pointer to a new TKeyC struct this simply doesn't happen. TNode<TBin> *Aux; TKeyC *AuxKC=new TKeyC; Aux->getObj().KC=AuxKC; Do I have to use a class instead of a struct in this case or is a problem of structs or there is a bug in it? Update template <class T> class TNode { private: T TObj; TNode<T> *Prev,*Next; public: TNode(); ~TNode(); TNode(T); void setObj(T); void sPrev(TNode<T>*); void sNext(TNode<T>*); T getObj(); TNode<T>* gPrev(); TNode<T>* gNext(); }; And the method getObj: template <class T> T TNode<T>::getObj() {return(TObj);};
A structure in C++ is a class whose members are all public. If your assignment isn't changing the value you want it to, then you are not assigning to what you think you are. Your getObj() function returns a copy of the structure, not a reference to the original. So you update the value in the copy, and the original remains unchanged. Get a reference to your object, either by changing the return type of getObj() to T& or adding another function if you have other code that depends on the behavior.
1,491,032
1,503,211
Is there any software or library available to draw screws in 3 dimensions in C, C++, Java, or Ruby?
Is there any software or library available to draw screws in 3 dimensions in C, C++, Java, or Ruby?
Iam not familiar with the topic but, May be this could help. Here
1,491,181
1,491,451
How to turn a function of 3 nested loops into one recursive function?
what would the recursive version for the following function would be like: void tri_loop(size_t i, size_t j, size_t k) { for(size_t x = 0; x < i; ++x) for(size_t y = 0; y < j; ++y) for(size_t z = 0; z < k; ++z) { cout << x <<y << z; } } Just for mental drilling.(Edit: emphasized this line)
void recurse(accumulator,b,c,d,limit) { if (limit == 0) printf("%i %i %i\n", b, c, d); else if (accumulator<limit) { recurse(accumulator+1,b,c,d,limit); recurse(0,accumulator,b,c,d); } } main() { int x=2,y=3,z=4; recurse(0,0,x,y,z); } Is that recursive enough?
1,491,491
1,491,570
Can I use std::stack as object pool container?
I need to create a pool of objects to eliminate dynamic allocations. Is it efficient to use std::stack to contain pointers of allocated objects? I suspect every time I push the released object back to stack a new stack element will be dynamically allocated. Am I right? Should I use std::vector to make sure nothing new is allocated?
Whether a stack is suited for your particular purpose or not is an issue I will not deal with. Now, if you are concerned about the number of allocations, the default internal container for a std::stack is an std::deque<>. It will not need to allocate new memory for the stack in each push (as long as it has space) and when it allocates it does not need to relocate all existing elements as an std::vector<> would. You can tell the stack to use an std::vector<> as underlying container with the second template argument: std::stack< int, std::vector<int> > vector_stack;
1,491,537
1,493,204
Can I use a "\n" character in strings that are to be translated with Qt Linguist
I'm working on supporting different languages for our GUI. I'm having a problem translating strings that have a '\n' in them. They seem to be ignored. In Qt Designer I have a QCheckBox with this in the text field: Here's an \nexample that doesn't work This appears in english in our french translation. Having looked at the .ts XML it seems that the text after the '\n' is ommited (I guess this is why it doesn't get translated ?) Does anyone have a way of including a newline in the original text? Seems I had carriage returns in my text before the newline. (no idea how they got there) e.g Here's an [][][][]\nexample that doesn't work After removing them, the translation worked.
The "\n" character itself was not my problem. Some invisible carriage returns in the string was the culprit. See http://qt.nokia.com/developer/task-tracker/index_html?method=entry&id=81275
1,491,671
1,493,216
How to format/change qmake build output
how can I format the make output (!!by only changing the qmake project file!!). My compilation lines continue growing, and the one-line-warnings/errors almost disappear between them. I am thinking of something like $(CC) in.ext -o out.ext thanks in regard
In qmake, you can add a silent configuration option: CONFIG += silent (note: I think that's the command. It's something similar to this.) Which should suppress most of the output, and only print lines like "compiling a.o", along with your warnings and errors. I believe this is similar to make's .SILENT. directive (I think that's the one...) You may want to be careful with this, however, because it suppresses a lot of information that error parsers like to use. For example, if you are compiling with a SUBDIRS configuration, it won't print out when it changes to the different directories.
1,491,716
1,492,059
best lib for vector array in c++
I have to do calculation on array of 1,2,3...9 dimensional vectors, and the number of those vectors varies significantly (say from 100 to up to couple of millions). Of course, it would be great if the data container can be easily decomposed to enable parallel algorithms. I came across blitz++(almost impossible to compile for me), but are there any other fast libs that manipulate array of vector data? Is boost::fusion worth a look? Furthermore, vtk's vtkDoubleArray seems nice, but vtk is lib used only for visualization. I must admit that having array of tuples is a tempting idea, but I didn't see any benchmarks regarding boost::fusion and/or vtkDoubleArray. Just as they are not built for speed in mind. Any thoughts? best regards, mightydodol
Eigen, supports auto-vectorisation of vector on certains compilers (GCC 4, VC++ 2008).
1,491,753
1,491,781
Can C++ automatic variables vary in size?
In the following C++ program: #include <string> using namespace std; int main() { string s = "small"; s = "bigger"; } is it more correct to say that the variable s has a fixed size or that the variable s varies in size?
It depends on what you mean by "size". The static size of s (as returned by sizeof(s)) will be the same. However, the size occupied on the heap will vary between the two cases. What do you want to do with the information?
1,491,971
1,492,158
MFC IMPLEMENT_DYNCREATE with template
Is there any way to use IMPLEMENT_DYNCREATE with a template class? If not, why not? Is there another solution to this? Example: template<typename T> class A : public B{ public: A(){ printf("A constuctor "); } void fn( ){ T* a = new T(); } }; IMPLEMENT_DYNCREATE(A<CObject>, B);
OK I've taken a quick look at the macros and thrown together a completely un tested macro that may work. #define _RUNTIME_CLASS(class_name, template_name) ((CRuntimeClass*)(&class_name<template_name>::class##class_name##template_name)) #define RUNTIME_CLASS(class_name, template_name) _RUNTIME_CLASS(class_name, template_name) #define _IMPLEMENT_RUNTIMECLASS( class_name, template_name, base_class_name, wSchema, pfnNew, class_init ) \ AFX_COMDAT CRuntimeClass class_name<template_name>::class##class_name##template_name = { \ #class_name, sizeof(class class_name<template_name>), wSchema, pfnNew, \ RUNTIME_CLASS(base_class_name), NULL, class_init }; \ CRuntimeClass* class_name<template_class::GetRuntimeClass() const \ { return RUNTIME_CLASS(class_name, template_name); } #define IMPLEMENT_DYNCREATE( class_name, template_name, base_class_name ) \ CObject* PASCAL class_name<template_name>::CreateObject() \ { return new class_name<template_name>; } \ IMPLEMENT_RUNTIMECLASS(class_name, template_name, base_class_name, 0xFFFF, \ class_name<template_name>::CreateObject, NULL) Then you can call: IMPLEMENT_DYNCREATE( A, CObject, B); Give it a try, as i say, it may work :D
1,492,087
1,492,208
What language would you use to implement auto-update/sync functionality on a memory stick?
We need to distribute documents to our partners on a USB key. I've been asked to develop a piece of software that will check if some documents have been updated on the server and proceed with the synchronization of files on the memory stick. The software itself will also need to have an auto-update functionality in case we want to improve it in the future. Where do you guys think I should start?
I'm assuming this is for Windows. C# would be an excellent choice, unless you can't be sure the user already has .Net installed. Otherwise I'd use Delphi, which can create native executables easily. The auto-update feature will be a pain no matter what language you use, given that a running EXE file can't replace itself. You can implement most of the program's functionality as a separate DLL which can be updated on the fly, but you're still SOL if you need to update the core EXE itself.
1,492,118
1,492,195
Which library would you consider on linux for DEA (Data Encryption Algorithm)?
I need a 3DES encrypt/decrypt library for my project. Do you know an implementation working on linux ? Linux is the target platform, but I essantially compile/debug on Windows. Therefore it could be really appreciated if it could work on Windows, while not mandatory.
OpenSSL is a very reputable, well tested open source security library. It's available for *nix and Windows. You can find it here Edit, can't find a simple example right now. The API documentation is pretty good though. There's a pre-compiled version for windows available for download from the openssl site. Most package managers will have a pre-packaged version of OpenSSL for Linux boxes, so you shouldn't have to compile your own version.
1,492,264
1,493,277
Deleting a method from Visual Studio properties window
The "Events", "Messages" and "Overrides" tabs in the Properties Window can be used to add new methods to a class as well as to remove them. However, when you select to "Delete" a method, it comments the method code instead of deleting it. I know this is for safety issues, but I almost never need the commented code and end up having to delete it manually. This is even more annoying in MFC, when I have to delete the method declaration, the method implementation and the entry on the message map which are usually on different places. Is there an option to simply delete the method code instead of just commenting it?
No there is no way of doing this, especially in C++ where there are too many places that directly or indirectly exist as part of the method declaration.
1,492,298
1,492,358
C++ expected type specifier error
I am trying to write a wrapper function to figure out who is calling a specific function. So in .h file I added the following: (and implementation in the .cc file) extern int foo(/*some arguments*/); extern void call_log(const char*file,const char*function,const int line,const char*args); #define foo(...) (call_log(__FILE__, __FUNCTION__, __LINE__, "" #__VA_ARGS__), foo(__VA_ARGS__)) However, I get the following error: error: expected a type specifier (call_log(__FILE__, __FUNCTION__, __LINE__, "" #__VA_ARGS__),foo(__VA_ARGS__) Assume that the foo function is called with some parameters and returns an int. the compiler is gcc 3.4 Thanks EDIT removed "." and extra spaced, yet problem still there. Can anyone see what can cause it. Also notice that I am using variadic macros -- supported by my compiler (c99) Edit 2 Just to get the claims about my illegal use of some c/c++ constructs. The following code below works, and I am trying to adapt it to my current (above function) #include <stdio.h> int funcA( int a, int b ){ return a+b; } // instrumentation void call_log(const char*file,const char*function,const int line,const char*args){ printf("file:%s line: %i function: %s args: %s\n",file,line,function,args); } #define funcA(...) \ (call_log(__FILE__, __FUNCTION__, __LINE__, "" #__VA_ARGS__), funcA(__VA_ARGS__)) // testing void funcB() { funcA(7,8); } int main(void){ int x = funcA(1,2)+ funcA(3,4); printf( "x: %i (==10)\n", x ); funcA(5,6); funcB(); } Edit 3 As litb pointed out, the problem is, in fact, due to macro substitutions. I also noticed that foo is not only a function call but also used as ptr->foo[] in some cases. Any ides how to resolve this sort of issues, without breaking more code
The best way to find out what's wrong would be to make the compiler show the preprocessed code. You can then easier spot the problem in the offending line.
1,492,504
1,492,548
How to manage object life time using Boost library smart pointers?
There is a scenario that i need to solve with shared_ptr and weak_ptr smart pointers. Two threads, thread 1 & 2, are using a shared object called A. Each of the threads have a reference to that object. thread 1 decides to delete object A but at the same time thread 2 might be using it. If i used shared_ptr to hold object A's references in each thread, the object wont get deleted at the right time. What should i do to be able to delete the object when its supposed to and prevent an error in other threads that using that object at the same time?
There's 2 cases: One thread owns the shared data If thread1 is the "owner" of the object and thread2 needs to just use it, store a weak_ptr in thread2. Weak pointers do not participate in reference counting, instead they provide a way to access a shared_ptr to the object if the object still exists. If the object doesn't exist, weak_ptr will return an empty/null shared_ptr. Here's an example: class CThread2 { private: boost::weak_ptr<T> weakPtr public: void SetPointer(boost::shared_ptr<T> ptrToAssign) { weakPtr = ptrToAssign; } void UsePointer() { boost::shared_ptr<T> basePtr; basePtr = weakPtr.lock() if (basePtr) { // pointer was not deleted by thread a and still exists, // so it can be used. } else { // thread1 must have deleted the pointer } } }; My answer to this question (link) might also be useful. The data is truly owned by both If either of your threads can perform deletion, than you can not have what I describe above. Since both threads need to know the state of the pointer in addition to the underlying object, this may be a case where a "pointer to a pointer" is useful. boost::shared_ptr< boost::shared_ptr<T> > or (via a raw ptr) shared_ptr<T>* sharedObject; or just T** sharedObject; Why is this useful? You only have one referrer to T (in fact shared_ptr is pretty redundant) Both threads can check the status of the single shared pointer (is it NULL? Was it deleted by the other thread?) Pitfalls: - Think about what happens when both sides try to delete at the same time, you may need to lock this pointer Revised Example: class CAThread { private: boost::shared_ptr<T>* sharedMemory; public: void SetPointer(boost::shared_ptr<T>* ptrToAssign) { assert(sharedMemory != NULL); sharedMemory = ptrToAssign; } void UsePointer() { // lock as needed if (sharedMemory->get() != NULL) { // pointer was not deleted by thread a and still exists, // so it can be used. } else { // other thread must have deleted the pointer } } void AssignToPointer() { // lock as needed sharedMemory->reset(new T); } void DeletePointer() { // lock as needed sharedMemory->reset(); } }; I'm ignoring all the concurrency issues with the underlying data, but that's not really what you're asking about.
1,492,513
1,494,213
Excel OpenText method
I keep getting the ambiguous error code of 0x800A03EC.   I've been searching quite a bit to see if I could find a specific reason for the error but unfortunately that code seems to cover a multitude of possible errors. I will copy and paste the code that seems to be giving me problems and hopefully someone will be able to provide me with some feedback on how I might solve the problem. I am using a method called AutoWrap that I came across in this kb21686  article.I'll add that method here: HRESULT AutoWrap(int autoType, VARIANT *pvResult, IDispatch *pDisp, LPOLESTR ptName, int cArgs...) { // Begin variable-argument list... va_list marker; va_start(marker, cArgs); if(!pDisp) { //MessageBox(NULL, "NULL IDispatch passed to AutoWrap()", "Error", 0x10010); MessageBox(NULL,_T("IDispatch error"),_T("LError"),MB_OK | MB_ICONEXCLAMATION); _exit(0); } // Variables used... DISPPARAMS dp = { NULL, NULL, 0, 0 }; DISPID dispidNamed = DISPID_PROPERTYPUT; DISPID dispID; HRESULT hr; char buf[200]; char szName[200]; // Convert down to ANSI WideCharToMultiByte(CP_ACP, 0, ptName, -1, szName, 256, NULL, NULL); // Get DISPID for name passed... hr = pDisp->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID); if(FAILED(hr)) { sprintf_s(buf, "IDispatch::GetIDsOfNames(\"%s\") failed w/err 0x%08lx", szName, hr); MessageBox(NULL, CString(buf), _T("AutoWrap()"), MB_OK | MB_ICONEXCLAMATION); _exit(0); return hr; } // Allocate memory for arguments... VARIANT *pArgs = new VARIANT[cArgs+1]; // Extract arguments... for(int i=0; i<cArgs; i++) { pArgs[i] = va_arg(marker, VARIANT); } // Build DISPPARAMS dp.cArgs = cArgs; dp.rgvarg = pArgs; // Handle special-case for property-puts! if(autoType & DISPATCH_PROPERTYPUT) { dp.cNamedArgs = 1; dp.rgdispidNamedArgs = &dispidNamed; } // Make the call! hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, autoType, &dp, pvResult, NULL, NULL); if(FAILED(hr)) { sprintf_s(buf, "IDispatch::Invoke(\"%s\"=%08lx) failed w/err 0x%08lx", szName, dispID, hr); MessageBox(NULL, CString(buf), _T("AutoWrap()"), MB_OK | MB_ICONEXCLAMATION); _exit(0); return hr; } // End variable-argument section... va_end(marker); delete [] pArgs; return hr; } Everything works fine up until I make this call: AutoWrap(DISPATCH_PROPERTYGET, &result, pXlBooks, L"OpenText",18,param1,vtMissing,vtMissing,paramOpt,paramOpt, vtMissing,vtMissing,vtMissing,paramTrue,vtMissing,vtMissing,vtMissing,vtMissing,vtMissing,vtMissing,vtMissing ,vtMissing,vtMissing); The parameters passed to the function are initialized as: VARIANT param1,paramOpt,paramFalse,paramTrue; param1.vt = VT_BSTR; paramOpt.vt = VT_I2; paramOpt.iVal = 1; paramFalse.vt = VT_BOOL; paramFalse.boolVal = 0; paramTrue.vt = VT_BOOL; paramTrue.boolVal = 1; //param1.bstrVal = ::SysAllocString(L"C:\\Documents and Settings\\donaldc\\My Documents\\DepositSlip.xls"); param1.bstrVal = ::SysAllocString(L"C:\\logs\\TestOut.txt"); If I uncomment the commented out param1 and make a call to Open and pass it that version of param1 everything works wonderfully. Unfortunately when Invoke is called on the OpenText method I get the 0x800A03EC error code. 90% of what I find when searching is performing automation using interop in C# and the other 10% is doing the same thing in VB and while the C# examples are helpful they don't help to explain the parameters being passed when using C++ very well. I feel like it's all a problem with parameters but I'm having difficulty in figuring out exactly what the problem with them is. Thanks in advance for any help you can offer and pelase let me know if I need to post more code.
From the KB article you linked to: One caveat is that if you pass multiple parameters, they need to be passed in reverse-order. From MSDN, the parameters to OpenText are: expression.OpenText(Filename, Origin, StartRow, DataType, TextQualifier, ConsecutiveDelimiter, Tab, Semicolon, Comma, Space, Other, OtherChar, FieldInfo, TextVisualLayout, DecimalSeparator, ThousandsSeparator, TrailingMinusNumbers, Local) So if param1 holds your filename then you are currently trying to pass that as the Local parameter and you aren't passing anything to the Filename parameter which is required
1,492,517
1,492,551
read matrix from a file in C C++
Just wonder, for a matrix stored in a file as what it is, i.e. each line in the file being a row of the matrix where elements are separated by space(s), how can I predetermine the size of the matrix, then create an array of the same size and read it into the array in C and C++? If you have some code example, that would be appreciated! Thanks and regards!
Something like this. You need to include vector, sstream and string. There is no need to find out the size of the vector in advance. std::vector<int> readRow(std::string row) { std::vector<int> retval; std::istringstream is(row); int num; while (is >> num) retval.push_back(num); return retval; } std::vector<std::vector<int> > readVector(std::istream &is) { std::string line; std::vector<std::vector<int> > retval; while (std::getline(is, line)) retval.push_back(readRow(line)); return retval; }
1,492,735
1,492,748
Differences between struct in C and C++
I am trying to convert a C++ struct to C but keep getting "undeclared identifier"? Does C++ have a different syntax for referring to structs? struct KEY_STATE { bool kSHIFT; //if the shift key is pressed bool kCAPSLOCK; //if the caps lock key is pressed down bool kCTRL; //if the control key is pressed down bool kALT; //if the alt key is pressed down }; I am using a variable of type KEY_STATE inside another structure: typedef struct _DEVICE_EXTENSION { WDFDEVICE WdfDevice; KEY_STATE kState; } DEVICE_EXTENSION, *PDEVICE_EXTENSION; results in error C2061: syntax error : identifier 'KEY_STATE' ...on the line KEY_STATE kState; I am building with the WDK compiler if that makes any difference. This is in a header file of course. I am porting C++ WDM driver to WDF and C. This is the MSDN article for C2061. An initializer may be enclosed by parentheses. To avoid this problem, enclose the declarator in parentheses or make it a typedef. This error could also be caused when the compiler detects an expression as a class template argument; use typename to tell the compiler it is a type. Changing KEY_STATE to typedef struct still causes this error and actually causes a lot more. There are no free parentheses or things in too many parentheses, that is the other thing the article suggests.
In C, the name of the type is struct KEY_STATE. So you have to declare the second struct as typedef struct _DEVICE_EXTENSION { WDFDEVICE WdfDevice; struct KEY_STATE kState; } DEVICE_EXTENSION, *PDEVICE_EXTENSION; If you do not want to write struct all the time, you can use a typedef declare KEY_STATE similar to DEVICE_EXTENSION: typedef struct _KEY_STATE { /* ... */ } KEY_STATE;
1,492,918
1,493,043
How do you get what kind of encoding your system uses in c/c++?
In linux terminal one would type locale charmap in order to see what kind of character-encoding your system uses, eg UTF-8. My question is how would you do this using c/c++. (I'm using linux) edit: I tried using nl_langinfo(CODESET) but I got ANSI_X3.4-1968 instead of UTF-8 (which is what I get when typing: locale charmap). Am I using nl_langinfo() wrong?
SETLOCALE(3) Linux Programmer’s Manual SETLOCALE(3) NAME setlocale - set the current locale SYNOPSIS #include <locale.h> char *setlocale(int category, const char *locale); DESCRIPTION The setlocale() function is used to set or query the program’s current locale. NL_LANGINFO(3) Linux Programmer’s Manual NL_LANGINFO(3) NAME nl_langinfo - query language and locale information SYNOPSIS #include <langinfo.h> char *nl_langinfo(nl_item item); DESCRIPTION The nl_langinfo() function provides access to locale information in a more flexible way than localeconv(3) does. Individual and additional elements of the locale categories can be queried. setlocale(3) needs to be executed with proper arguments before. Examples for the locale elements that can be specified in item using the constants defined in <langinfo.h> are: CODESET (LC_CTYPE) Return a string with the name of the character encoding used in the selected locale, such as "UTF-8", "ISO-8859-1", or "ANSI_X3.4-1968" (better known as US-ASCII). This is the same string that you get with "locale charmap". For a list of char‐ acter encoding names, try "locale -m", cf. locale(1).
1,492,982
1,514,510
Compiling an application that uses WinUsb
I am in the process of writing an application to communicate with Usb devices using WinUsb.dll. This is a user-mode library that allows communication with a device through winusb.sys installed as its driver in the kernel. I am writing this application in C++ with Visual Studio 2008. The header WinUsb.h is found in the Windows DDK so I add the include path "D:\WinDDK\7100.0.0\inc\ddk". I then get an error that Usb.h cannot be found which WinUsb.h includes, Usb.h is also in the ddk but in a different directory, so I add "D:\WinDDK\7100.0.0\inc\api" as an include dir. Once I add that path then everything goes in the toilet and I start getting compile errors in stdio.h and a bunch of other weird places. I really don't want to use the DDK build system and compiler in order to simply use this DLL, thats one of the main reasons I'm using WinUsb instead of writing a proper driver. Has anyone built an application using WinUsb.dll and Visual Studio?
I am working on writing a cross-platform USB library and using the DDK build environment would make my build process much more complicated. WinUsb is meant to be used by client applications for devices who load WinUsb.sys as their driver. However there doesn't seem to be a version of the WinUsb headers packaged for use in user-mode programs (not including UMDF drivers). What I ended up doing was copying the few headers that support winusb.h out of the DDK and into a private directory, I then reference that directory as an include directory during the build. These are the headers I needed to copy: POPPACK.h PSHPACK1.h usb.h usb100.h usb200.h winusb.h winusbio.h Once I had these included in a private directory and linked with winusb.lib in the DDK I was able to compile and run my project in Visual Studio. I don't know if I'd recommend this method as it could be bad when the headers change between DDK releases, but I will open a CONNECT bug to see if I can get MS to create a package of WinUsb headers for use in client user-mode applications.
1,493,000
1,493,181
What happens if I ReleaseMutex() twice?
The Microsoft documentation is silent about what happens if I mistakenly call ReleaseMutex() when the mutex is already unlocked. Details: I'm trying to fix up some Windows code without having access to the compiler. I realise that WinApi mutexes are all recursive, and reference-counted. If I were making use of that feature, it's obvious that the extra ReleaseMutex() call would prematurely decrement the reference counter. However, the code that I am looking at does not use the mutex recursively, so the reference count never gets higher than '1'. It does release the mutex more times than necessary... so what happens? Does the reference count go negative? Does it stay at zero (unlocked) and just return an ignorable error? (Naturally, this code doesn't actually check for errors when it calls these functions!)
peejay provided a good link in his comment to the ReleaseMutex documentation. I believe that this line from the documentation answers your question: The ReleaseMutex function fails if the calling thread does not own the mutex object. While it is not explicitly said, I think that releasing a mutex (the first time) causes the calling thread to no longer own the mutex object. Thus the second call will simply fail. Such an implementation would make sense too since it would allow easily detecting this type of error (Just check the return value).
1,493,045
1,493,054
How to initialize a static member
I want to initialize two static data members. See the two files // Logger.h class Logger { public: static LoggerConcrete error; static LoggerConcrete write; }; and //Logger.cpp Logger::error = LoggerConcrete(LOG_DEBUG); Logger::write = LoggerConcrete(LOG_DEBUG); The initilization of the two static members in Logger.cpp doesn't work. I get the following compiler (g++) error: g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Logger.d" -MT"Logger.d" -o"Logger.o" "../Logger.cpp" ../Logger.cpp:13: error: expected constructor, destructor, or type conversion before '=' token ../Logger.cpp:14: error: expected constructor, destructor, or type conversion before '=' token I want to use Logger::write and Logger::error in each class in which I include Logger.h. How do I have to initialize these two members?
You need to specify the type: LoggerConcrete Logger::error = LoggerConcrete(LOG_DEBUG); LoggerConcrete Logger::write = LoggerConcrete(LOG_DEBUG);
1,493,450
1,559,535
Adobe Dreamweaver Extensions
Does anyone know if its possible to turn off dreamweavers "custom icons" that it shows in the file browser so you can see the standard system-cache ones instead? Something I'm trying to do via an extension but I cant find where its coming from in the large pile of XML files that is dreamweaver. As the guy below pointed out this isn't available in the API; does anyone know a way of disabling the icons elsewhere (i.e which of the hundreds of files the icons are stored in) so I can in theory patch the file... can see that upsetting adobe but who cares. Literally Looking for an if so, how. Ta
Its actually impossible via the extension interface; but is possible by editing the Dreamweaver library files. Rubbish solution though and would never make it through adobe-exchange
1,493,524
1,493,592
How to handle different protocol versions transparently in c++?
This is a generic C++ design question. I'm writing an application that uses a client/server model. Right now I'm writing the server-side. Many clients already exist (some written by myself, others by third parties). The problem is that these existing clients all use different protocol versions (there have been 2-3 protocol changes over the years). Since I'm re-writing the server, I thought it would be a great time to design my code such that I can handle many different protocol versions transparently. In all protocol versions, the very first communication from the client contains the protocol version, so for every client connection, the server knows exactly which protocol it needs to talk. The naive method to do this is to litter the code with statements like this: if (clientProtocolVersion == 1) // do something here else if (clientProtocolVersion == 2) // do something else here else if (clientProtocolVersion == 3) // do a third thing here... This solution is pretty poor, for the following reasons: When I add a new protocol version, I have to find everywhere in the source tree that these if statements are used, and modify them to add the new functionality. If a new protocol version comes along, and some parts of the protocol version are the same as another version, I need to modify the if statements so they read if (clientProtoVersion == 5 || clientProtoVersion == 6). I'm sure there are more reasons why it's bad design, but I can't think of them right now. What I'm looking for is a way to handle different protocols intelligently, using the features of the C++ langauge. I've thought about using template classes, possibly with the template parameter specifying the protocol version, or maybe a class heirarchy, one class for each different protocol version... I'm sure this is a very common design pattern, so many many people must have had this problem before. Edit: Many of you have suggested an inheritance heirarchy, with the oldest protocol version at the top, like this (please excuse my ASCII art): IProtocol ^ | CProtoVersion1 ^ | CProtoVersion2 ^ | CProtoVersion3 ... This seems like a sensible thing to do, in terms of resuse. However, what happens when you need to extend the protocol and add fundamentally new message types? If I add virtual methods in IProtocol, and implement these new methods in CProtocolVersion4, how are these new methods treated in earlier protocol versions? I guess my options are: Make the default implementation a NO_OP (or possibly log a message somewhere). Throw an exception, although this seems like a bad idea, even as I'm typing it. ... do something else? Edit2: Further to the above issues, what happens when a newer protocol message requires more input than an older version? For example: in protocl version 1, I might have: ByteArray getFooMessage(string param1, int param2) And in protocol version 2 I might want: ByteArray getFooMessage(string param1, int param2, float param3) The two different protocol versions now have different method signatures, which is fine, except that it forces me to go through all calling code and change all calls with 2 params to 3 params, depending on the protocol version being used, which is what I'm trying to avoid in the first place! What is the best way of separating protocol version information from the rest of your code, such that the specifics of the current protocol are hidden from you?
Since you need to dynamically choose which protocol to use, using different classes (rather than a template parameter) for selecting the protocol version seems like the right way to go. Essentially this is Strategy Pattern, though Visitor would also be a possibility if you wanted to get really elaborate. Since these are all different versions of the same protocol, you could probably have common stuff in the base class, and then the differences in the sub classes. Another approach might be to have the base class be for the oldest version of the protocol and then have each subsequent version have a class that inherits from the previous version. This is a somewhat unusual inheritance tree, but the nice thing about it is that it guarantees that changes made for later versions don't affect older versions. (I'm assuming the classes for older versions of the protocol will stabilize pretty quickly and then rarely ever change. However you decide to organize the hierarchy, you'd then want to chose the protocol version object as soon as you know the protocol version, and then pass that around to your various things that need to "talk" the protocol.
1,493,540
2,200,911
Troubleshooting Assembly Linker Error, C++, VS 2005
Using Visual Studio 2005 with the latest Service Pack. I have a managed C++ solution with 38 projects (that I've just inherited.) When I build this solution, I'm receiving the following error from the Assembly Linker: "error AL1019: Metadata failure while creating assembly -- The process cannot access the file because it is being used by another process." I'm kind of at a loss as to how to resolve or troubleshoot this. The surrounding steps in the build output are: Writing Resource File... Done. Compiling resources... Linking... Creating library [PATH]\[FileName].lib and object [PATH]\[FileName].exp Creating resource satellites... Error Occurs Here. There is no difference in the results between Build vs Rebuild vs Project Only with or without Cleaning the Solution first. And, in all cases, the DLL, EXP, ILK, LIB and PDB files for this project are created. I've compared this particular project to other projects in the solution that are structured similarly and see no appreciable differences. I've looked at the batch files and temporary rsp files that get generated during the build process and see nothing that jumps out there either. My current speculation is that the Linker is trying to embed the Intermediate Manifest file into the assembly while something else is still trying to write to the same Intermediate Manifest file (or to the assembly itself.) Though, I'm kind of guessing at this point. If anyone knows how to resolve this or has any insight as to what else to look into to try and troubleshoot I'd greatly appreciate it. Thanks. A sanitized version of the end of my build log, if it helps: /ASSEMBLYRESOURCE:".\Debug\[Namespace].[ErringProject].dll.licenses" ] Creating command line "link.exe @[Path]\[ErringProject]\Debug\RSP00030A20042852.rsp /NOLOGO /ERRORREPORT:PROMPT" Creating temporary file "[Path]\[ErringProject]\Debug\RSP00030B20042852.rsp" with contents [ /out:"[OutputPath]\[Namespace].[ErringProject].dll" /c:Run /template:"..\..\..\..\..\Run\[Namespace].[ErringProject].dll" /embed:".\Debug\[Namespace].StringsNT.resources" /embed:".\Debug\[Namespace].Strings.resources" ] Creating command line "al.exe @[Path]\[ErringProject]\Debug\RSP00030B20042852.rsp /nologo"
Finally tracked this down to the order of the XML Filter Collections in the Project file when using the external resource compiler (i.e. resgen.) The failing project had, in its Proj file: <files> <Filter Name="Header Files" ...> ... </Filter> <Filter Name="Resource Files" ...> ... </Filter> <Filter Name="Source Files" ...> ... </Filter> </files> Switching that to: <files> <Filter Name="Header Files" ...> ... </Filter> <Filter Name="Source Files" ...> ... </Filter> <Filter Name="Resource Files" ...> ... </Filter> </files> Did the trick.
1,493,581
1,504,635
How to go about benchmarking a software rasterizer
Ok, ive been developing a software rasterizer for some time now, but have no idea how to go about benchmarking it to see if its actually any good.... i mean say you can render X amount of verts ant Y frames per second, what would be a good way to analyse this data to see if its any good? rather than someone just saying "30 fps with 1 light is good" etc?
What do you want to measure? I suggest fillrate and triangle rate. Basically fillrate is how many pixels your rasterizer can spit out each second, Triangle rate is how many triangles your rasterizer + affine transformation functions can push out each second, independent of the fillrate. Here's my suggestion for measuring both: To measure the fillrate without getting noise from the time used for the triangle setup, use only two triangles, which forms a quad. Start with a small size, and then increase it with a small interval. You should eventually find an optimal size with respect to the render time of one second. If you don't, you can perform blending, with full-screen triangle pairs, which is a pretty slow operation, and which only burns fillrate. The fillrate becomes width x height of your rendered triangle. For example, 4 megapixels / second. To measure the triangle rate, do the same thing; only for triangles this time. Start with two tiny triangles, and increase the number of triangles until the rendering time reaches one second. The time used by the triangle/transformation setup is much more apparent in small triangles than the time used to fill it. The units is triangle count/second. Also, the overall time used to render a frame might be comparable too. The render time for a frame is the derivative of the global time, i.e delta time. The reciprocal of the delta time is the number of frames per second, if that delta time was constant for all frames. Of course, for these numbers to be half-way comparable across rasterizers, you have to use the same techniques and features. Comparing numbers from a rasterizer which uses per-pixel lighting against another which uses flat-shading doesn't make much sense. Resolution and color depth should also be equal. As for optimization, getting a proper profiler should do the trick. GCC has the GNU profiler gprof. If you want an opinion on clever things to optimize in a rasterizer, ask that as a seperate question. I'll answer to the best of my ability.
1,493,652
1,494,634
display map every time it is updated sorted by value
basically, I have the map<std::string, int> so if i have foo 5 bar 10 jack 3 in the map, I want to display it (notice the reverse order) bar 10 foo 5 jack 3 And every time it is updated, I want iterate through all the elements, cout them, sorted by value. What is the good way to implement that? should I provide a comparator to the constructor? I want to note that values in the map will be updated at least 100 million times, so efficiency is crucial, where as extra-space is no problem Please no Boost solutions...thx
struct keyval_t { std::string key; int val; }; int operator<(const keyval_t &a, const ketval_t &b) { return a.val<b.val || (a.val==b.val && a.key<b.key); } Then you need one map and one set: map<std::string, int>; set<keyval_t>; On update, you need to look up the map first to determine the key-value pair and then update both map and set. On printing, you just iterate through the set. In terms of theoretical time complexity, this is optimal. It doubles the memory, though. Does this meet your goal? To reduce memory, you may consider the following: map<std::string,uint64_t>; set<uint64_t>; The value of the map (also the key of the set) is: (uint64_t)val<<32|counter, where counter is something that differentiates identical values. For example, whenever you insert a key, increase the counter by 1. You do not need to update the counter when you update the value. If you do not like uint64_t, use pair<int,int> instead. This solution is also faster as it avoids comparisons between strings.
1,493,904
1,493,925
Can I increment a char* passed to a function?
I'm working on a C++ application that will build a fixed-length record from a set of database fields. I'm writing a function that will accept the output record as a char*, the string to write, and the total length of the field. The purpose of the function is to copy the string to the current position of the char pointer, and then fill the rest of the length with spaces. Here's a simplified example of what I'm doing. void writeOut(char* output, string data, const int length) { if ((int) data.size() > length) { //Just truncate it data = data.substr(0, length); } int index = 0; while (index < (int) data.size()) { *output++ = data[index++]; } while (index++ < length) { *output++ = ' '; } } int test() { char output[100]; writeOut(output, "test1", 10); writeOut(output, "test2", 10); writeOut(output, "test3test4test5", 10); cout << output; } I expected to see something like this. test1 test2 test3test4 Instead all I get is... test3test4 So it's incrementing the char* within the function, but only within the function. When the function ends the char* is right back where it started. Is it possible to pass a pointer in such a way that the pointer is updated in the calling function? In case you can't tell, I'm pretty new to C++. Any suggestions will be appreciated.
Since you are not passing your arguments by reference, the compiler creates a copy of the pointer and modifies the copy accordingly within the function. Change your function signature to the following. void writeOut(char*& output, string data, const int length) You may also want to consider passing string as const string& if you don't plan to modify it.
1,493,933
1,494,002
How to prevent a function from being optimized
I am optimizing the entire code, yet I dont want a certain function from being optimized, say for debugging purposes. Is there a way to do it on gcc 3.4+ compiler?
Easiest way, place the function in its own compilation unit, compile that one without optimization flags. Recent gcc versions (4.4+ I think) have an attribute to control optimization per functions, use __attribute__((optimize(0))) on the function to disable optimizations
1,494,010
1,494,926
AV while iterating through hash_map?
_transaction is a private member variable of my class, declared as: public: typedef stdext::hash_map<wchar_t*, MyClass*, ltstr> transaction_hash_map; private: transaction_hash_map _transactions; During cleanup I am trying to iterate through this list and free up any objects still unfreed. However I am getting an AV on the for line here: for (transaction_hash_map::const_iterator it = _transactions.begin(); it != _transactions.end(); it++) { MyClass* item = (MyClass*)it->second; if (item != NULL) { item->End(); delete item; } } Re: What is ltstr? private: struct ltstr { enum { bucket_size = 8, min_buckets = 16 }; bool operator()(wchar_t* s1, wchar_t* s2) const { return wcscmp( s1, s2 ) < 0; } size_t operator()(wchar_t *s1) const { size_t h = 0; wchar_t *p = const_cast<wchar_t*>(s1); wchar_t zero = L'\0'; while ( *p != zero ) h = 31 * h + (*p++); return h; } }; The stack shows it inside the begin() method. Any ideas?
One possible thing I can think of is that your class has already been deleted elsewhere before you try to iterate through the hash_map, and thus begin() will be operating on garbage. Worth a check... Also - how are your wchar_t*'s getting allocated/freed? The code you've shown doesn't appear to be dealing with those. I'm not sure how that would cause trouble in your loop, but it's worth thinking about. One minor thing - you shouldn't need the (MyClass*) cast. The hash_map's values should be of that type anyway, so it's nicer to let the compiler enforce type checks than to possibly bypass them with an explicit cast. That shouldn't be making any difference here though.
1,494,109
1,494,154
Is it bad that C++0x's lambda expressions don't have a named type?
I've been reading a bit about lambda expressions on the internet recently and it seems to me that C++0x's lambda expressions will not have a single type (or types) that will bind exclusively to lambda expressions -- in other words, lambda expressions will only match template arguments or auto arguments/variables. What happens, as described here, is that Compilers that support lambdas will create a unique anonymous functor type for each lambda expression My question is, is that a bad thing? Wouldn't it make sense to have some keyword that matches only to lambda expressions, e.g. lambda, which would work as follows void f(std::function<int(int)> func) { func(2); } template<typename T> void g(T func) { func(2); } void h(lambda func) { func(2); } int main() { int fpointer(int); struct { int operator()(int var) { return var; } } functor; f(fpointer); //ok (actually a linker error, but for the sake of example) f(functor); //ok f([](int var) { return var; }); //ok g(fpointer); //ok g(functor); //ok g([](int var) { return var; }); //ok h(fpointer); //error -- function pointer isn't a lambda expr h(functor); //error -- functor isn't a lambda expr h([](int var) { return var; }); //ok return 0; } To be honest, I actually can't see the usefulness of this (especially given that auto accepts lambda expressions, so one could then assign a lambda to a variable), but it still doesn't sit right with me that lambda expressions are anonymous types and cannot be bound specifically to just one particular type (to the exclusion of all others). In essence, my question is, is it fine that lambda expressions are anonymous (both in terms of utility -- does the lack of a lambda type devoid us of some functionality -- and philosophically -- does it really make sense that lambda expressions always have the 'type' auto)?
Lambdas are independent types. The code void h(lambda func) { func(2); } doesn't make any sense because lambdas don't have runtime polymorphism. Recall that a lambda is the equivalent of struct unique_name { return_type operator()(Arg1 a1, Arg2 a2, ... , Argn an) { code_inside_lambda; } } Which is itself a unique type. The code above would be the same as saying void h(class C) { C(2); } Which also makes no sense even if we assure that C has operator(). You need a template: template<typename T> void g(T func) { func(2); } int main() { g([](int x){return x + 2;}); }
1,494,122
1,494,165
Performance issues with hard disk reading
I have a C++ program which reads files from the hard disk and does some processing on the data in the files. I am using standard Win32 APIs to read the files. My problem is that this program is blazingly fast some times and then suddenly slows down to 1/6th of the previous speed. If I read the same files again and again over multiple runs, then normally the first run will be the slowest one. Then it maintains the speed until I read some other set of files. So my obvious guess was to profile the disk access time. I used perfmon utility and measured the IO Read Bytes/sec for my program. And as expected there was a huge difference (~ 5 times) in the number of bytes read. My questions are: (1). Does OS (Windows in my case) cache the recently read files somewhere so that the subsequent loads are faster? (2). If I can guarantee that all the files I read reside in the same directory then is there any way I can place them in the hard disk so that my disk access time is faster? Is there anything I can do for this?
1) Windows does cache recently read files in memory. The book Windows Internals includes an excellent description of how this works. Modern versions of Windows also use a technology called SuperFetch which will try to preemptively fetch disk contents into memory based on usage history and ReadyBoost which can cache to a flash drive, which allows faster random access. All of these will increase the speed with which data is accessed from disk after the initial run. 2) Directory really doesn't affect layout on disk. Defragmenting your drive will group file data together. Windows Vista on up will automatically defragment your disk. Ideally, you want to do large sequential reads and minimize your writes. Small random accesses and interleaving writes with reads significantly hurts performance. You can use the Windows Performance Toolkit to profile your disk access.
1,494,164
1,494,479
Memory corrupt in adding string to vector<string> loop
This is on Visual Studio 2008 on a dual-core, 32 bit Vista machine. In the debug code this runs fine, but in Release mode this bombs: void getFromDB(vector<string>& dates) { ... sql::Resultset res = stmt->executeQuery("SELECT FROM ..."); while (res->next()) { string date = res->getString("date"); dates.push_back(date); } // <<< crashing here (line 56) delete res; } The MySQL C++ connector has this method in it's ResultSet: virtual std::string getString(const std::string& columnLabel) const = 0; For some reason in the release compiled (against a MySQL C++ connector DLL) this crashes at the end of the loop with a heap corruption: HEAP[sa-ms-release.exe]: Invalid address specified to RtlFreeHeap( 024E0000, 001C4280 ) Windows has triggered a breakpoint in sa-ms-release.exe. ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes ntdll.dll!_RtlpValidateHeapEntry@12() + 0x713e8 bytes ntdll.dll!_RtlDebugFreeHeap@12() + 0x9a bytes ntdll.dll!@RtlpFreeHeap@16() + 0x145cf bytes ntdll.dll!_RtlFreeHeap@12() + 0xed5 bytes kernel32.dll!_HeapFree@12() + 0x14 bytes > sa-ms-release.exe!free(void * pBlock=0x001c4280) Line 110 C sa-ms-release.exe!std::allocator<char>::deallocate(char * _Ptr=0x001c4280, unsigned int __formal=32) Line 140 + 0x9 bytes C++ sa-ms-release.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Tidy(bool _Built=true, unsigned int _Newsize=0) Line 2158 C++ sa-ms-release.exe!std::basic_string<char,std::char_traits<char>,std::allocator<char> >::~basic_string<char,std::char_traits<char>,std::allocator<char> >() Line 907 C++ sa-ms-release.exe!StyleData:: getFromDB( std::vector<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > & dates) Line 56 + 0x69 bytes C++ I think I may be violating some basic C++ rule that causes the destructor to be called on a string I want to preserve inside the vector. If I replace string date = res->getString("date") with string date = string ("2008-11-23"); everything works fine. It seems to have to do with the string returned from the MySQL C++ Connector getString() method. The returned string is destroyed and that causes the problem, I guess. But more likely something else is wrong. I am using the release (opt) MySQL connector.
imho, problem may arise from VS run time libraries.That means, DLL you use for sql connector methods are compiled not with "multi thread dll" code generation option.So different versions of strings are passed through parameters and they chrash.I think you should check this code generation flag.
1,494,182
1,495,582
Setting the internal buffer used by a standard stream (pubsetbuf)
I'm writing a subroutine that needs to write data to an existing buffer, and I would like to use the stringstream class to facilitate the formatting of the data. Initially, I used the following code to copy the contents of the stream into the buffer, but would like to avoid this solution as it copies too much data. #include <sstream> #include <algorithm> void FillBuffer(char* buffer, unsigned int size) { std::stringstream message; message << "Hello" << std::endl; message << "World!" << std::endl; std::string messageText(message.str()); std::copy(messageText.begin(), messageText.end(), buffer); } This is when I discovered the streambuf::pubsetbuf() method and simply rewrote the above code as follows. #include <sstream> void FillBuffer(char* buffer, unsigned int size) { std::stringstream message; message.rdbuf()->pubsetbuf(buffer, size); message << "Hello" << std::endl; message << "World!" << std::endl; } Unfortunately, this does not work under the C++ standard library implementation that ships with Visual Studio 2008; buffer remains unchanged. I looked at the implementation of pubsetbuf and it turns out that it literally "does nothing". virtual _Myt *__CLR_OR_THIS_CALL setbuf(_Elem *, streamsize) { // offer buffer to external agent (do nothing) return (this); } This appears to be a limitation of the given C++ standard library implementation. What is the recommended way to configure a stream to write its contents to a given buffer?
After some more research on this problem, and scrutiny of my code, I came across a post suggesting the use of a hand-coded std::streambuf class. The idea behind this code is to create a streambuf that initializes its internals to refer to the given buffer. The code is as follows. #include <streambuf> template <typename char_type> struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> > { ostreambuf(char_type* buffer, std::streamsize bufferLength) { // set the "put" pointer the start of the buffer and record it's length. setp(buffer, buffer + bufferLength); } }; Now if you look at my original code, you will notice that I didn't really need a stringstream to begin with. All I really needed was a way to write to an external buffer using the IOStream library and std::ostream is a much better type to address this problem. Incidentally, I suspect this is how the array_sink type from Boost.IOStreams is implemented. Here is the modified code that uses my ostreambuf type. #include <ostream> #include "ostreambuf.h" // file including ostreambuf struct from above. void FillBuffer(char* buffer, unsigned int size) { ostreambuf<char> ostreamBuffer(buffer, size); std::ostream messageStream(&ostreamBuffer); messageStream << "Hello" << std::endl; messageStream << "World!" << std::endl; }
1,494,231
1,494,267
How to get a timestamp older than 1901
I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]). Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?
In python, there's the datetime module. Specifically, the date class will help. from datetime import date print date(1850, 1, 1).weekday() # 1, which is Tuesday # (Mon is 0) Edit Or, to your specific problem, working with timedelta will help out. from datetime import datetime td = datetime.now() - datetime(1850, 1, 1) print (86400*td.days)+td.seconds # seconds since then till now
1,494,399
1,494,435
How do I Search/Find and Replace in a standard string?
How do I replace all occurrences of a substring with another string, for std::strings? std::string s ("One hello, two hellos."); s = s.replace("hello", "world"); // something like this
Why not implement your own replace? void myReplace(std::string& str, const std::string& oldStr, const std::string& newStr) { std::string::size_type pos = 0u; while((pos = str.find(oldStr, pos)) != std::string::npos){ str.replace(pos, oldStr.length(), newStr); pos += newStr.length(); } }
1,494,407
1,494,530
Undefined symbol _main when trying to build shared library g++ / mac
I am trying to build libdecodeqr on a mac. My c++ building and linking history is all on windows, so it's an exciting journey of discovery. I have finally got to the point where I want to create the linked library. The command I am running is: g++ -shared -o libdecodeqr.so.0.9.3 bitstream.o codedata.o container.o ecidecoder.o formatinfo.o galois.o imagereader.o libdecodeqr.o -L/opt/local/lib -arch i386 -lcxcore -lcv The result is: Undefined symbols: "_main", referenced from: start in crt1.10.5.o I was under the impression that a creating a library using -shared flag meant I shouldn't need a main function. There certainly isn't one in the source code. Just for kicks I added int main() {return 0;} to one of the cpp files and rebuilt. The whole thing compiled and linked, but when I tried to use the output as a library I got errors telling me that I can't link to a main executable. That makes sense I guess. Is there something else I need to pass to g++ to tell it to build a library?
-shared is not supported on OSX. Use either -dynamiclib or -bundle (depending on which type of shared library you want to create).
1,494,423
1,494,767
How To Prepare An ActiveX Control For Delivery Over The Web
So i have the misfortune of embedding this proprietary ActiveX control we created into a web page so that it downloads the code from our server and installs as necessary. Our ActiveX requires a host of other files which need to be installed along with the activex control itself. It should also be noted that the activex and all its dependencies are c++-based COM objects (many use MFC). So I read this article about it: http://msdn.microsoft.com/en-us/library/aa751974(VS.85).aspx But it leaves a lot of things unanswered. For one thing, my ActiveX is actually embedded in a DLL file that contains other COM interfaces. Also, is it possible to have the mentioned cab file include the ActiveX/SDK installer and run that if the GUID isn't present? For example: [version] signature="$CHICAGO$" AdvancedINF=2.0 [Add.Code] Setup.exe=Setup.exe [Setup.exe] file-win32-x86=thiscab run=%EXTRACT_DIR%\Setup.exe Security is not an issue here as this is an intranet-based solution (not available publically). Also, the article mentioned here seems really old. Is there more up to date info available?
You can create a dependency between the installer and a dll that is on the system like this: [Add.Code] Your-dll-name [Your-dll-name] Version=Your dll version hook=setup.exe [Setup.exe] file-win32-x86=thiscab run=%EXTRACT_DIR%\Setup.exe If the system cannot find your dll or the version is lower, then it will run the setup.exe that suppose to install and register the dll.