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,262,404
1,330,801
Access Motherboard information without using WMI
I need to access motheroard identification (serial, manufacture, etc) in my application on multiple processes. I have been able to successfully query this using WMI, but I'm looking for an alternative. If you care to know situation: I have some application behavior that is different depending on the hardware configuration, or if a particular environment variable is set (for testing purposes). bool IsVideoCardDisplay = ( getenv("Z_VI_DISPLAY") || !QueryWmiForSpecialBoard() ) ? false : true; When the environment variable is set the WMI query isn't necessary--the application runs fine. However, when the environment variable is not present some of the components of my app fail to launch when is necessary to make the the WMI queries. I suspect that there may be some side effects of the WMI calls (which only a maximum of happen once per processes. This is why I'm seeking an alternative way.
Apparently there is no way to do this, which is unfortunate.
1,262,715
1,262,750
Reading std::string from binary file
I have a couple of functions I created a while ago for reading and writing std::strings to a FILE* opened for reading in binary mode. They have worked fine before (and WriteString() still works) but ReadString() keeps giving me memory corruption errors at run-time. The strings are stored by writing their size as an unsigned int before the string data as char. bool WriteString(std::string t_str, FILE* t_fp) { // Does the file stream exist and is it valid? If not, return false. if (t_fp == NULL) return false; // Create char pointer from string. char* text = const_cast<char*>(t_str.c_str()); // Find the length of the string. unsigned int size = t_str.size(); // Write the string's size to the file. fwrite(&size, sizeof(unsigned int), 1, t_fp); // Followed by the string itself. fwrite(text, 1, size, t_fp); // Everything worked, so return true. return true; } std::string ReadString(FILE* t_fp) { // Does the file stream exist and is it valid? If not, return false. if (t_fp == NULL) return false; // Create new string object to store the retrieved text and to return to the calling function. std::string str; // Create a char pointer for temporary storage. char* text = new char; // UInt for storing the string's size. unsigned int size; // Read the size of the string from the file and store it in size. fread(&size, sizeof(unsigned int), 1, t_fp); // Read [size] number of characters from the string and store them in text. fread(text, 1, size, t_fp); // Store the contents of text in str. str = text; // Resize str to match the size else we get extra cruft (line endings methinks). str.resize(size); // Finally, return the string to the calling function. return str; } Can anyone see any problems with this code or have any alternative suggestions?
Biggest major problem that jumped out at me: // Create a char pointer for temporary storage. char* text = new char; // ... // Read [size] number of characters from the string and store them in text. fread(text, 1, size, t_fp); This creates text as a pointer to a single character, and then you try to read an arbitrary number of characters (potentially many more than one) into it. In order for this to work right, you would have to create text as an array of characters after you figured out what the size was, like this: // UInt for storing the string's size. unsigned int size; // Read the size of the string from the file and store it in size. fread(&size, sizeof(unsigned int), 1, t_fp); // Create a char pointer for temporary storage. char* text = new char[size]; // Read [size] number of characters from the string and store them in text. fread(text, 1, size, t_fp); Second, you don't free the memory that you allocated to text. You need to do that: // Free the temporary storage delete[] text; Finally, is there a good reason why you are choosing to use C file I/O in C++? Using C++-style iostreams would have alleviated all of this and made your code much, much shorter and more readable.
1,262,808
1,263,122
Which STL container should I use for a FIFO?
Which STL container would fit my needs best? I basically have a 10 elements wide container in which I continually push_back new elements while pop_front ing the oldest element (about a million time). I am currently using a std::deque for the task but was wondering if a std::list would be more efficient since I wouldn't need to reallocate itself (or maybe I'm mistaking a std::deque for a std::vector?). Or is there an even more efficient container for my need? P.S. I don't need random access
Since there are a myriad of answers, you might be confused, but to summarize: Use a std::queue. The reason for this is simple: it is a FIFO structure. You want FIFO, you use a std::queue. It makes your intent clear to anybody else, and even yourself. A std::list or std::deque does not. A list can insert and remove anywhere, which is not what a FIFO structure is suppose to do, and a deque can add and remove from either end, which is also something a FIFO structure cannot do. This is why you should use a queue. Now, you asked about performance. Firstly, always remember this important rule of thumb: Good code first, performance last. The reason for this is simple: people who strive for performance before cleanliness and elegance almost always finish last. Their code becomes a slop of mush, because they've abandoned all that is good in order to really get nothing out of it. By writing good, readable code first, most of you performance problems will solve themselves. And if later you find your performance is lacking, it's now easy to add a profiler to your nice, clean code, and find out where the problem is. That all said, std::queue is only an adapter. It provides the safe interface, but uses a different container on the inside. You can choose this underlying container, and this allows a good deal of flexibility. So, which underlying container should you use? We know that std::list and std::deque both provide the necessary functions (push_back(), pop_front(), and front()), so how do we decide? First, understand that allocating (and deallocating) memory is not a quick thing to do, generally, because it involves going out to the OS and asking it to do something. A list has to allocate memory every single time something is added, and deallocate it when it goes away. A deque, on the other hand, allocates in chunks. It will allocate less often than a list. Think of it as a list, but each memory chunk can hold multiple nodes. (Of course, I'd suggest that you really learn how it works.) So, with that alone a deque should perform better, because it doesn't deal with memory as often. Mixed with the fact you're handling data of constant size, it probably won't have to allocate after the first pass through the data, whereas a list will be constantly allocating and deallocating. A second thing to understand is cache performance. Going out to RAM is slow, so when the CPU really needs to, it makes the best out of this time by taking a chunk of memory back with it, into cache. Because a deque allocates in memory chunks, it's likely that accessing an element in this container will cause the CPU to bring back the rest of the container as well. Now any further accesses to the deque will be speedy, because the data is in cache. This is unlike a list, where the data is allocated one at a time. This means that data could be spread out all over the place in memory, and cache performance will be bad. So, considering that, a deque should be a better choice. This is why it is the default container when using a queue. That all said, this is still only a (very) educated guess: you'll have to profile this code, using a deque in one test and list in the other to really know for certain. But remember: get the code working with a clean interface, then worry about performance. John raises the concern that wrapping a list or deque will cause a performance decrease. Once again, he nor I can say for certain without profiling it ourselves, but chances are that the compiler will inline the calls that the queue makes. That is, when you say queue.push(), it will really just say queue.container.push_back(), skipping the function call completely. Once again, this is only an educated guess, but using a queue will not degrade performance, when compared to using the underlying container raw. Like I've said before, use the queue, because it's clean, easy to use, and safe, and if it really becomes a problem profile and test.
1,262,859
1,262,883
Intercepting mouse clicks when the mouse is hovering above a control
I'm working on a MFC C++ dialog where I need to respond to right mouse click events for a dialog even if the mouse is hovering over a control. I could write event handler code for each control to delegate the work to the parent dialog, but I'm hoping there is a more elegant solution? I'm hoping there is some way to intercept the windows messages, but I'm still figuring that part out. I've tried listening to the WM_COMMAND messages with Spy++ but I didn't see what I needed. Any suggestions?
You could set up a hook to intercept mouse messages. Take a look at SetWindowsHookEx and WH_MOUSE
1,263,292
1,263,324
multidimensional array in C++ hang
I wanna to declare an array: int a[256][256][256] And the program hang. (I already comment out all other codes...) When I try int a[256][256], it runs okay. I am using MingW C++ compiler, Eclipse CDT. My code is: int main(){ int a[256][256][256]; return 0; } Any comment is welcomed.
This might happen if your array is local to a function. In that case, you'd need a stack size sufficient to hold 2^24 ints (2^26 bytes, or 64 MB). If you make the array a global, it should work. I'm not sure how to modify the stack size in Windows; in Linux you'd use "ulimit -s 10000" (units are KB). If you have a good reason not to use a global (concurrency or recursion), you can use malloc/free. The important thing is to either increase your stack (not a good idea if you're using threads), or get the data on the heap (malloc/free) or the static data segment (global). Ideally you'd get program termination (core dump) and not a hang. I do in cygwin.
1,263,447
1,263,463
Copying C-Style String to Free Store Using Only Dereference
As said in the title, the goal is to copy a C-style string into memory without using any standard library functions or subscripting. Here is what I have so far [SOLVED] #include "std_lib_facilities.h" char* strdup(const char* p) { int count = 0; while (p[count]) ++count; char* q = new char[count+1]; for (int i = 0; i < count + 1; ++i) *(q + i) = *(p + i); } int main() { char word[] = "Happy"; char* heap_str = strdup(word); } Obviously the problem is that allocating just *p (which is equivalent to p[0]) only allocates the letter "H" to memory. I'm not sure how to go about allocating the C-style string without subscripting or STL functions.
C-style string ends with '\0'. You need to traverse the string inside the function character by character until you encounter '\0' to know how long it is. (This is effectively what you would do by calling strlen() to work it out.) Once you know how long the string is, you can allocate the right amount of memory, which is the length+1 (because of the '\0'). To access the i'th element of an array p, one use subscript: p[i]. Subscript of the form p[i] is formally defined to be *((p)+(i)) by both the C standard (6.5.2.1 of C99) and the C++ standard (5.2.1 of C99). Here, one of p or i is of the type pointer to T, and the other is of integral type (or enumeration in C++). Because array name is converted automatically (in most types of use anyway) to a pointer to the first element of said array, p[i] is thus the i'th element of array p. And just like basic arithmetic, ((p)+(i)) is equivalent to ((i)+(p)) in pointer arithmetic. This mean *((p)+(i)) is equivalent to *((i)+(p)). Which also mean p[i] is equivalent to i[p].
1,263,521
1,263,529
What is #pragma used for?
Can anyone help me understand #pragma? ifndef TARGET_OS_LINUX #pragma once endif What,when, where, why, an example? The above is in some code that I am refactoring....
#pragma is just the prefix for a compiler-specific feature. In this case, #pragma once means that this header file will only ever be included once in a specific destination file. It removes the need for include guards.
1,263,599
1,263,627
GDI+ leaks memory when deleting pointers as GdiplusBase*?
I'm trying to work with GDI+ and I'm running into a weird memory leak. I have a vector of GdiplusBase pointers, all of them dynamically created. The odd thing is, though, is that if I try to delete the objects as GdiplusBase pointers, e.g., vector<GdiplusBase*> gdiplus; gdiplus.push_back(new Image(L"filename.jpg")); delete gdiplus[0]; The object is not deleted and memory leaks (according to Task Manager). However, if I cast back to the original pointer and then delete, delete (Image*)gdiplus[0]; The object is correctly deleted. The strange this about this, as far as I can tell, is that (according to MSDN) GdiplusBase is the base class of all GDI+ objects and owns the delete operators for all of them. In that case, shouldn't delete gdiplus[0]; work correctly and free the memory? Am I doing anything wrong here?
I would imagine the problem is that GdiplusBase does not have a virtual destructor, and thus when you call delete like that, no destructor is called. And the destructor of Image is likely releasing some other resources (such as bitmap handles etc). So the memory for the Image object itself is freed correctly, but other resources it is using (which may also use up memory) aren't freed.
1,263,607
1,263,619
C, C++ preprocessor macro
Can anyone please explain how this works #define maxMacro(a,b) ( (a) > (b) ) ? (a) : (b) inline int maxInline(int a, int b) { return a > b ? a : b; } int main() { int i = 1; j = 2, k = 0; k = maxMacro(i,j++); // now i = 1, j = 4 and k = 3, Why ?? Where is it incremented ? //reset values i = 1; j = 2, k = 0; k = maxInline(i,j++); // now i = 1, j = 3, and k = 2, Why ?? return 0; } So, I want to know where exactly is the value of j incremented, while checking condition or while returning or while calling ? a. using macro b. using inline method UPDATE : Thanks to all, now I understand this. But just out of curiosity, why would anyone do j++ while calling method, why not increment j after calling method, this way it would be less confusing. I saw this piece of code somewhere so asking it !!
The issue is the preprocessor does just straight text substitution for macros. maxMacro(i, j++) becomes ( (i) > (j++) ) ? (i) : (j++) As you can see, it does two increments when j is greater. This is exactly why you should prefer inline functions over macros.
1,263,825
1,264,004
Is this valid C++ code?
I had the following code, which was basically, class foo { public: void method(); }; void foo::foo::method() { } I had accidentally added an extra foo:: in front of the definition of foo::method. This code compiled without warning using g++(ver 4.2.3), but errored out using Visual Studio 2005. I didn't have a namespace named foo. Which compiler is correct?
If I read the standard correctly, g++ is right and VS is wrong. ISO-IEC 14882-2003(E), §9.2 Classes (pag.153): A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name. For purposes of access checking, the injected-class-name is treated as if it were a public member name. Following on the comments below, it's also particularly useful to retain the following concerning the actual Name Lookup rules: ISO-IEC 14882-2003(E), §3.4-3 Name Lookup (pag.29): The injected-class-name of a class (clause 9) is also considered to be a member of that class for the purposes of name hiding and lookup. It would be odd if it wasn't, given the final part of text at 9.2. But as litb commented this reassures us that indeed g++ is making a correct interpretation of the standard. No questions are left.
1,263,899
1,263,910
Where do you track the developments of new c++ standards?
Where do you guys generally look for developments in C++, most importantly, developments in new standard and its approx/scheduled release data? also boost (well, boost.com) Is there a centralized place? thx
C++ has been updated much here lately. I would recommend wikipedia's article on C++ though. It usually is kept up to date (not that a lot's changed). I guess the closest thing to a specification that I've found is Bjarne Stroustrup's book (the creator of the C++ language) on, what else, the C++ language.
1,264,052
1,264,055
How to determine whether it is EOF when using getline() in c++?
string s; getline(cin,s); while (HOW TO WRITE IT HERE?) { inputs.push_back(s); getline(cin,s); }
Since I'm too lazy to give a full answer today, I'll just paste what the really useful bot in ##c++ on Freenode has to say: Using "while (!stream.eof()) {}" is almost certainly wrong. Use the stream's state as the tested value instead: while (std::getline(stream, str)) {}. For further explanation see http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5 In other words, your code should be string s; while (getline(cin, s)) { inputs.push_back(s); }
1,264,059
1,264,344
In C++, what is the difference between 1 and 1i64?
I'm converting some 32-bit compatible code into 64-bit - and I've hit a snag. I'm compiling a VS2008 x64 project, and I receive this warning: warning C4334: '<<' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) Here's the original line of code: if ((j & (1 << k)) != 0) { And here's what it looks like if I follow Microsoft's advice: if ((j & (1i64 << k)) != 0) { Is this safe to do, when the code will be compiled on both 32-bit and 64-bit systems? If so, please explain why I must add "i64" to the end, and why this will not affect a 32-bit compilation. Otherwise, a work-around would be much appreciated. Beyond this, I have what looks like an even trickier bit of code. if (id[j] != id[j ^ (1u << k)]) { I understand that the "u" means that the digit is unsigned, but what's the point in specifying that on a value that doesn't exceed the signed maximum value... I'm guessing this has something to do with the bit shift?
1 has type int according to C++ Standard. On 64-bit Microsoft compiler int has sizeof = 4 bytes, it means that int is 32-bit variable. 1i64 has type __int64. When you use shift operator the type of the result is the same as the type of the left operand. It means that shifting 1 you'll get 32-bit result. Microsoft compiler assumes that it could be not what you are expecting (on 64-bit platform) and gives you warning message. When you use 1i64 result will be 64-bit on both platforms. j and 0 will be implicitly casted to 64-bit. So the whole expression will be calculated in 64-bit variables and result will be bool. So using 1i64 is safe on both (32/64) platforms.
1,264,405
1,264,416
error: non-lvalue in unary `&' in C++
We are using a macro wrapper to Bind Where Parameter function. #define bindWhereClause(fieldName, fieldDataType, fieldData) _bindWhereClause(fieldName, fieldDataType, sizeof(fieldData), &fieldData) void _bindWhereClause(const char *name, int dataType, int dataSize, void *data) { // Implementation } Database.bindWhereClause( "FIRST_NAME", SQL_VARCHAR, name.getFirstName()); When I tried to call the macro with a function as parameter (as above) I am getting the error message "error: non-lvalue in unary `&'". I am able to call the macro with normal variables like Database.bindWhereClause( "FIRST_NAME", SQL_VARCHAR, firstName); How to resolve this? Do I need to use inline functions instead of macro? Appreciate your help in advance. Thanks, Mathew Liju
You can't take the address of the return value of a function - it is ephemeral. You need to use a real variable: Nametype first_name = name.getFirstName(); Database.bindWhereClause( "FIRST_NAME", SQL_VARCHAR, first_name); // ... and maybe name.setFirstName(first_name); here Using an inline function would make it compile but it is unlikely to actually work. Presumably this is followed by something like: Database.execute(); ...which expects the objects whose addresses you passed earlier to still be valid. If you use an inline function instead of a macro, those objects will no longer exist, since they were just local to the inline function which has already exited.
1,264,596
1,264,744
Decode WMA with FFMpeg to PCM
I want to decode a WMA stream to 16 Bit PCM. Now i have a Question concerning FFMpeg- what is the output format of .. len = avcodec_decode_audio2(c, (int16_t *)outbuf, &outbuf_used, inbuf_ptr, size); is this the right function for this task? Thank you
A remark : try to ask this question on ffmpeg user list. You will certainly find ffmpeg gurus there. I mainly use ffmpeg to encode/decode video. To decode, the "avcodec_decode_*" are the right things to use for ... decoding. What you get is ... 16 bits PCM. What I mean is that decoding a multimedia stream can be tricky and ffmpeg is quite a low level lib. It is hard to be more precise with just the line of code you give (at least you should be more precise about your parameters). What you should be careful about is that when reading multimedia stream, you have to demux you stream first (sometimes even if there is only one stream in your container) and then to decode it with the right codec. If you have correctly demuxed your stream, correctly initialized your codec / codec context then you can call avcodec_decode and it will works :) As you mention c++ in your tags, you can try a c++ wrapping for ffmpeg : FOBS The use is much more simple but of course, you lose precise control ... I hope it helps.
1,264,723
1,265,960
How to add menu command handler in VC 2008?
how to add a menu command handler in vc 2008?
Is this a trick question? alt text http://img197.imageshack.us/img197/5603/93284930.png
1,265,099
1,265,678
How to find if an document can be OPENed via ShellExecute?
I want to check if a particular file can be successfully "OPEN"ed via ShellExecute, so I'm attempting to use AssocQueryString to discover this. Example: DWORD size = 1024; TCHAR buff[1024]; // fixed size as dirty hack for testing int err = AssocQueryString(0, ASSOCSTR_EXECUTABLE, ".mxf", NULL ,buff , &size); openAction->Enabled = ((err == S_OK) || (err == S_FALSE)) && (size > 0); Now, this almost works. If there's a registered application, I get the string. But, there's a catch: On Vista, even if there is no registered application, It returns that the app c:\Windows\System32\shell32.dll is associated, which is the thing that brings up the 100% useless "Windows cannot open this file: Use the Web service to find the correct program?" dialog. Obviously I want to hide that peice of cr*p from end users, but simply comparing the returned string to a constant seems like an ugly, brute-force and fragile way of doing it. Also, hacking the registry to totally disable this dialog isn't a great idea. What's a better option?
I always use FindExecutable() to get the registered application for a given document.
1,265,338
1,436,355
How to retrieve cookies for a specific site and path in winhttp
I would like to retrieve the cookies stored in the winhttp session cache based upon a specific host and path that I am about to send a request to. I want to retrieve those cookies before I send the request, so I don't have the request handle yet, all I have is the session and connection handles and of course the path and host I'm going to send the request to. In other words I would like to retrieve the cookies that winhttp will send to the server before I actually send the request. Reason I'm asking is because our server checks a specific header, which I have to set, to match an md5 check based upon, amongst other, the cookies. I don't have control over the server code or anything. Cheers,
Use the WINHTTP_CALLBACK_STATUS_SENDING_REQUEST notification as a chance to inspect the cookie headers winhttp put by default on the request and then add the md5 header before returning from the callback.
1,265,354
1,265,424
How to design a state machine in face of non-blocking I/O?
I'm using Qt framework which has by default non-blocking I/O to develop an application navigating through several web pages (online stores) and carrying out different actions on these pages. I'm "mapping" specific web page to a state machine which I use to navigate through this page. This state machine has these transitions; Connect, LogIn, Query, LogOut, Disconnect and these states; Start, Connecting, Connected, LoggingIn, LoggedIn, Querying, QueryDone, LoggingOut, LoggedOut, Disconnecting, Disconnected Transitions from *ing to *ed states (Connecting->Connected), are due to LoadFinished asynchronous network events received from network object when currently requested url is loaded. Transitions from *ed to *ing states (Connected->LoggingIn) are due to events send by me. I want to be able to send several events (commands) to this machine (like Connect, LogIn, Query("productA"), Query("productB"), LogOut, LogIn, Query("productC"), LogOut, Disconnect) at once and have it process them. I don't want to block waiting for the machine to finish processing all events I sent to it. The problem is they have to be interleaved with the above mentioned network events informing machine about the url being downloaded. Without interleaving machine can't advance its state (and process my events) because advancing from *ing to *ed occurs only after receiving network type of event. How can I achieve my design goal? EDIT The state machine I'm using has its own event loop and events are not queued in it so could be missed by machine if they come when the machine is busy. Network I/O events are not posted directly to neither the state machine nor the event queue I'm using. They are posted to my code (handler) and I have to handle them. I can forward them as I wish but please have in mind remark no. 1. Take a look at my answer to this question where I described my current design in details. The question is if and how can I improve this design by making it More robust Simpler
Sounds like you want the state machine to have an event queue. Queue up the events, start processing the first one, and when that completes pull the next event off the queue and start on that. So instead of the state machine being driven by the client code directly, it's driven by the queue. This means that any logic which involves using the result of one transition in the next one has to be in the machine. For example, if the "login complete" page tells you where to go next. If that's not possible, then the event could perhaps include a callback which the machine can call, to return whatever it needs to know.
1,265,574
1,266,739
#define _AFX_NO_DEBUG_CRT causes a stream of compilation errors
I have an MFC C++ project compiler under Visual Studio 2008. I'm adding a _AFX_NO_DEBUG_CRT in my stdafx.h before the #include to avoid all the debug new and deletes that MFC provides (I wish to provide my own for better cross platform compatibility). However when I do this I get a stream of errors such as the following: >c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : '__asm' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ')' before '{' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ')' before '{' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ')' before '{' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before '{' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : warning C4091: '' : ignored on left of 'int' when no variable is declared 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before 'constant' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before '}' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before ',' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : ')' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : ')' 1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : ')' 1 I "think" it may have something to do with an __asm int 3 call but I cannot be sure. Has anyone had this problem before? If so, how did you fix it? Am i stuck with MFC's memory tracking? I really hope not because it will make my libraries a lot less cross platform :( Any help would be hugely appreciated!
I've come up with one method which involves using the /FORCE:MULTIPLE command line to force it to use mine instead of the MFC one. It all seems to be working quite nicely. I can, now, even track "mallocs" and "new"s performed by functions not owned by me :) If anyone has any better solutions then please post them but for now this seems to solve my problem :)
1,265,650
1,265,817
What is a callback? What is it for and how is it implemented in for example C++
I realise this is a newbie question, but as I'm trying to learn C++ I'm stumpling upon this expression "callback" frequently. I've googled it and checked wikipedia, but without finding a good explination. I am familiar with some Java and C#, but how unlikely it sounds, I have never really understood what a callback means. If someone know how to explain this term to a simple layman, I would be really thankfull.
I am familiar with some Java and C# A callback is an event or delegate in those languages - a way to get your code run by somebody else's code in it's context. Hence, the term "callback": You call some other piece of code It runs, perhaps calculating an intermediate value It calls back into your code, perhaps giving you that intermediate value It continues running, eventually passing control back to you by completing A canonical example is a sort routine with a user defined comparison function (the callback). Given a sort routine such as: void Sort(void* values, int length, int valueSize, int (*compare)(const void*, const void*) { for (int i = 0; i < length; i = i + 2) { // call the callback to determine order int isHigher = compare(values[i], values[i + 1]); /* Sort */ } } (The specifics of how the sort is performed isn't important - just focus on the fact that any sorting algorithm needs to compare 2 values and determine which is higher.) So, now we can define some comparison functions: int CompareInts(const void* o, const void* p) { int* a = (int*) o; int* b = (int*) p; if (a == b) return 0; return (a < b) ? -1 : 1; } int ComparePersons(const void* o, const void* p) { Person* a = (Person*) o; Person* b = (Person*) p; if (a == b) return 0; return (a->Value() < b=>Value()) ? -1 : 1; } And reuse the same sort function with them: int intValues[10]; Person personValues[10]; Sort(intValues, 10, sizeof(intVaues[0]), CompareInts); Sort(personValues, 10, sizeof(personVaues[0]), ComparePersons); Things get a bit more complicated if you're using member functions, as you have to manage the this pointer - but the concept is the same. As with most things, it's easier to explain them in C first. ;)
1,265,666
1,265,681
Reason why not to have a DELETE macro for C++
Are there any good reasons (except "macros are evil", maybe) NOT to use the following macros ? #define DELETE( ptr ) \ if (ptr != NULL) \ { \ delete ptr; \ ptr = NULL; \ } #define DELETE_TABLE( ptr ) \ if (ptr != NULL) \ { \ delete[] ptr; \ ptr = NULL; \ }
Personally I prefer the following template< class T > void SafeDelete( T*& pVal ) { delete pVal; pVal = NULL; } template< class T > void SafeDeleteArray( T*& pVal ) { delete[] pVal; pVal = NULL; } They compile down to EXACTLY the same code in the end. There may be some odd way you can break the #define system but, personally (And this is probably going to get me groaned ;) I don't think its much of a problem.
1,265,702
1,265,730
Comparing two vectors of maps
I've got two ways of fetching a bunch of data. The data is stored in a sorted vector<map<string, int> >. I want to identify whether there are inconsistencies between the two vectors. What I'm currently doing (pseudo-code): for i in 0... min(length(vector1), length(vector2)): for (k, v) in vector1[i]: if v != vector2[i][k]: // report that k is bad for index i, // with vector1 having v, vector2 having vector2[i][k] for i in 0... min(length(vector1), length(vector2)): for (k, v) in vector2[i]: if v != vector1[i][k]: // report that k is bad for index i, // with vector2 having v, vector1 having vector1[i][k] This works in general, but breaks horribly if vector1 has a, b, c, d and vector2 has a, b, b1, c, d (it reports brokenness for b1, c, and d). I'm after an algorithm that tells me that there's an extra entry in vector2 compared to vector1. I think I want to do something where when I encountered mismatches entries, I look at the next entries in the second vector, and if a match is found before the end of the second vector, store the index i of the entry found in the second vector, and move to matching the next entry in the first vector, beginning with vector2[i+1]. Is there a neater way of doing this? Some standard algorithm that I've not come across? I'm working in C++, so C++ solutions are welcome, but solutions in any language or pseudo-code would also be great. Example Given the arbitrary map objects: a, b, c, d, e, f and g; With vector1: a, b, d, e, f and vector2: a, c, e, f I want an algorithm that tells me either: Extra b at index 1 of vector1, and vector2's c != vector1's d. or (I'd view this as an effectively equivalent outcome) vector1's b != vector2's c and extra d at index 2 of vector1 Edit I ended up using std::set_difference, and then doing some matching on the diffs from both sets to work out which entries were similar but different, and which had entries completely absent from the other vector.
Something like the std::mismatch algorithm You could also use std::set_difference
1,265,864
1,265,952
What could be a reason to not use bracket classes in C++?
It's often needed to accomplish the following task: change the state of something, do action, then change the state back to original. For example, in Win32 GDI it's needed to change background color, then do some drawing, then change the color back. It can be either done directly: COLORREF oldColor = SetBkColor( deviceContext, newColor ); drawStuff( deviceContext ); SetBkColor( deviceContext, oldColor ); or via a bracket class that would do the forward change in the constructor and the backward change in the destructor: CBkColorSwitcher switcher( deviceContext, newColor ); drawStuff( deviceContext ); //once control reaches end of block the switcher is destroyed and the change is reverted The advantage of a bracket class is obvious - if an exception is thrown in between the changes the change is reverted correctly. What are the disadvantages?
I'm nitpicking here, but: Code size, your code will be bigger because of the exception handler. You need to write a lot of class to handle all sort of switches. Bigger stack. Always preforming code on all exceptions, even if its not need (for example you just want the application to crash)
1,265,951
1,265,972
What are preprocessor macros good for?
After reading another question about the use of macros, I wondered: What are they good for? One thing I don't see replaced by any other language construct very soon is in diminishing the number of related words you need to type in the following: void log_type( const bool value ) { std::cout << "bool: " << value; } void log_type( const int value ) { std::cout << "int: " << value; } ... void log_type( const char value ) { std::cout << "char: " << value; } void log_type( const double value ) { std::cout << "int: " << value; } void log_type( const float value ) { std::cout << "float: " << value; } as opposed to #define LOGFN( T ) void log_type( const T value ) { std::cout << #T ## ": " << value; } LOGFN( int ) LOGFN( bool ) ... LOGFN( char ) LOGFN( double ) LOGFN( float ) Any other 'irreplaceables'? EDIT: trying to summarize the reasons-why encountered in the answers; since that's what I was interested in. Mainly because I have a feeling that most of them are due to us still programming in raw text files in, still, poorly supporting environments. flexibility of code-to-be compiled (e.g. #ifdef DEBUG, platform issues) (SadSido, Catalin, Goz) debug purposes (e.g. __LINE__, __TIME__); I also put 'stringifying' under this reason (SadSido, Jla3ep, Jason S) replacing e.g. PHP's require vs. include feature (#pragma once) (SadSido, Catalin) readability enhancement by replacing complicated code (e.g. MESSAGEMAP, BOOST_FOREACH) (SadSido, fnieto) DRY principle (Jason S) an inline replacement (Matthias Wandel, Robert S. Barnes) stringifying (Jason S)
compile different code under different conditions ( #ifdef __DEBUG__ ); guards to include each header once for each translation unit ( #pragma once ); __FILE__ and __LINE__ - replaced by the current file name and current line; structuring the code to make it more readable (ex: BEGIN_MESSAGE_MAP() ); See interesting macro discussion at gotw here: http://www.gotw.ca/gotw/032.htm http://www.gotw.ca/gotw/077.htm
1,266,233
1,266,308
What is activation record in the context of C and C++?
What does it mean and how important to know about it for a C/C++ programmers? Is it the same across the platforms, at least conceptually? I understand it as a block of allocated memory used to store local variable by a function... I want to know more
An activation record is another name for Stack Frame. It's the data structure that composes a call stack. It is generally composed of: Locals to the callee Return address to the caller Parameters of the callee The previous stack pointer (SP) value The Call Stack is thus composed of any number of activation records that get added to the stack as new subroutines are added, and removed from the stack (usually) as they return. The actual structure and order of elements is platform and even implementation defined. For C/C++ programmers, general knowledge of this structure is useful to understand certain implementation features like Calling Conventions and even why do buffer overflows allow 3rd party malicious code to be ran. A more intimate knowledge will further the concepts above and also allow a programmer to debug their application and read memory dumps even in the absence of a debugger or debugging symbols. More generally though, a C/C++ programmer can go by a large portion of their hobbyist programming career without even giving the call stack a moments thought.
1,266,277
1,266,335
How to implement a stacktrace in C++ (from throwing to catch site)?
Is the trickery way that we can show the entire stack trace (function+line) for an exception, much like in Java and C#, in C++? Can we do something with macros to accomplish that for windows and linux-like platforms? thanks
On Windows it can be done using the Windows DbgHelp API, but to get it exactly right requires lots of experimenting and twiddling. See http://msdn.microsoft.com/en-us/library/ms679267(VS.85).aspx for a start. I have no idea how to implement it for other platforms. Hope this helps a bit. Regards, Sebastiaan
1,266,534
1,663,424
C++ plus VS plus WORKFLOW?
I have seen there is Workflow Foundation for .NET. Is there some kind of a tool for creating work flow with C++ on VS? Or there maybe there are similar tools which helps to architect application business processes? Thanks in advance ! :)
Creating workflows can be done in the Visual Studio Designer. For architecting applications you should look at Visual Studio Architect Edition http://ajdotnet.wordpress.com/2009/03/29/visual-studio-2010-architecture-edition/ You can download the Beta 2 version from here: http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
1,266,570
1,266,621
Python non-trivial C++ Extension
I have fairly large C++ library with several sub-libraries that support it, and I need to turn the whole thing into a python extension. I'm using distutils because it needs to be cross-platform, but if there's a better tool I'm open to suggestions. Is there a way to make distutils first compile the sub-libraries, and link them in when it creates an extension from the main library?
I do just this with a massive C++ library in our product. There are several tools out there that can help you automate the task of writing bindings: the most popular is SWIG, which has been around a while, is used in lots of projects, and generally works very well. The biggest thing against SWIG (in my opinion) is that the C++ codebase of SWIG itself is really rather crufty to put it mildly. It was written before the STL and has it's own semi-dynamic type system which is just old and creaky now. This won't matter much unless you ever have to get stuck in and make some modifications to the core (I once tried to add doxygen -> docstring conversion) but if you ever do, good luck to you! People also say that SWIG generated code is not that efficient, which may be true but for me I've never found the SWIG calls themselves to be enough of a bottleneck to worry about it. There are other tools you can use if SWIG doesn't float your boat: boost.python is also popular and could be a good option if you already use boost libraries in your C++ code. The downside is that it is heavy on compile times since it is pretty much all c++ template based. Both these tools require you to do some work up-front in order to define what will be exposed and quite how it will be done. For SWIG you provide interface files which are like C++ headers but stripped down, and with some extra directives to tell SWIG how to translate complex types etc. Writing these interfaces can be tedious, so you may want to look at something like pygccxml to help you auto-generate them for you. The author of that package actually wrote another extension which you might like: py++. This package does two things: it can autogenerate binding definitions that can then be fed to boost.python to generate python bindings: basically it is the full solution for most people. You might want to start there if you no particulrly special or difficult requirements to meet. Some other questions that might prove useful as a reference: Extending python - to swig or not to swig SWIG vs CTypes Extending Python with C/C++ You may also find this comparison of binding generation tools for Python handy. As Alex points out in the comments though, its rather old now but at least gives you some idea of the landscape... In terms of how to drive the build, you may want to look at a more advanced built tool that distutils: if you want to stick with Python I would highly recommend Waf as a framework (others will tell you SCons is the way to go, but believe me it's slow as hell: I've been there and back already!)...it takes a little learning, but when you get your head around it is extremely powerful. And since it's pure Python it will integrate perfectly with any other Python code you have as part of your build process (say for example you use Py++ in the end)...
1,266,861
1,267,439
C++0x noise, bloat and portability
At first when I saw the upcoming C++0x standard I was delighted, and not that I'm pessimistic, but when thinking of it now I feel somewhat less hopeful. Mainly because of three reasons: a lot of boost bloat (which must cause hopeless compile times?), the syntax seems lengthy (not as Pythonic as I initially might have hoped), and I'm very interested in portability and other platforms (iPhone, Xbox, Wii, Mac), isn't there are very real risk that the "standard" will take long to get portable enough? I suppose #3 is less of a risk, lessons learned from templates in the previous decade; however Devil's in the details. Edit 2 (trying to be less whimsy): Would you say it's safe for a company to transition to C++0x in the first effective year of the standard, or will that be associated with great risk?
Edit: do I (and others like me) have to keep a very close eye on build times, unreadable code and lack of portability and do massive prototyping to ensure that it's safe to move on with the new standard? Yes. But you have to do all these things with the current standard as well. I don't see that it is getting any worse with C++0x. C++ build times have always sucked. There's no reason why C++0x should be slower than it is today, though. As always, you only include the headers you need. And each header has not grown noticeably bigger, as far as I can tell. Of course Concepts was one of the big unknowns here, and it was feared that they would slow down compile-times dramatically. Which was one of the many reasons why they were cut. C++ easily becomes unreadable if you're not careful. Again, nothing new there. And again, C++0x offers a lot of tools to help minimize this problem. Lambdas aren't quite as concise as in, say, Python or SML, but they're a hell of a lot more readable than the functors we're having to define today. As for portability, C++ is a minefield already. There are no guarantees given for integer type sizes, nor for string encodings. In both cases, C++0x offers the tools to fix this (with Unicode-specific char types, and integers of a guaranteed fixed size) The upcoming standard nails down a number of issues that currently hinder portability. So overall, yes, the issues you mention are real. They exist today, and they will exist in C++0x. But as far as I can see, C++0x lessens the impact of these problems. It won't make them worse. You're right, it'll take a while for compliant standards to become available on all platforms. But I think it'll be a quicker process than it was with C++98. All the major compiler vendors seem very keen on C++0x support, which wasn't really the case last time around. (probably because back then, it was mostly a matter of adjusting and fixing the pre-standard features they already implemented, so it was easier to claim that your pre-standard compiler was "sort of almost nearly C++98-compliant". I think on the whole, the C++ community is much more standard-focused and forward-looking than a decade ago. If you want to sell your compiler, you're going to have to take C++0x seriously. But there's definitely going to be a period of several years from the standard is released until fully (or mostly) compliant compilers are available.
1,267,019
1,267,220
Is there a way to use macros to add additional values to an enum from elsewhere at compile time?
We use one big enum for message passing and there are optional parts of our code base that use specific messages that really only need to be added to the enum if those parts are to be compiled in. Is there a way to define a macro that could do this or something similar? I would like to be able to just add REGISTER_MSG(MESSAGE_NAME); to the beginning of a file in the optional code. I guess the real problem is that macros only replace the code at the location they are written.
I would rethink this design, but if you really want to do it this way you can construct the enum header at compile time using Make. BigEnum.h: # First put in everything up to the opening brace, cat BigEnumTop > $@ # then extract all of the message names and add them (with comma) to BigEnum.h, cat $(OPTIONAL_SOURCES) | grep REGISTER_MSG | sed 's/.*(\(.*\))/\1/' >> $@ # then put in the non-optional message names, closing brace, and so on. cat BigEnumBottom >> $@
1,267,067
1,268,043
C++ style menu bar in VB.NET?
Ive been looking a long time for this, but can't seem to find it. When I add a menu strip in vb .net, it looks like this: http://img19.imageshack.us/img19/4341/menu1sbo.jpg http://img19.imageshack.us/img19/4341/menu1sbo.jpg and I want it to look like the WinRar, Calculator, Notepad etc menus like this: http://img8.imageshack.us/img8/307/menu1a.jpg http://img8.imageshack.us/img8/307/menu1a.jpg From what I gathered, in vb 6 you could create a mainmenu and do it this way, but in vb .net it seems like all there is is ugly menustrip. Thanks
You may have to get dirty and create a CustomRenderer(ToolStripProfessionalRenderer) to apply to the ToolStripManager Without rehashing to much, this doc looks like a nice overview or you can always opt for the Microsoft tutorial menustrip is derived from toolstrip
1,267,173
1,268,011
How do I find resource leaks in Win32?
After running some hours my application fails in creating a new font object: CreateFontIndirect() returns NULL. I know how to find memory leaks (i.e. using parallel inspector or another profiler - most of them include leak detection). But how can I locate a resource leak in Win32?
Grab yourself a copy of GDI View - this useful tool can show all the GDI objects used by your app, including details on the font name, size, etc. This has proved very handy in the past. For Win32 apps you might want to look at the WTL framework - this wraps GDI objects with lightweight C++ classes that will handle object deletion for you.
1,267,354
1,273,320
GTK Window configure events not propagating
I'm attempting to capture an event on a GTK window when the window is moved. I'm doing so with something that looks like this: void mycallback(GtkWindow* parentWindow, GdkEvent* event, gpointer data) { // do something... } ... GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_add_events(GTK_WIDGET(window), GDK_CONFIGURE); g_signal_connect_(G_OBJECT(window), "configure-event", G_CALLBACK(mycallback), NULL); ... This works- the event is properly called when the window is moved... but it's also called when the window is resized. This has the side effect of not resizing the window's sub-elements as they would if I didn't connect the event. According to this table in the GTK docs, the GDK_CONFIGURE event does not propagate. If the event does not propagate, how can I still detect the window's movement while allowing it to resize properly? note: I'm using GTK version 2.12.9
Luke, as you have discovered, returning FALSE allows the event to propagate. This is explained in the gtk tutorial here
1,267,541
1,276,394
Adding C++ custom action in Visual studio installer
due to some constraints i want to write a custom action in c++ and add its assembly in Visual Studio installer... is it possible? as i know about c# or vb in those one can create classes inherited from Installer and it worked but now i want the same with C++....
figured out that the assembly should contain a function named Install() in c++... it serves as an installer entry point.. added as Install custom action MSI installer executes that function .
1,267,697
1,267,723
finding why a DLL is being loaded
I have a winxp process which has all sorts of dlls and static libs. One of our libs is calling ms debug dlls, I have a suspicion which one it is but want to prove it in a tool like Process Explorer. How can I get a tree of my process, to see exactly who is loading what modules?
You can use tools like Dependency Walker
1,267,811
1,267,880
__declspec(dllimport/dllexport) and inheritance
Given a DLL with the following classes : #define DLLAPI __declspec(...) class DLLAPI Base { public: virtual void B(); }; class Derived : public Base { public: virtual void B(); virtual void D(); }; Will my "Derived" class be visible outside of the dll even if the "DLLAPI" keyword is not applied to the class definition (at least, not directly)? Is the "D()" function visible to? Thanks
class Derived won't be exported by your DLL. Classes don't inherit exporting. Add DLLAPI to that too. Note too that class members default to private accessibility, so none of your methods should be accessible. However, I do see Base::B() being exported in my test. The C++ header in the DLL-using code would flag the error, but I wonder if you tweaked the header there, if you could fool it. Anyway, if you did instantiate a Derived inside your DLL (via another entry point), the virtual table should still work, so if you did: Base* b = getTheDerived(); b->B(); you'd invoke Derived::B().
1,267,915
1,268,132
Cast from size_t to int, or iterate with size_t?
Is it better to cast the iterator condition right operand from size_t to int, or iterate potentially past the maximum value of int? Is the answer implementation specific? int a; for (size_t i = 0; i < vect.size(); i++) { if (some_func((int)i)) { a = (int)i; } } int a; for (int i = 0; i < (int)vect.size(); i++) { if (some_func(i)) { a = i; } }
I almost always use the first variation, because I find that about 80% of the time, I discover that some_func should probably also take a size_t. If in fact some_func takes a signed int, you need to be aware of what happens when vect gets bigger than INT_MAX. If the solution isn't obvious in your situation (it usually isn't), you can at least replace some_func((int)i) with some_func(numeric_cast<int>(i)) (see Boost.org for one implementation of numeric_cast). This has the virtue of throwing an exception when vect grows bigger than you've planned on, rather than silently wrapping around to negative values.
1,268,005
1,268,074
AfxGetAppName() returns garbage characters
I have the following line of code in my application: CString strAppName = AfxGetAppName(); Sometimes it fills strAppName up with garbage characters, and I can't figure out why. Anyone have any ideas? TIA.
That is possible if you change m_pszAppName manually. At the very beginning of application initialization, AfxWinInit calls CWinApp::SetCurrentHandles, which caches the current value of the m_pszAppName pointer as follows: pModuleState->m_lpszCurrentAppName = m_pszAppName; That is, the module state struct holds a copy of the m_pszAppName pointer. If you change m_pszAppName in InitInstance as adviced in MSDN, you still have the old pointer value in pModuleState->m_lpszCurrentAppName. The AfxGetAppName() function returns AfxGetModuleState()->m_lpszCurrentAppName. You could add data breakpoint on m_lpszCurrentAppName and on m_pszAppName. It is initialized in <...>\Microsoft Visual Studio 9.0\VC\atlmfc\src\mfc\appinit.cpp file. You'll see what is going on with that variable and who's trying to change it.
1,268,077
1,268,965
MinGW compile for MS DOS
I'm using Code::Blocks with MinGW to write my C++ applications in Windows XP. Now I want to compile my code to run under an MS DOS environment, so I can put it on my DOS formatted floppy disc. Can anyone help me? Thanks in advance. P.S. I don't mean the Command Prompt, but really the good old MS DOS Operating System.
It's pretty old, but DJGPP exists precisely for DOS development. I hasn't been updated since 2000, but it works. It's basically the same as MinGW, but exclusively for DOS.
1,268,101
1,268,189
Why does the library compiled on two slightly different machines behaves slightly different?
Here's the setup: My coworker has a Fedora x64_86 machine with a gcc 4.3.3 cross compiler (from buildroot). I have an Ubuntu 9.04 x64_86 machine with the same cross compiler. My coworker built an a library + test app that works on a test machine, I compiled the same library and testapp and it crashes on the same test machine. As far as I can tell, gcc built against buildroot-compiled ucLibc, so, same code, same compiler. What kinds of host machine differences would impact cross compiling? Any insight appreciated. Update: To clarify, the compilers are identical. The source code for the library and testapp is identical. The only difference is that the testapp + lib have been compiled on different machines..
If your code crashes (I assume you get a sigsegv), there seems to be a bug. It's most likely some kind of undefined behaviour, like using a dangling pointer or writing over a buffer boundary. The unfortunate point of undefined behaviour is, that it may work on some machines. I think you are experiencing such an event here. Try to find the bug and you'll know what happens :-)
1,268,216
1,268,230
How to pass a C# Reference to COM Object to a C++ DLL
I am writing a Visual Studio add-in to process C++ code, and think that COM interop is slowing me down to much. I therefore want to pass a C# reference to a COM object to a small C++ DLL, have the DLL perform the necessary calculations and return back a string. I would be passing a CodeFunction2 object to the DLL and getting an XML string with information on the method back. While you are welcome to question whether I really need this for the performance boost, if you call a dozen member variables accross a COM interop for thousands of methods it seems to eat up way too much time changing between managed and unmanaged code. How do I format the arguments to the C++ DLL? I have no experience with calling unmanaged code from managed code in general, but the main question I need answered is how to format the call.
Maybe you should write a Managed C++ dll instead (using the /clr switch), then you can directly pass managed objects into the C++ dll and do whatever COM magic you like without worrying about passing them between dlls.
1,268,504
1,268,905
Why is the template argument deduction not working here?
I created two simple functions which get template parameters and an empty struct defining a type: //S<T>::type results in T& template <class T> struct S { typedef typename T& type; }; //Example 1: get one parameter by reference and return it by value template <class A> A temp(typename S<A>::type a1) { return a1; } //Example 2: get two parameters by reference, perform the sum and return it template <class A, class B> B temp2(typename S<A>::type a1, B a2)//typename struct S<B>::type a2) { return a1 + a2; } The argument type is applied to the struct S to get the reference. I call them with some integer values but the compiler is unable to deduce the arguments: int main() { char c=6; int d=7; int res = temp(c); int res2 = temp2(d,7); } Error 1 error C2783: 'A temp(S::type)' : could not deduce template argument for 'A' Error 2 error C2783: 'B temp2(S::type,B)' : could not deduce template argument for 'A' Why is this happening? Is it that hard to see that the template arguments are char and int values?
Just as first note, typename name is used when you mention a dependent name. So you don't need it here. template <class T> struct S { typedef T& type; }; Regarding the template instantiation, the problem is that typename S<A>::type characterizes a nondeduced context for A. When a template parameter is used only in a nondeduced context (the case for A in your functions) it's not taken into consideration for template argument deduction. The details are at section 14.8.2.4 of the C++ Standard (2003). To make your call work, you need to explicitly specify the type: temp<char>(c);
1,268,541
1,268,556
BOOST_FOREACH: is there a trick to avoid the all-caps spelling?
BOOST_FOREACH is really neat, but the C macro style of writing is somewhat off-putting. Is there a trick to avoid the all-caps spelling?
Actually, a little more googling and reading revealed the answer right in the Boost foreach documentation: Making BOOST_FOREACH Prettier People have complained about the name BOOST_FOREACH. It's too long. ALL CAPS can get tiresome to look at. That may be true, but BOOST_FOREACH is merely following the Boost Naming Convention. That doesn't mean you're stuck with it, though. If you would like to use a different identifier (foreach, perhaps), you can simply do: #define foreach BOOST_FOREACH #define reverse_foreach BOOST_REVERSE_FOREACH Only do this if you are sure that the identifier you choose will not cause name conflicts in your code. and with that I just opted for // cf http://www.boost.org/doc/libs/1_39_0/doc/html/foreach.html // -- Making BOOST_FOREACH Prettier #define boostForeach BOOST_FOREACH
1,268,604
1,268,978
vs 2008 623 compiler errors
I have a c++ console app that has been doing just fine and upon clean make started throwing compiler errors. Obviously I've redefined or omitted something, but I'm not sure what. ------ Rebuild All started: Project: alpineProbe, Configuration: Release Win32 ------ Deleting intermediate and output files for project 'abc', configuration 'Release|Win32' Compiling... wmiTest.cpp C:\Program Files\Microsoft Visual Studio 9.0\VC\include\excpt.h(60) : error C2065: '_$notnull' : undeclared identifier C:\Program Files\Microsoft Visual Studio 9.0\VC\include\excpt.h(60) : error C3861: '_Pre1_impl_': identifier not found C:\Program Files\Microsoft Visual Studio 9.0\VC\include\excpt.h(60) : error C2146: syntax error : missing ')' before identifier '_Deref_pre2_impl_' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\excpt.h(60) : warning C4229: anachronism used : modifiers on data are ignored C:\Program Files\Microsoft Visual Studio 9.0\VC\include\excpt.h(64) : error C2059: syntax error : ')' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\ctype.h(94) : error C2144: syntax error : 'int' should be preceded by ';' C:\Program Files\Microsoft Visual Studio 9.0\VC\include\ctype.h(94) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int I'm sure it's something obvious, but I don't see it. One other thing, I reloaded the project from a backup copy. Edit: Using /showIncludes as suggested by Michael Burr gives the following: 1>Note: including file: c:\development\alpineaccess\final\Tokenizer.h 1>Note: including file: c:\development\alpineaccess\final\testFunctions.h 1>Note: including file: c:\development\alpineaccess\final\curl/curl.h 1>Note: including file: c:\development\alpineaccess\final\curl\curlver.h 1>Note: including file: C:\Program Files\Microsoft Visual Studio 9.0\VC\include\stdio.h 1>Note: including file: C:\Program Files\Microsoft Visual Studio 9.0\VC\include\crtdefs.h 1>Note: including file: C:\Program Files\Microsoft Visual Studio 9.0\VC\include\sal.h 1>Note: including file: c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h 1>Note: including file: C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\windows.h 1>Note: including file: C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\sdkddkver.h 1>Note: including file: C:\Program Files\Microsoft Visual Studio 9.0\VC\include\excpt.h 1>Note: including file: C:\Program Files\Microsoft Visual Studio 9.0\VC\include\crtdefs.h Note that there's a circular reference via sourceannotations.h. I see what the problem is, but have no idea how to fix it.
Found it. Thanks to Michael Burr and his suggestion to use /showIncludes. The problem was that the file \CodeAnalysis\sourceannotations.h in the C++ installation had gotten clobbered. Reinstalling should fix it. Thanks for the help
1,268,682
1,268,707
Writing to user documents folder C++
I'm trying to write some info to the user's documents folder (eg. C:\Documents and Settings\[userName]), but I can't seem to find out how to grab the path programmatically. Is there any way to do this? C++, not using .NET. Thanks!
SHGetFolderPath with CSIDL_PERSONAL can be used to get the user's Documents folder. WCHAR path[MAX_PATH]; HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path);
1,269,019
1,269,049
What should happen to the negation of a size_t (i.e. `-sizeof(struct foo)`))?
I'm dealing with some code at work that includes an expression of the form -(sizeof(struct foo)) i.e. the negation of a size_t, and I'm unclear on what the C and C++ standards require of compilers when they see this. Specifically, from looking around here and elsewhere, sizeof returns an unsigned integral value of type size_t. I can't find any clear reference for specified behavior when negating an unsigned integer. Is there any, and if so, what is it? Edit: Ok, so there are some good answers regarding arithmetic on unsigned types, but it's not clear that this is in fact such. When this negates, is it operating on an unsigned integer, or converting to a signed type and doing something with that? Is the behavior to expect from the standards "imagine it's the negative number of similar magnitude and then apply the 'overflow' rules for unsigned values"?
Both ISO C and ISO C++ standards guarantee that unsigned arithmetic is modulo 2n - i.e., for any overflow or underflow, it "wraps around". For ISO C++, this is 3.9.1[basic.fundamental]/4: Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.41 ... 41) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type. For ISO C(99), it is 6.2.5/9: A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. Which means the result is guaranteed to be the same as SIZE_MAX - (sizeof(struct foo)) + 1. In ISO 14882:2003 5.3.1.7: [...] The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is the number of bits in the pro- moted operand. The type of the result is the type of the promoted operand.
1,269,131
1,269,336
Template's member typedef use in parameter undeclared identifier in VS but not GCC
I'm looking at some codes which makes heavy uses of templates. It compiles fine on GCC, but not on VS (tested on 2003 - 2010 beta 1), where it fails during syntax analysis. Unfortunately I don't know enough of the code structure to be able reduce the problem and reproduce it in only a few lines, so I can only guess at the cause. I'm hoping someone here can point me in the right direction. We have template< class UInt, typename IntT, bool is_signed = std::numeric_limits<IntT>::is_signed > struct uii_ops_impl; // .... template<class UInt> struct uii_ops_impl< UInt, typename make_signed<typename UInt::digit_type>::type, true > { typedef UInt unbounded_int_type; typedef typename make_signed< typename unbounded_int_type::digit_type >::type integral_type; // ... static void add(unbounded_int_type& lhs, integral_type rhs); // ... }; template<class UInt> void uii_ops_impl< UInt, typename make_signed<typename UInt::digit_type>::type, true >::add(unbounded_int_type& lhs, integral_type rhs) { // .... } When compiled on VS, the first error message (among many) it returns is : error C2065: 'unbounded_int_type' : undeclared identifier I mean, point at the typedef huh? :-S EDIT: It seems there's something to do with typename make_signed<typename UInt::digit_type>::type being used as a template parameter. Throughout the rest of the codes, similar typedefs being used in the member function parameter compiles fine. The only difference I can see so far is that none of the other cases have the above line as a template parameter. make_signed is from Boost.TypeTraits. EDIT: Okay, maybe that's not it, because the exact same thing is done in another file where it compiled fine. Hmm... Bounty EDIT: Okay, I think it's obvious at this point the problem is not actually where the compiler is complaining about. Only the two member functions definition at that particular point fail. It turns out that explicitly qualifying the parameter still doesn't compile. The only immediate solution is to define the function inline. That passes syntax analysis. However, when trying to instalize the template VS now fails because std::allocator<void> doesn't have a size_type member. Turns out VS have a specialization of std::allocator<T> for T=void that does not declare a size_type. I thought size_type is a required member of all allocators? So the question now is, what could possibly foul up VS so much during syntax analysis that it complains about completely unrelated non-problem as errors, and how do you debug such codes? p.s. For those that have too much time to spare, the code I'm trying to make work in VS is Kevin Sopp's mp_math in Boost's sandbox, which is based on libtommath.
I think this can be caused by a few circumstances unbounded_int_type is a non-dependent type (defined at 14.6.2.1) Its declaration appears in the class template. Because it's non-dependent, its name has to be resolved to a declaration at the time the member function is defined. I suspect that Visual C++ is not able to do this lookup, and errors out instead. As someone else mentions, you can explicitly qualify the type-names in the member function definition. The types are then dependent, and this will trigger the compiler's mechanism to delay name lookup until instantiation. template<class UInt> void uii_ops_impl< UInt, typename make_signed<typename UInt::digit_type>::type, true >::add(typename /* repeat-that-beast uii_ops...true> here */ ::unbounded_int_type& lhs, typename /* and here too */::integral_type rhs) { // .... }
1,269,216
1,269,235
Error passing 2D char* array into a function
I'm trying to pass a 2D array of char* into a function. I am getting this error: "cannot convert 'char* (*)[2]' to 'char***' for argument '1' to 'int foo(char***)'" Code: int foo(char*** hi) { ... } int main() { char* bar[10][10]; return foo(bar); }
Your array is an array of 10 char* arrays, each storing 10 char* pointers. This means that when passing it to a function whose parameter is not a reference, it is converted to a pointer to an array of 10 char*. The correct function parameter type is thus int foo(char* (*hi)[10]) { ... } int main() { char* bar[10][10]; return foo(bar); } Read further on this Pet peeve entry on Stackoverflow.
1,269,325
1,269,365
Boost regex not working as expected in my code
I just started using Boost::regex today and am quite a novice in Regular Expressions too. I have been using "The Regulator" and Expresso to test my regex and seem satisfied with what I see there, but transferring that regex to boost, does not seem to do what I want it to do. Any pointers to help me a solution would be most welcome. As a side question are there any tools that would help me test my regex against boost.regex? using namespace boost; using namespace std; vector<string> tokenizer::to_vector_int(const string s) { regex re("\\d*"); vector<string> vs; cmatch matches; if( regex_match(s.c_str(), matches, re) ) { MessageBox(NULL, L"Hmmm", L"", MB_OK); // it never gets here for( unsigned int i = 1 ; i < matches.size() ; ++i ) { string match(matches[i].first, matches[i].second); vs.push_back(match); } } return vs; } void _uttokenizer::test_to_vector_int() { vector<string> __vi = tokenizer::to_vector_int("0<br/>1"); for( int i = 0 ; i < __vi.size() ; ++i ) INFO(__vi[i]); CPPUNIT_ASSERT_EQUAL(2, (int)__vi.size());//always fails } Update (Thanks to Dav for helping me clarify my question): I was hoping to get a vector with 2 strings in them => "0" and "1". I instead never get a successful regex_match() (regex_match() always returns false) so the vector is always empty. Thanks '1800 INFORMATION' for your suggestions. The to_vector_int() method now looks like this, but it goes into a never ending loop (I took the code you gave and modified it to make it compilable) and find "0","","","" and so on. It never find the "1". vector<string> tokenizer::to_vector_int(const string s) { regex re("(\\d*)"); vector<string> vs; cmatch matches; char * loc = const_cast<char *>(s.c_str()); while( regex_search(loc, matches, re) ) { vs.push_back(string(matches[0].first, matches[0].second)); loc = const_cast<char *>(matches.suffix().str().c_str()); } return vs; } In all honesty I don't think I have still understood the basics of searching for a pattern and getting the matches. Are there any tutorials with examples that explains this?
The basic problem is that you are using regex_match when you should be using regex_search: The algorithms regex_search and regex_match make use of match_results to report what matched; the difference between these algorithms is that regex_match will only find matches that consume all of the input text, where as regex_search will search for a match anywhere within the text being matched. From the boost documentation. Change it to use regex_search and it will work. Also, it looks like you are not capturing the matches. Try changing the regex to this: regex re("(\\d*)"); Or, maybe you need to be calling regex_search repeatedly: char *where = s.c_str(); while (regex_search(s.c_str(), matches, re)) { where = m.suffix().first; } This is since you only have one capture in your regex. Alternatively, change your regex, if you know the basic structure of the data: regex re("(\\d+).*?(\\d+)"); This would match two numbers within the search string. Note that the regular expression \d* will match zero or more digits - this includes the empty string "" since this is exactly zero digits. I would change the expression to \d+ which will match 1 or more.
1,269,352
1,269,379
C++: Looking for a concise solution to replace a set of characters in a std::string with a specific character
Suppose I have the following: std::string some_string = "2009-06-27 17:44:59.027"; The question is: Give code that will replace all instances of "-" and ":" in some_string with a space i.e. " " I'm looking for a simple one liner (if at all possible) Boost can be used.
You could use Boost regex to do it. Something like this: e = boost::regex("[-:]"); some_string = regex_replace(some_string, e, " ");
1,269,378
1,699,635
tutorials about WinAPI unicode?
I'm wondering if you guys are aware of any article of some sort that shows how to make code fully unicode? Reason I ask is because I'm dealing with winapi right now and it seems that everything's supposed to be unicode like L"blabla" .. Functions that I've encountered won't work properly by simply using the standard string for example. Thanks!
When one of my projects need to be compiled with UNICODE on and off, I usually use the following definition to create an STL string that uses TCHAR instead of CHAR and wchar_t: #ifdef _UNICODE typedef std::wstring tstring; #else typedef std::string tstring; #endif or the following may also work: typedef std::basic_string<TCHAR> tstring; In my whole project I will then define all strings as tstring and use the _T() macro to create the strings correctly. When you then call a WIN32 API just use the .c_str() method on the string.
1,269,480
1,269,533
Globbing in C++/C, on Windows
Is there a smooth way to glob in C or C++ in Windows? E.g., myprogram.exe *.txt sends my program an ARGV list that has...ARGV[1]=*.txt in it. I would like to be able to have a function (let's call it readglob) that takes a string and returns a vector of strings, each containing a filename. This way, if I have files a.txt b.txt c.txt in my directory and readglob gets an argument *.txt, it returns the above filelist. //Prototype of this hypothetical function. vector<string> readglob(string); Does such exist?
Link with setargv.obj (or wsetargv.obj) and argv[] will be globbed for you similar to how the Unix shells do it: http://msdn.microsoft.com/en-us/library/8bch7bkk.aspx I can't vouch for how well it does it though.
1,269,568
1,269,651
How to pass a constant array literal to a function that takes a pointer without using a variable C/C++?
If I have a prototype that looks like this: function(float,float,float,float) I can pass values like this: function(1,2,3,4); So if my prototype is this: function(float*); Is there any way I can achieve something like this? function( {1,2,3,4} ); Just looking for a lazy way to do this without creating a temporary variable, but I can't seem to nail the syntax.
You can do it in C99 (but not ANSI C (C90) or any current variant of C++) with compound literals. See section 6.5.2.5 of the C99 standard for the gory details. Here's an example: // f is a static array of at least 4 floats void foo(float f[static 4]) { ... } int main(void) { foo((float[4]){1.0f, 2.0f, 3.0f, 4.0f}); // OK foo((float[5]){1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // also OK, fifth element is ignored foo((float[3]){1.0f, 2.0f, 3.0f}); // error, although the GCC doesn't complain return 0; } GCC also provides this as an extension to C90. If you compile with -std=gnu90 (the default), -std=c99, or -std=gnu99, it will compile; if you compile with -std=c90, it will not.
1,269,751
1,269,757
How to verify if a window of another program is minimized?
How can I do this? I've tried IsWindowVisible() but that doesn't seem to do the job.
To check whether a window is minimized, use IsIconic(HWND).
1,269,801
1,269,814
delete[] and memory leaks
I am wondering about the delete[] operator in C++. (I am using Visual Studio 2005). I have an unmanaged DLL that is being called by a managed DLL. When I close this program after performing a few tasks while debugging, I am getting many (thousands?) of memory leaks, mostly 24 bytes - 44 bytes in size.. I suspect it might be due to a certain unmanaged DLL I have. Anyway, from what I understand, if I have the following code: char* pointer = new char[500] /* some operations... */ delete[] pointer; Then all the memory for it is freed up correctly, am I right? What happens when I have the following code: char* pointer = new char[500]; char* pointerIt = pointer; /* some code perhaps to iterate over the whole memory block, like so */ for (int i = 0; i < 250; i++){ // only iterate halfway *pointerIt = 0; pointerIt++; } delete[] pointer; The memory pointed to by pointer is deleted right? So it means that pointerIt is now not pointing to valid memory.. But that's ok because I can set both pointers to NULL, right? Anyway, what happens now if I do this: char* pointerFirstPosition = new char[500]; char* pointerIt = pointerFirstPosition; for (int i = 0; i < 250; i++){ // only iterate halfway *pointerIt = 0; pointerIt++; } delete[] pointerIt; // delete the pointer iterator... Will this code delete the memory block pointed to by pointerIt up to pointerIt +500? or will it delete the memory block pointed to by pointerFirstPos to pointerFirstPos +500? Could this result in a memory leak? Sorry for the long winded message, I'm trying to get my message across clearly. Thanks, kreb
First question set: char* pointer = new char[500] /* some operations... */ delete[] pointer; Then all the memory for it is freed up correctly, am I right? right. Second question set: char* pointer = new char[500]; char* pointerIt = pointer; /* some code perhaps to iterate over the whole memory block, like so */ for (int i = 0; i < 250; i++){ // only iterate halfway *pointerIt = 0; pointerIt++; } delete[] pointer; The memory pointed to by pointer is deleted right? So it means that pointerIt is now not pointing to valid memory.. But that's ok because I can set both pointers to NULL, right? The memory pointer holds an address to is fully delted yes. Both pointer and pointerIt hold an address to invalid memory. Each pointer is simply a variable, and every variable is independent. So both store their own address independent of each other. The dereference operator * will simply give you the variable at that address. The variable at that address is a different variable than the pointer variable. Third question set: You should be deleting only the address that was allocated, the whole array. You'll have undefined results if you try to delete a partial array. Could it result in a memory leak? Possibly, could it result in a crash? Possibly, could it result in ....? Possibly. So only delete what you allocate. If you allocate an array then you delete with delete[] if you delete a type that is not an array you delete with delete. Here is an eample of something that is fine just for clarity: char* pointer = new char[500]; char* pointerIt = pointer; //This is fine because you are deleting the same address: delete[] pointerIt; //The memory that both variables point to is freed, do not try to free again
1,269,806
1,270,305
Qt Widget being resized twice upon initialization?
My "EditorView" (a QGLWidget) is being resized twice when it's created. It starts at say 846x630, then shrinks to 846x607 (losing 23 pixels in height). Created like this: EditorWindow::EditorWindow() { Q_INIT_RESOURCE(icons); readSettings(); setWindowTitle("Q2D Map Editor"); createActions(); createMenus(); createToolBars(); createStatusBar(); editorView = new EditorView; setCentralWidget(editorView); } And then this automatically gets called twice: void EditorView::resizeGL(int w, int h) { printf("%d x %d\n", w, h); glViewport(0, 0, w, h); updateView(); } I figure 23 pixels is about the size of the status bar, but the status bar should be already in place before the central widget is initialized, no? Or is it delayed for some reason? Callstack 1 http://img259.imageshack.us/img259/8881/callstack1.png Callstack 2 http://img259.imageshack.us/img259/2200/callstack2.png
You should set a breakpoint in the resizeGL method, and check the call stack, to see, in both cases, what was the reason for calling resizeGL. From code you provided, it is not obvious.
1,269,819
1,269,851
Implementing Skip List in C++
[SOLVED] So I decided to try and create a sorted doubly linked skip list... I'm pretty sure I have a good grasp of how it works. When you insert x the program searches the base list for the appropriate place to put x (since it is sorted), (conceptually) flips a coin, and if the "coin" lands on a then that element is added to the list above it(or a new list is created with element in it), linked to the element below it, and the coin is flipped again, etc. If the "coin" lands on b at anytime then the insertion is over. You must also have a -infinite stored in every list as the starting point so that it isn't possible to insert a value that is less than the starting point (meaning that it could never be found.) To search for x, you start at the "top-left" (highest list lowest value) and "move right" to the next element. If the value is less than x than you continue to the next element, etc. until you have "gone too far" and the value is greater than x. In this case you go back to the last element and move down a level, continuing this chain until you either find x or x is never found. To delete x you simply search x and delete it every time it comes up in the lists. For now, I'm simply going to make a skip list that stores numbers. I don't think there is anything in the STL that can assist me, so I will need to create a class List that holds an integer value and has member functions, search, delete, and insert. The problem I'm having is dealing with links. I'm pretty sure I could create a class to handle the "horizontal" links with a pointer to the previous element and the element in front, but I'm not sure how to deal with the "vertical" links (point to corresponding element in other list?) If any of my logic is flawed please tell me, but my main questions are: How to deal with vertical links and whether my link idea is correct Now that I read my class List idea I'm thinking that a List should hold a vector of integers rather than a single integer. In fact I'm pretty positive, but would just like some validation. I'm assuming the coin flip would simply call int function where rand()%2 returns a value of 0 or 1 and if it's 0 then a the value "levels up" and if it's 0 then the insert is over. Is this incorrect? How to store a value similar to -infinite? Edit: I've started writing some code and am considering how to handle the List constructor....I'm guessing that on its construction, the "-infinite" value should be stored in the vectorname[0] element and I can just call insert on it after its creation to put the x in the appropriate place.
Just store 2 pointers. One called above, and one called below in your node class. Not sure what you mean. According to wikipedia you can also do a geometric distribution. I'm not sure if the type of distribution matters for totally random access, but it obviously matters if you know your access pattern. I am unsure of what you mean by this. You can represent something like that with floating point numbers.
1,269,911
1,269,940
Have you used boost::tribool in real work?
tribool strikes me as one of the oddest corners of Boost. I see how it has some conveniences compared to using an enum but an enum can also be easily expanded represent more than 3 states. In what real world ways have you put tribool to use?
While I haven't used C++, and hence boost, I have used three-state variables quite extensively in a network application where I need to store state as true/false/pending.
1,269,994
1,270,011
nanoseconds to milliseconds - fast division by 1000000
I'm wanting to convert the output from gethrtime to milliseconds. The obvious way to do this is to divide by 1000000. However, I'm doing this quite often and wonder if it could become a bottleneck. Is there an optimized divide operation when dealing with numbers like 1000000? Note: Any code must be portable. I'm using gcc and this is generally on Sparc hardware Some quick testing using the code below... hope that is right. #include <sys/time.h> #include <iostream> using namespace std; const double NANOSECONDS_TO_MILLISECONDS = 1.0 / 1000000.0; int main() { hrtime_t start; hrtime_t tmp; hrtime_t fin; start = gethrtime(); tmp = (hrtime_t)(start * NANOSECONDS_TO_MILLISECONDS); fin = gethrtime(); cout << "Method 1" cout << "Original val: " << start << endl; cout << "Computed: " << tmp << endl; cout << "Time:" << fin - start << endl; start = gethrtime(); tmp = (start / 1000000); fin = gethrtime(); cout "Method 2" cout << "Original val: " << start << endl; cout << "Computed: " << tmp << endl; cout << "Time:" << fin - start << endl; return 0; } Example outputs: Original val: 3048161553965997 Computed: 3048161553 Time:82082 Original val: 3048161556359586 Computed: 3048161556 Time:31230 Original val: 3048239663018915 Computed: 3048239663 Time:79381 Original val: 3048239665393873 Computed: 3048239665 Time:31321 Original val: 3048249874282285 Computed: 3048249874 Time:81812 Original val: 3048249876664084 Computed: 3048249876 Time:34830 If this is correct, then the multiple by reciprocal is actually slower in this case. It's probably due to using floating point math instead of fixed point math. I will just stick to integer division then which still takes hardly any time at all.
Division is not an expensive operation. I doubt very much if a divide-by-1000000 operation will be anywhere near the main bottleneck in your application. Floating-point processors will be way faster than any sort of "tricks" you can come up with than just doing the single operation.
1,270,285
1,270,609
Trouble debugging C++ using Eclipse Galileo on Mac
I am trying to debug C++ code using Eclipse Galileo on my MacBook Pro running Mac OS X v10.5 (Leopard). It's my first time trying this. I have a complicated C++ program I'd like to debug, but to test things out, I just tried to debug and step through the following: #include <iostream> using namespace std; int main() { int x = 0; cout << x << endl; x = 54; cout << x << endl; return 0; } I clicked the debug icon, told it to use GDB (DSF) Create Process Launcher and started to step through the code. I wanted to be able to monitor the value of x, so I opened up the Variables window and watched. Initially, it was 4096 - presumably some garbage value. As soon as I hit the next line, where it had shown the value, it now shows the following error: Failed to execute MI command: -var-update 1 var1 Error message from debugger back end: Variable object not found I can't seem to figure this out or get around it. And a few Google searches turned up bone dry without even the hint of a lead. Solution: As drhirsch pointed out below, use the Standard Create Process Launcher instead of the GDB Create Process Launcher. (This is actually a workaround and not a true solution, but it worked for at least two of us.)
In my experience the gdb/dsf launcher is still quite unusable. I can't get it to show variables too, it seems still very buggy. Did you try the Standard Create Process Launcher? For me this works fine.
1,270,449
1,270,519
How would you replace the 'new' keyword?
There was an article i found long ago (i cant find it ATM) which states reasons why the new keyword in C++ is bad. I cant remember all of the reasons but the two i remember most is you must match new with delete, new[] with delete[] and you cannot use #define with new as you could with malloc. I am designing a language so i like to ask how would you change the C++ language so new is more friendly. Feel free to state problems with new and articles. I wish i can find the article link but i remember it was long and was written by a professor at (IIRC) a known school.
Problem match new, delete, new[], delete[] Not really a big deal. You should be wrapping memory allocation inside a class so this does not really affect normal users. A single obejct can be wrapped with a smart pointer. While an array can be represented by std::Vector<> cannot use #define with new as you could with malloc. The reason to mess with malloc like this was to introduce your own memory management layer between your app and the standard memory management layer. This is because in C you were not allowed to write your own version of malloc. In C++ it is quite legal to write your own version of the new which makes this trick unnecessary.
1,270,517
1,283,308
Porting project to my laptop results in a blank screen
So I'm making something in openGL using SDL. I'm about to take a long flight, and I can't seem to get the project to work on my laptop. I've used SDL on my laptop before, so I'm left thinking it is openGL's fault. The laptop is on win xp pro, and has an intel 945 graphics "card." I've tried updating the drivers, but to no avail. The images I'm using can't be the problem because I have it coded so the program closes if it can't locate the file. Also, I get no errors at all when compiling, it just creates the window, and instead of all my images, I get white. Just white. Any ideas? Please, I don't want to be on this 5 hr flight and go stir crazy =/
You might need to provide a bit more info, but at a guess I'd say your textures are invalid. OpenGL draws white when there is a texture problem. Possible reasons are... Image size is bigger than the max texture size of the graphics chip Image isn't power of 2 and the card doesn't support rectangular textures. You have run out of texture memory. Your texture env isn't supported by the graphics chip, eg. unsupported format. You aren't drawing what you think you are drawing, eg a white quad on a white background, in the position you think you are drawing it, ie you're looking in the wrong direction. Programmer error. Try drawing a single 128x128 texture on a single quad with a glcolor of purple and a clear colour of orange. This will eliminate most of the above problems and give you something to debug.
1,270,798
1,271,883
How to create data fom image like "Letter Image Recognition Dataset" from UCI
I am using letter_regcog example from OpenCV, it used dataset from UCI which have structure like this: Attribute Information: 1. lettr capital letter (26 values from A to Z) 2. x-box horizontal position of box (integer) 3. y-box vertical position of box (integer) 4. width width of box (integer) 5. high height of box (integer) 6. onpix total # on pixels (integer) 7. x-bar mean x of on pixels in box (integer) 8. y-bar mean y of on pixels in box (integer) 9. x2bar mean x variance (integer) 10. y2bar mean y variance (integer) 11. xybar mean x y correlation (integer) 12. x2ybr mean of x * x * y (integer) 13. xy2br mean of x * y * y (integer) 14. x-ege mean edge count left to right (integer) 15. xegvy correlation of x-ege with y (integer) 16. y-ege mean edge count bottom to top (integer) 17. yegvx correlation of y-ege with x (integer) example: T,2,8,3,5,1,8,13,0,6,6,10,8,0,8,0,8 I,5,12,3,7,2,10,5,5,4,13,3,9,2,8,4,10 now I have segmented image of letter and want to transform it into data like this to put recognize it but I don't understand the mean of all value like "6. onpix total # on pixels" what is it mean ? Can you please explain the mean of these value. thanks.
I am not familiar with OpenCV's letter_recog example, but this appears to be a feature vector, or set of statistics about the image of a letter that is used to classify the future occurrences of the letter. The results of your segmentation should leave you with a binary mask with 1's on the letter and 0's everywhere else. onpix is simply the total count of pixels that fall on the letter, or in other words, the sum of your binary mask. Most of the rest values in the list need to be calculated based on the set of pixels with a value of 1 in your binary mask. x and y are just the position of the pixel. For instance, x-bar is just the sample mean of all of the x positions of all pixels that have a 1 in the mask. You should be able to easily find references on the web for mathematical definitions of mean, variance, covariance and correlation. 14-17 are a little different since they are based on edge pixels, but the calculations should be similar, just over a different set of pixels.
1,270,927
1,270,948
Are function static variables thread-safe in GCC?
In the example code void foo() { static Bar b; ... } compiled with GCC is it guaranteed that b will be created and initialized in a thread-safe manner ? In gcc's man page, found the -fno-threadsafe-statics command line option: Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe. Does it mean, that local statics are thread-safe by default with GCC ? So no reason to put explicit guarding e.g. with pthread_mutex_lock/unlock ? How to write portable code - how to check if compiler will add its guards ? Or is it better to turn off this feature of GCC ?
No, it means that the initialization of local statics is thread-safe. You definitely want to leave this feature enabled. Thread-safe initialization of local statics is very important. If you need generally thread-safe access to local statics then you will need to add the appropriate guards yourself.
1,271,122
1,271,142
How to get ShowState of a window in c# or c++?
I am trying to get showstate of a window. I know that I can maximize, minimize, or close a window by ShowWindow API in c# or c++. How do I get ShowState of a window?
In C++: WINDOWPLACEMENT wp; GetWindowPlacement( hWnd, &wp ); UINT showCmd = wp.showCmd;
1,271,144
1,271,227
Is 'using namespace' inside another namespace equivalent to an alias?
Consider the following two statements: namespace foo = bar; and namespace foo { using namespace bar; } Are those two statements equivalent, or are there some subtle differences I'm not aware of? (Please note that this is not a question about coding style - I'm just interested in C++ parsing).
namespace foo=bar; This does not affect any name lookup rules. The only affect is to make 'foo' an alias to 'bar'. for example: namespace bar { void b(); } void f () { bar::b (); // Call 'b' in bar foo::b (); // 'foo' is an alias to 'bar' so calls same function } The following does change lookup rules namespace NS { namespace bar { } namespace foo { using namespace bar; void f () { ++i; } } } When lookup takes place for 'i', 'foo' will be searched first, then 'NS' then 'bar'.
1,271,248
1,271,692
C++: When (and how) are C++ Global Static Constructors Called?
I'm working on some C++ code and I've run into a question which has been nagging me for a while... Assuming I'm compiling with GCC on a Linux host for an ELF target, where are global static constructors and destructors called? I've heard there's a function _init in crtbegin.o, and a function _fini in crtend.o. Are these called by crt0.o? Or does the dynamic linker actually detect their presence in the loaded binary and call them? If so, when does it actually call them? I'm mainly interested to know so I can understand what's happening behind the scenes as my code is loaded, executed, and then unloaded at runtime. Thanks in advance! Update: I'm basically trying to figure out the general time at which the constructors are called. I don't want to make assumptions in my code based on this information, it's more or less to get a better understanding of what's happening at the lower levels when my program loads. I understand this is quite OS-specific, but I have tried to narrow it down a little in this question.
When talking about non-local static objects there are not many guarantees. As you already know (and it's also been mentioned here), it should not write code that depends on that. The static initialization order fiasco... Static objects goes through a two-phase initialization: static initialization and dynamic initialization. The former happens first and performs zero-initialization or initialization by constant expressions. The latter happens after all static initialization is done. This is when constructors are called, for example. In general, this initialization happens at some time before main(). However, as opposed to what many people think even that is not guaranteed by the C++ standard. What is in fact guaranteed is that the initialization is done before the use of any function or object defined in the same translation unit as the object being initialized. Notice that this is not OS specific. This is C++ rules. Here's a quote from the Standard: It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized
1,271,307
1,271,953
Why is VC++ C4150 (deletion of pointer to incomplete type) only a warning?
Of course, warning must be treated, but why is VC++ C4150 (deletion of pointer to incomplete type) only a warning?
Because standard says it's legal, although dangerous: 5.3.5 If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.
1,271,335
1,271,456
Inline Function (When to insert)?
Inline functions are just a request to compilers that insert the complete body of the inline function in every place in the code where that function is used. But how the compiler decides whether it should insert it or not? Which algorithm/mechanism it uses to decide? Thanks, Naveen
Some common aspects: Compiler option (debug builds usually don't inline, and most compilers have options to override the inline declaration to try to inline all, or none) suitable calling convention (e.g. varargs functions usually aren't inlined) suitable for inlining: depends on size of the function, call frequency of the function, gains through inlining, and optimization settings (speed vs. code size). Often, tiny functions have the most benefits, but a huge function may be inlined if it is called just once inline call depth and recursion settings The 3rd is probably the core of your question, but that's really "compiler specific heuristics" - you need to check the compiler docs, but usually they won't give much guarantees. MSDN has some (limited) information for MSVC. Beyond trivialities (e.g. simple getters and very primitive functions), inlining as such isn't very helpful anymore. The cost of the call instruction has gone down, and branch prediction has greatly improved. The great opportunity for inlining is removing code paths that the compiler knows won't be taken - as an extreme example: inline int Foo(bool refresh = false) { if (refresh) { // ...extensive code to update m_foo } return m_foo; } A good compiler would inline Foo(false), but not Foo(true). With Link Time Code Generation, Foo could reside in a .cpp (without a inline declararion), and Foo(false) would still be inlined, so again inline has only marginal effects here. To summarize: There are few scenarios where you should attempt to take manual control of inlining by placing (or omitting) inline statements.
1,271,367
1,271,587
Radix Sort implemented in C++
I am trying to improve my C++ by creating a program that will take a large amount of numbers between 1 and 10^6. The buckets that will store the numbers in each pass is an array of nodes (where node is a struct I created containing a value and a next node attribute). After sorting the numbers into buckets according to the least significant value, I have the end of one bucket point to the beginning of another bucket (so that I can quickly get the numbers being stored without disrupting the order). My code has no errors (either compile or runtime), but I've hit a wall regarding how I am going to solve the remaining 6 iterations (since I know the range of numbers). The problem that I'm having is that initially the numbers were supplied to the radixSort function in the form of a int array. After the first iteration of the sorting, the numbers are now stored in the array of structs. Is there any way that I could rework my code so that I have just one for loop for the 7 iterations, or will I need one for loop that will run once, and another loop below it that will run 6 times before returning the completely sorted list? #include <iostream> #include <math.h> using namespace std; struct node { int value; node *next; }; //The 10 buckets to store the intermediary results of every sort node *bucket[10]; //This serves as the array of pointers to the front of every linked list node *ptr[10]; //This serves as the array of pointer to the end of every linked list node *end[10]; node *linkedpointer; node *item; node *temp; void append(int value, int n) { node *temp; item=new node; item->value=value; item->next=NULL; end[n]=item; if(bucket[n]->next==NULL) { cout << "Bucket " << n << " is empty" <<endl; bucket[n]->next=item; ptr[n]=item; } else { cout << "Bucket " << n << " is not empty" <<endl; temp=bucket[n]; while(temp->next!=NULL){ temp=temp->next; } temp->next=item; } } bool isBucketEmpty(int n){ if(bucket[n]->next!=NULL) return false; else return true; } //print the contents of all buckets in order void printBucket(){ temp=bucket[0]->next; int i=0; while(i<10){ if(temp==NULL){ i++; temp=bucket[i]->next; } else break; } linkedpointer=temp; while(temp!=NULL){ cout << temp->value <<endl; temp=temp->next; } } void radixSort(int *list, int length){ int i,j,k,l; int x; for(i=0;i<10;i++){ bucket[i]=new node; ptr[i]=new node; ptr[i]->next=NULL; end[i]=new node; } linkedpointer=new node; //Perform radix sort for(i=0;i<1;i++){ for(j=0;j<length;j++){ x=(int)(*(list+j)/pow(10,i))%10; append(*(list+j),x); printBucket(x); }//End of insertion loop k=0,l=1; //Linking loop: Link end of one linked list to the front of another for(j=0;j<9;j++){ if(isBucketEmpty(k)) k++; if(isBucketEmpty(l) && l!=9) l++; if(!isBucketEmpty(k) && !isBucketEmpty(l)){ end[k]->next=ptr[l]; k++; if(l!=9) l++; } }//End of linking for loop cout << "Print results" <<endl; printBucket(); for(j=0;j<10;j++) bucket[i]->next=NULL; cout << "End of iteration" <<endl; }//End of radix sort loop } int main(){ int testcases,i,input; cin >> testcases; int list[testcases]; int *ptr=&list[0]; for(i=0;i<testcases;i++){ cin>>list[i]; } radixSort(ptr,testcases); return 0; }
I think you're severely overcomplicating your solution. You can implement radix using the single array received in the input, with the buckets in each step represented by an array of indices that mark the starting index of each bucket in the input array. In fact, you could even do it recursively: // Sort 'size' number of integers starting at 'input' according to the 'digit'th digit // For the parameter 'digit', 0 denotes the least significant digit and increases as significance does void radixSort(int* input, int size, int digit) { if (size == 0) return; int[10] buckets; // assuming decimal numbers // Sort the array in place while keeping track of bucket starting indices. // If bucket[i] is meant to be empty (no numbers with i at the specified digit), // then let bucket[i+1] = bucket[i] for (int i = 0; i < 10; ++i) { radixSort(input + buckets[i], buckets[i+1] - buckets[i], digit+1); } } Of course buckets[i+1] - buckets[i] will cause a buffer overflow when i is 9, but I omitted the extra check or readability's sake; I trust you know how to handle that. With that, you just have to call radixSort(testcases, sizeof(testcases) / sizeof(testcases[0]), 0) and your array should be sorted.
1,271,513
1,271,691
C++ code visualization
A sort of follow up/related question to this. I'm trying to get a grip on a large code base that has hundreds and hundreds of classes and a large inheritance hierarchy. I want to be able to see the "main veins" of the inheritance hierarchy at a glance - not all the "peripheral" classes that only do some very specific / specialized thing. Visual Studio's "View Class Diagram" makes something that looks like a train and its sprawled horizontally across the screen and isn't very organized. You can't grok it easily. I've just tried doxygen and graphviz but the results are .. somewhat similar to Visual Studio. I'm getting sweet looking call graphs but again too much detail for what I'm trying to get. I need a quick way to generate the inheritance hierarchy, in some kind of collapsible view.
Why not just do it manually, it is a great learning experience when starting to work with a large code base. I usually just look at what class inherits from what, and what class contain what instances, references or pointers to other classes. Have a piece of paper next to you and get drawing...
1,271,784
1,272,723
using QTextStream to read stdin in a non-blocking fashion
Using Qt, I'm attempting to read the contents of the stdin stream in a non-blocking fashion. I'm using the QSocketNotifier to alert me when the socket has recieved some new data. The setup for the notifier looks like this: QSocketNotifier *pNot = new QSocketNotifier(STDIN_FILENO, QSocketNotifier::Read, this); connect(pNot, SIGNAL(activated(int)), this, SLOT(onData())); pNot->setEnabled(true); The onData() slot looks like this: void CIPCListener::onData() { qDebug() << Q_FUNC_INFO; QTextStream stream(stdin, QIODevice::ReadOnly); QString str; forever { fd_set stdinfd; FD_ZERO( &stdinfd ); FD_SET( STDIN_FILENO, &stdinfd ); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; int ready = select( 1, &stdinfd, NULL, NULL, &tv ); if( ready > 0 ) { str += stream.readLine(); } else { break; } } qDebug() << "Recieved data:" << str; } As you can see I'm attempting to use the select() system call to tell me when I've run out of data to read. However, in practise what is happening is the select() call returns 0 after I've read the first line of text. So, for example, if I write 5 lines of text to the process's stdin stream, I only ever read the first line. What could be the problem?
Line buffering. Default is flushing after a "\n". If you write 5 lines to your process, your slot gets called 5 times. If you want to avoid that, you have to call setbuf(stdin, _IOFBF). But even then it is not guaranteed you can read arbitrarily large amounts of data in one chunk. Edit: It would probably better to use QTextStream::atEnd() instead of select, since QTextStream has its own internal buffers.
1,272,073
1,272,122
boost interprocess : shared memory and stl types
I have a simple struct : struct MyType { std::string name; std::string description; } and I'm putting it in a shared memory : managed_shared_memory sharedMemory(open_or_create, "name", 65535); MyType* pType = sharedMemory.construct<MyType>("myType")(); // ... setting pType members ... If the two applications communicating with the shared memory are built using different version of Visual Studio (different version of stl implementation) should I put native types in the shared memory (e.g. char*) instead of stl types? Edit : I tried with typedef boost::interprocess::basic_string<char> shared_string; and it works!
Boost.Interprocess often offers replacements for STL types, for usage in shared memory. std::string, especially when just a member of a struct, will not be accessible from another process. Other people also had such a problem.
1,272,120
1,283,446
What are the error messages for breaking the GLSL shader instruction limits?
We're a small dev team working with some GLSL that may be too large for older graphics cards to compile. We want to display a sensible error message to the user (rather than just dump the info log or output a generic 'this shader didn't work' type of message) when this happens based on the type of error. The question is, ATI and nVidia have different conventions for these error messages and the only way I've found to decide what type of error the shader had is to parse the error string generated by glGetShaderInfoLog. Given that, is there a listing somewhere or does anyone know what the error output for both ATI and nVidia cards looks like? Or is there a better way to detect when the instruction limit has been exceeded?
Even if you know what the error messages look like now, nVidia and ATI are under no obligation to keep them the same in the next version(s) of their drivers. They basically can't be relied on for anything except debugging purposes. I would look and see if the vendor extensions might be able to provide you with more specific diagnostic information.
1,272,161
1,272,341
Unlocked access to stl vector::size safeness
I've several writers(threads) and one reader on a stl vector. Normal writes and reads are mutex protected, but I would like to avoid contention on a loop I have and I was wondering if vector::size would be safe enough, I suppose it depends on implementations, but since normally vector dynamic memory is for the stored items the memory where the size is stored shouldn't be invalidated during reallocations. I don't mind to have false positives, after a size > 0 I'll actually lock and check again so if reading size() while another thread writes doesn't segfault ever it should be safe enough for me.
I don't know off-hand of an implementation in which concurrent reads and writes to an integer segfault (although the C++03 standard does not prohibit that, and I don't know whether POSIX does). If the vector uses pImpl, and doesn't store the size in the vector object itself, you could maybe have problems where you try to read the size from a pImpl object which has been freed in another thread. For example, GCC on my machine does use a pImpl (and doesn't store the size directly - it's calculated as the difference between begin() and end(), so there's obvious opportunities there for race conditions during modification). Even if it doesn't crash, though, it might very well give a meaningless or wrong answer. If you don't lock then the value you read could for example be: read non-atomically, meaning you get the most significant half of one value and the least significant half of another. In practice, reading size_t is probably atomic on most implementations, since there are good reasons for size_t to be the natural word size of the architecture. But if it happens, this could read a value as 0 when neither the "before" not the "after" was 0. Consider for example the transition 0x00FF -> 0x0100. If you get the bottom half of the "after" and the top half of "before", you've read 0. arbitrarily stale. Without locking (or some other memory barrier), you could get a value out of a cache. If that cache is not shared with other CPUs/cores, and if your architecture does not have so-called 'coherent caches', then a different CPU or core running a different thread could have changed the size six weeks ago, and you will never see the new value. Furthermore, different addresses might be different amounts stale - without memory barriers, if another thread has done a push_back you could conceivably "see" the new value at the end of your vector but not "see" the increased size. A lot of these problems are hidden on common architectures. For instance, x86 has coherent caches, and MSVC guarantees full memory barriers when accessing volatile objects. ARM doesn't guarantee coherent caches, but in practice multi-core ARM isn't that common, so double-checked locking normally works there too. These guarantees solve some difficulties and allow some optimisations, which is why they're made in the first place, but they're not universal. Obviously you can't write multi-threaded code at all without making some assumptions beyond the C++ standard, but the more vendor-specific guarantees you rely on, the less portable your code is. It's not possible to answer your question other than with reference to a particular implementation. If you're writing portable code, then really you should think of all memory reads and writes as potentially being to your thread's own private memory cache. Memory barriers (including locks) are a means to "publish" your writes and/or "import" writes from other threads. The analogy with version-control systems (or your favourite other example of local copies of anything) is clear, with the difference that things might be published/imported at any time, even if you don't ask them to be. And of course there's no merging or conflict detection, unless the industry has finally implemented transactional memory while I wasn't looking ;-) In my opinion, multi-threaded code should first avoid shared memory, then lock if absolutely necessary, then profile, then worry about contention and lock-free algorithms. Once you get to the last stage, you need to research and follow well-tested principles and patterns for your particular compiler and architecture. C++0x will help somewhat by standardising some things you can rely on, and some of Herb Sutter's "Effective Concurrency" series goes into details how to make use of these guarantees. One of the articles has an implementation of a lock-free multi-writer single-reader queue, which may or may not be adaptable for your purposes.
1,272,398
1,278,465
How to send a notification that's handled by ON_NOTIFY?
I'm trying to post a LVN_ ITEMCHANGED to my custom gridlist's owner. I know how to send a WM_ User message using PostMessage (as shown here) ::PostMessage( AfxGetMainWnd()->GetSafeHwnd(), WM_REFRESH, (WPARAM)pBuffer, (LPARAM)GetOutputIdx() ); When I use this same code to send a LVN_ITEMCHANGED message though, ::PostMessage( AfxGetMainWnd()->GetSafeHwnd(), LVN_ITEMCHANGED, 0, 0); it doesn't seem to be caught by the ON_NOTIFY(LVN_ITEMCHANGED, ..., ...) I have in the owner class. Am I wrong to be using ::PostMessage to send a Notify event? Is there a difference between Notify messages and WM_ prefix messages or how they're handled? Can someone post a sample of how I would send the message properly? Thanks in advance. Edit I found another solution to the problem. See my answer below.
I found out that I could override the message handler in my derived class and pass the message on to my parent control simply by using this code in the message map: ON_NOTIFY_REFLECT_EX(LVN_ITEMCHANGED, OnListItemChanged) Then in OnListItemChanged, I first call the base class function then return FALSE. This causes the message to be reflected to the parent class effortlessly.
1,272,680
1,272,707
What does a colon following a C++ constructor name do?
What does the colon operator (":") do in this constructor? Is it equivalent to MyClass(m_classID = -1, m_userdata = 0);? class MyClass { public: MyClass() : m_classID(-1), m_userdata(0) { } int m_classID; void *m_userdata; };
This is a member initializer list, and is part of the constructor's implementation. The constructor's signature is: MyClass(); This means that the constructor can be called with no parameters. This makes it a default constructor, i.e., one which will be called by default when you write MyClass someObject;. The part : m_classID(-1), m_userdata(0) is called member initializer list. It is a way to initialize some fields of your object (all of them, if you want) with values of your choice. After executing the member initializer list, the constructor body (which happens to be empty in your example) is executed. Inside it you could do more assignments, but once you have entered it all the fields have already been initialized - either to random, unspecified values, or to the ones you chose in your initialization list. This means the assignments you do in the constructor body will not be initializations, but changes of values.
1,272,775
1,272,790
Printing the value of a float to 2 decimal places
I have a float with the value of e.g 57.400002. I use sprintf_s to display the value on my GUI. sprintf_s(xPosition, 19, "%f", xPositionValue); How can I format the float so it displays as 57.40?
sprintf_s(xPosition, 19, "%.2f", xPositionValue);
1,273,026
1,273,034
limit size of Queue<T> in C++
I notice the thread of similar question: Limit size of Queue<T> in .NET? That's exactly what I want to do, but I am not using .net but GNU C++. I have no reference to the base class in GNU C++, so java like super.***() or .net like base.***() will not work. I have been trying to inherit from queue class but it turns out in vain. What I want to do: specify the size of the queue, and automatically dequeue when the queue is full. To be specific: if the maximum size of my queue is 2, when I push the 3rd item, the 1st item will be automatically popped out before pushing the new item. How to implement such a queue? Thanks.
Make a new class that encapsulates the queue and enforce a size limit in the new class.
1,273,148
1,273,163
C++ constructor definition
All of the constructors methods here do the same thing. I mostly use method2 but saw method3 for the first time today. Have seen method1 in some places but dont know what are the exact differences between them ? Which one is the best way to define constructors and why ? Is there any performance issues involved ? 1 class Test 2 { 3 private: 4 int a; 5 char *b; 6 public: 7 Test(){}; 8 9 // method 1 10 Test(int &vara, char *& varb) : a(vara), b(varb){} 11 12 // method 2 13 Test(int &vara, char *& varb) 14 { 15 a = vara; 16 b = varb; 17 } 18 19 //method 3 20 Test(int &vara, char *& varb) 21 { 22 this->a = vara; 23 this->b = varb; 24 } 25 26 ~Test(){} 27 }; I have here used simple fields int and char*,what will happen if I have many fields or complex types like struct ?? Thanks
For the types you use, there will probably be no difference in performance. However for non-POD data (classes with constructors) the form: Test(int &vara, char *& varb) : a(vara), b(varb){} will be the most efficient. This is because non-POD data will be initialised whther you provide an initialisation list or not. The other forms, which use assignment, will take the hit for initialisation, and then another hit for assignment.
1,273,295
1,273,355
Java FAQ equivalent of C++ FAQ lite?
Is there any Java FAQ equivalent of the Parashift C++ FAQ lite ? (Books like Effective Java are handy to have around, but I'm looking for a comprehensive online (advanced) Java FAQ that I could use)
There is nothing quite like it that I know of, but Angelika Langer's Generics FAQ covers generics pretty well. Also, you might find Roedy Green's Java Glossary handy.
1,273,548
1,274,893
How is Non-Virtual Interface pattern imlemented in C++?
I am curious about both, a h single and multi-threaded implementation. Thanks
Your question is vague, but it sounds like you want the Curiously recurring template pattern There are a lot better people than I to explain this on the web it is used a lot in the boost library. check out boost.iterator documentation and code for a good example
1,273,572
1,273,601
Will pthreads become obsolete once std:thread makes into C++Ox
Obviously we will still maintain it, but how useful will it be, once the C++ standard guarantees is. What about synchronization primitives (Mutex, conditional variables) with advent of the new standard? Do you consider pthread harder to master as opposed to std::thread?
C isn't going away. POSIX isn't going away. Multithreaded code written in C for POSIX isn't going away. So pthreads isn't going away. Many implementations of std::thread will use pthreads under the hood. "The Pthreads API is defined in the ANSI/IEEE POSIX 1003.1 - 1995 standard." -- POSIX Threads Programming https://computing.llnl.gov/tutorials/pthreads/
1,273,687
1,273,749
Why or why not should I use 'UL' to specify unsigned long?
ulong foo = 0; ulong bar = 0UL;//this seems redundant and unnecessary. but I see it a lot. I also see this in referencing the first element of arrays a good amount blah = arr[0UL];//this seems silly since I don't expect the compiler to magically //turn '0' into a signed value Can someone provide some insight to why I need 'UL' throughout to specify specifically that this is an unsigned long?
void f(unsigned int x) { // } void f(int x) { // } ... f(3); // f(int x) f(3u); // f(unsigned int x) It is just another tool in C++; if you don't need it don't use it!
1,273,833
1,273,892
How to send output of native executable programs into the world of Web Services?
I have many C/C++ old native .exe and .dll programs running on Windows servers of my company. Some .exe programs (I will designate with E) get results on the console or into a file and most of .dll programs (D) return results in arrays of structures. My boss has asked me for the possibility to “also” send the results generated by ‘E’ and ‘D’ to a .NET Web Service platform using WCF without modifying ‘E’ and ‘D’. I read a little about Web Services/WCF to have an answer. However, I built a first solution scenario in my mind: create C# WCF projects which: For ‘E’, will read the files generated by the ‘E’ programs and will send the results to clients For ‘D’, will “interoperate and marshall” with the returned values before sending the results. I have some questions here; after getting the results from ‘E’ and ‘D’, how do I send these results to the client? Is this a “must” to serialize the results before sending to the client program? I suppose the client program should have a routine to deserialize. If the value to send to the client is a simple string or a simple integer, is this necessary to serialize? Thanks!!
First of all, you should be aware that there are different kinds of webservices. The most common ones are REST and SOAP. I assume that you want to use SOAP. In that case every message has to be encoded, but that will be handled by your SOAP library/framework. The same is true for the client. He will usually not decode SOAP messages "by hand". It's handled by the clients SOAP library/framework. Your thoughts about integrating E and D are right. For D you might also have a look at CLI/C++. It might make integration easier, but that depends on your scenario and your .Net and C++ knowledge.
1,273,900
1,274,208
delete boost function while in use
I have a situation where a boost::function and boost::bind (actually a std::tr1::function and bind) are being deleted while still in use. Is this safe? I would normally avoid it, but the offending code is a bit entrenched and my only other option is adding a new thread. typedef function<int(int)> foo_type; foo_type* global_foo = NULL; int actual_foo( int i, Magic* m ) { delete global_foo; return m->magic(i); } int main() { Magic m; global_foo = new foo_type( bind( &actual_foo, _1, &m ); return (*global_foo)(10) } The bound parameters are always plain integral types (an int and a pointer in the real code), and not references.
boost::function or std::tr1::functions are copyable objects. So, generally there is absolutly no reason to allocate them -- just pass them by value. They are well optimized for most of real cases... So just pass them by value: typedef function<int(int)> foo_type; foo_type global_foo; int actual_foo( int i, Magic* m ) { delete global_foo; return m->magic(i); } int main() { Magic m; global_foo = bind( &actual_foo, _1, &m ); return global_foo(10) } The code you suggested is dangerous, run this code: #include <boost/function.hpp> #include <boost/bind.hpp> #include <iostream> using namespace std; boost::function<void()> *glb; struct Data { int x; Data(int _x = 0) : x(_x) { cout<<"ctor:"<<this<<endl; } ~Data() { cout<<"dtor:"<<this<<endl; } Data(Data const &p) {x=p.x; cout<<"ctor:"<<this<<endl; } Data const &operator=(Data const &p) { x=p.x; cout<<this<<"="<<&p<<endl; return *this; } }; void func(Data const &x) { delete glb; cout<<&x<<endl; } int main() { glb=new boost::function<void()>(boost::bind(func,Data(3))); (*glb)(); return 0; } You would find that you try to access in func to destoryed object (dtor with same pointer value) that is shown in cout<<&x<<endl was already called. Because when you destroy your function objects you also destroy the binded parameters you have and Data const &x become unavailible becuase it was destoryed with global_function Edit: Clearification for comment: If you have something like map<string,function<void()> > calls; void delete_key(){ calls.erase("key"); } main() { calls["key"]=delete_key; // Wrong and dangerous // You delete function while in use calls["key"](); // Correct and safe // You create a copy of function so it would not // be deleted while in use. function<void()> f=calls["key"]; f(); }
1,274,022
1,276,295
Getting the size of a Qt Object
I'm using Qt and C++, I need to find out the amount of memory used by instances of certain Qt classes, this is usually done using sizeof, however in Qt each class holds a pointer to an another class containing the actual implementation, the definition of this private implementation class is not found in headers but only in the source-code. I'm new to Qt so may be there's a standard way to do this, if there isn't do you have any ideas to solve this?
There's no exact answer to the question, since the amount of memory allocated for different objects of the same type might not even be the same (e.g. QSomething A might be able to reuse some data from a cache whereas QSomething B might have to allocate it separately, etc). What you could do, I suppose, is write a trivial test program that starts up, allocates N of the object in question, then goes to sleep() for a long time. While the program is sleeping, use Task Manager (or whatever tool you prefer) to see how much RAM the process is using. Then ctrl-C (or kill) the process, and run it again with a larger value for N, and repeat the measurement. Repeat that process and eventually you'll get an idea of how the process's RAM allocation grows with the number of items allocated, and then you can do a little algebra to get a ballpark idea of the average memory cost per object. (keep in mind that there's a good bit of memory overhead just in starting the process, so subtract the memory used by the N=0 case from all the cases so that you're measuring just the objects' costs and not the environmental overhead)
1,274,036
1,276,419
Generating C++ BackTraces in OS/X (10.5.7)
I've been utilizing backtrace and backtrace_symbols to generate programmatic stack traces for the purposes of logging/diagnosis. It seems to roughly work, however, I'm getting a little bit of mangling and there are no accompanying file/line numbers associated with each function invocation (as I'd expect within a gdb bt call or something). Here's an example: 1 leonardo 0x00006989 _ZN9ExceptionC2E13ExceptionType + 111 2 leonardo 0x00006a20 _ZN9ExceptionC1E13ExceptionType + 24 3 leonardo 0x0000ab64 _ZN5Rules11ApplyActionER16ApplicableActionR9GameState + 1060 4 leonardo 0x0000ed15 _ZN9Simulator8SimulateEv + 2179 5 leonardo 0x0000eec9 _ZN9Simulator8SimulateEi + 37 6 leonardo 0x00009729 main + 45 7 leonardo 0x000025c6 start + 54 Anything I'm missing something, doing something silly, or is this all I can expect out of backtrace on OS/X? Some other tidbits: I don't see a rdynamic link option for the g++ version (4.0.1) I'm using. -g/-g3 doesn't make any difference. abi::__cxa__demangle doesn't seem to do anything
The backtraces typically come back from backtrace_symbols in the following format: ./MyApp(_ZN4test3fooEv+0x8) [0x821c874] abi::__cxa_demangle expects only the function name. Thus, some parsing must first be done on the trace: std::string trace(backtrace[idx]); // attempt to demangle { std::string::size_type begin, end; // find the beginning and the end of the useful part of the trace begin = trace.find_first_of('(') + 1; end = trace.find_last_of('+'); // if they were found, we'll go ahead and demangle if (begin != std::string::npos && end != std::string::npos) { trace = trace.substr(begin, end - begin); size_t maxName = 1024; int demangleStatus; char* demangledName = (char*) malloc(maxName); if ((demangledName = abi::__cxa_demangle(trace.c_str(), demangledName, &maxName, &demangleStatus)) && demangleStatus == 0) { trace = demangledName; // the demangled name is now in our trace string } free(demangledName); } } I've tested this is on my own project, and it gives somewhat nicer backtraces with the following format: test::foo() Sure, there are no line numbers, but I'm not certain that is even possible.
1,274,189
1,279,814
Why is CoCreation of a COM+ component failing with 0x8007007e "The specified module could not be found"?
I have a COM dll that is working fine as an in-proc server and I install it in Component Services COM+ Applications. Now when I try to CoCreate it from my client app, I get HRESULT 0x8007007e "The specified module could not be found". What could be causing this?
The dll was registered on a ClearCase dynamic view, similar to a mapped drive, not available to COM+. Solution was to move the dll and the proxy/stub dll to a local drive and register them there.
1,274,428
1,274,441
Can you declare a pointer on the heap?
This is the method for creating a variable on the heap in C++: T *ptr = new T; ptr refers to a pointer to the new T, obviously. My question is, can you do this: T *ptr = new T*; That seems like it could lead to some very, very dangerous code. Does anyone know if this is possible/how to use it properly?
int** ppint = new int*; *ppint = new int; delete *ppint; delete ppint;
1,274,460
1,274,483
QApplication without display
I using Qt3.3 and I'm trying to create an QApplication without display. I need to check signals from QSocket objects, and this is the reason that I need the QApplication. I'm trying to do QApplication( 0, 0 ), but I'm getting "QApplication: invalid Display* argument.". How is the correct way to do it?
From the docs: QApplication::QApplication ( int & argc, char ** argv, bool GUIenabled ) Constructs an application object with argc command line arguments in argv. If GUIenabled is TRUE, a GUI application is constructed, otherwise a non-GUI (console) application is created. Set GUIenabled to FALSE for programs without a graphical user interface that should be able to run without a window system. You get that message because the compiler probably binds against this constructor method QApplication::QApplication(Display *dpy,HANDLE visual=0,HANDLE colormap=0) treating your first zero as a NULL pointer to Display * (I guess this is a Display structure you can get from X11)
1,274,484
1,274,853
Avoiding global variables in embedded programming
In the type of embedded programming I'm getting into, determinism and transparency of the running code are highly valued. What I mean by transparency is, for instance, being able to look at arbitrary sections of memory and know what variable is stored there. So, as I'm sure embedded programmers expect, new is to be avoided if at all possible, and if it can't be avoided, then limited to initialization. I understand the need for this, but don't agree with the way my coworkers have gone about doing this, nor do I know a better alternative. What we have are several global arrays of structures, and some global classes. There is one array of structs for mutexes, one for semaphores, and one for message queues (these are initialized in main). For each thread that runs, the class that owns it is a global variable. The biggest problem I have with this is in unit testing. How can I insert a mock object when the class I want to test #includes global variables that I don't? Here's the situation in pseudo-code: foo.h #include "Task.h" class Foo : Task { public: Foo(int n); ~Foo(); doStuff(); private: // copy and assignment operators here } bar.h #include <pthread.h> #include "Task.h" enum threadIndex { THREAD1 THREAD2 NUM_THREADS }; struct tThreadConfig { char *name, Task *taskptr, pthread_t threadId, ... }; void startTasks(); bar.cpp #include "Foo.h" Foo foo1(42); Foo foo2(1337); Task task(7331); tThreadConfig threadConfig[NUM_THREADS] = { { "Foo 1", &foo1, 0, ... }, { "Foo 2", &foo2, 0, ... }, { "Task", &task, 0, ... } }; void FSW_taskStart() { for (int i = 0; i < NUMBER_OF_TASKS; i++) { threadConfig[i].taskptr->createThread( ); } } What if I want more or less tasks? A different set of arguments in the constructor of foo1? I think I would have to have a separate bar.h and bar.cpp, which seems like a lot more work than necessary.
If you want to unit test such code first I would recommend reading Working Effectively With Legacy Code Also see this. Basically using the linker to insert mock/fake objects and functions should be a last resort but is still perfectly valid. However you can also use inversion of control, without a framework this can push some responsibility to the client code. But it really helps testing. For instance to test FSW_taskStart() tThreadConfig threadConfig[NUM_THREADS] = { { "Foo 1", %foo1, 0, ... }, { "Foo 2", %foo2, 0, ... }, { "Task", %task, 0, ... } }; void FSW_taskStart(tThreadConfig configs[], size_t len) { for (int i = 0; i < len; i++) { configs[i].taskptr->createThread( ); } } void FSW_taskStart() { FSW_taskStart(tThreadConfig, NUM_THREADS); } void testFSW_taskStart() { MockTask foo1, foo2, foo3; tThreadConfig mocks[3] = { { "Foo 1", &foo1, 0, ... }, { "Foo 2", &foo2, 0, ... }, { "Task", &foo3, 0, ... } }; FSW_taskStart(mocks, 3); assert(foo1.started); assert(foo2.started); assert(foo3.started); } Now you can can can pass mock version of you're threads to 'FSW_taskStart' to ensure that the function does in fact start the threads as required. Unfortunatly you have to rely on the fact that original FSW_taskStart passes the correct arguments but you are now testing a lot more of your code.
1,274,549
1,274,882
C++ Spin Image Resources
Does anyone know of a good resource that will show me how to load an image with C++ and spin it? What I mean by spin is to do an actual animation of the image rotating and not physically rotating the image and saving it. If I am not clear on what I am asking, please ask for clarification before downvoting. Thanks
You could use SDL and the extension sdl_image and/or sdl_gfx
1,274,910
1,275,260
does (w)ifstream support different encodings
When I read a text file to a wide character string (std::wstring) using an wifstream, does the stream implementation support different encodings - i.e. can it be used to read e.g. ASCII, UTF-8, and UTF-16 files? If not, what would I have to do? (I need to read the entire file, if that makes a difference)
C++ supports character encodings by means of std::locale and the facet std::codecvt. The general idea is that a locale object describes the aspects of the system that might vary from culture to culture, (human) language to language. These aspects are broken down into facets, which are template arguments that define how localization-dependent objects (include I/O streams) are constructed. When you read from an istream or write to a ostream, the actual writing of each character is filtered through the locale's facets. The facets cover not only encoding of Unicode types but such varied features as how large numbers are written (e.g. with commas or periods), currency, time, capitalization, and a slew of other details. However just because the facilities exist to do encodings doesn't mean the standard library actually handles all encodings, nor does it make such code simple to do right. Even such basic things as the size of character you should be reading into (let alone the encoding part) is difficult, as wchar_t can be too small (mangling your data), or too large (wasting space), and the most common compilers (e.g. Visual C++ and Gnu C++) do differ on how big their implementation is. So you generally need to find external libraries to do the actual encoding. iconv is generally acknowledge to be correct, but examples of how to bind it to the C++ mechanism are hard to find. jla3ep mentions libICU, which is very thorough but the C++ API does not try to play nicely with the standard (As far as I can tell: you can scan the examples to see if you can do better.) The most straightforward example I can find that covers all the bases, is from Boost's UTF-8 codecvt facet, with an example that specifically tries to encode UTF-8 (UCS4) for use by IO streams. It looks like this, though I don't suggest just copying it verbatim. It takes a little more digging in the source to understand it (and I don't claim to): typedef wchar_t ucs4_t; std::locale old_locale; std::locale utf8_locale(old_locale,new utf8_codecvt_facet<ucs4_t>); ... std::wifstream input_file("data.utf8"); input_file.imbue(utf8_locale); ucs4_t item = 0; while (ifs >> item) { ... } To understand more about locales, and how they use facets (including codecvt), take a look at the following: Nathan Myers has a thorough explanation of locales and facets. Myers was one of the designers of the locale concept. He has more formal documentation if you want to wade through it. Apache's Standard Library implementation (formerly RogueWave's) has a full list of facets. Nicolai Josuttis' The C++ Standard Library Chapter 14 is devoted to the subject. Angelika Langer and Klaus Kreft's Standard C++ IOStreams and Locales devotes a whole book.
1,274,912
1,274,978
Base-to-derived class typecast
I have a base class: class RedBlackTreeNode { // Interface is the same as the implementation public: RedBlackTreeNode* left; RedBlackTreeNode* right; RedBlackTreeNode* parent; Color color; TreeNodeData* data; RedBlackTreeNode(): left(0), right(0), parent(0), color(Black), data(0) { } // This method is to allow dynamic_cast virtual void foo() { } }; and a derived from it one: class IndIntRBNode : public RedBlackTreeNode { public: IndIntRBNode* left; IndIntRBNode* right; IndIntRBNode* parent; IndexedInteger* data; IndIntRBNode(): RedBlackTreeNode(), left(0), right(0), parent(0), color(Black), data(0) { } }; root() and rootHolder are defined in RedBlackTree class: class RedBlackTree { public: RedBlackTreeNode rootHolder; RedBlackTreeNode* root() { return rootHolder.left; } ... } Then I'm trying to typecast: IndIntRBNode *x, *y, *z; z = dynamic_cast<IndIntRBNode*>(root()); And "z" just becomes a zero-pointer, which means that typecast failed. So what's wrong with it, how can I fix it to be able to reference "z" as pointer to the IndIntRBNode? Added: the initialization of the rootHolder.left was some kind of that: int n = atoi(line + i); tree.clear(); int j = 0; if (n > 100) { n = 100; // Maximum 100 nodes } while (j < n) { IndexedInteger num(j,j + 10); RedBlackTreeNode* node; int c = tree.search(&num, tree.root(), &node); if (c != 0) { // if value is not in the tree IndexedInteger* v = new IndexedInteger(num); tree.insert(node, v, c); ++j; } } In the other words, it was initialized on the first iteration of "while" by the "insert" method in such way: void RedBlackTree::insert( RedBlackTreeNode* parentNode, TreeNodeData* v, // If it's negative, then add as the left son, else as the right int compare ) { assert(parentNode != 0 && compare != 0); RedBlackTreeNode* x = new RedBlackTreeNode; x->data = v; x->parent = parentNode; // If it's root if (parentNode == &rootHolder) { // Then it must be black x->color = Black; } else { // Leaf must be red x->color = Red; } if (compare < 0) { // Insert the node as the left son assert(parentNode->left == NULL); parentNode->left = x; } else { // Insert the node as the right son assert(parentNode != &rootHolder && parentNode->right == NULL); parentNode->right = x; } ++numNodes; if (x != root()) { rebalanceAfterInsert(x); } } It actually was the problem: "insert" created the RedBlackTreeNode dinamically, so it couldn't be IndIntRBNode. I really have initialized it wrong, but then how can I derive the base class and not write the whole implementation of it from a scratch just to change the types? Do I really have to override all the "type-relative" methods in the derived class? It seems to be very stupid, I think there should be the other way - something with class deriving and typecasting, isn't it?
Are you sure that RedBlackTree::rootHolder.left has been initialized? I think you somewhere initialized IndIntRBNode::left, but when you are accessing RedBlackTree::rootHolder.left you are accessing RedBlackTreeNode::left, which is not the same field.
1,275,864
1,275,869
Is there any cool project written in STL?
I want to learn STL by quick browsing of real project source. Where can I find a high quality project that uses STL?
Notepad++: pure Win32 + STL only! Based on a powerful editing component Scintilla, Notepad++ is written in C++ and uses pure Win32 API and STL which ensures a higher execution speed and smaller program size. By optimizing as many routines as possible without losing user friendliness, Notepad++ is trying to reduce the world carbon dioxide emissions. When using less CPU power, the PC can throttle down and reduce power consumption, resulting in a greener environment.
1,276,020
1,276,993
Skipping a C++ template parameter
A C++ hash_map has the following template parameters: template<typename Key, typename T, typename HashCompare, typename Allocator> How can I specify a Allocator without specifying the HashCompare? This won't compile :( hash_map<EntityId, Entity*, , tbb::scalable_allocator>
There's one trick you can use which will at least save you having to work out what the default is, but it does require that you know the name of the type as it is defined in hash_map. The hash_map will probably be declared something like: class allocator {}; class hash_compare {}; template<typename Key , typename T , typename HashCompare = hash_compare , typename Allocator = allocator> class hash_map { public: typedef HashCompare key_compare; // ... }; We cannot leave out the default for the hash, but we can refer to the default using the member typedef: hash_map<EntityId , Entity* , hash_map<EntityId,Entity*>::key_compare // find out the default hasher , tbb::scalable_allocator> hm; If you're going to use the type a lot, then create a typedef: typedef hash_map<EntityId,Entity*>::key_compare EntityKeyCompare; hash_map<EntityId , Entity* , EntityKeyCompare , tbb::scalable_allocator> hm;
1,276,339
1,276,358
Operator templates in C++
If I want to create a function template, where the template parameter isn't used in the argument list, I can do it thusly: template<T> T myFunction() { //return some T } But the invocation must specify the 'T' to use, as the compiler doesn't know how to work it out. myFunction<int>(); But, suppose I wanted to do something similar, but for the '[]' operator. template T SomeObject::operator [ unsigned int ] { //Return some T } Is there any way to invoke this operator? This doesn't appear valid: SomeObject a; a<int>[3];
This should work: class C { public: template <class T> T operator[](int n) { return T(); } }; void foo() { C c; int x = c.operator[]<int>(0); } But it's of no real value because you'd always have to specify the type, and so it looks like a very ugly function call - the point of an operator overload is to look like an operator invocation.
1,276,687
1,276,861
How can I find out the current color depth of a machine running vista/w7?
I want to check the current color depth of the OS to warn users if they try to run my application with a "wrong" color depth (using c++ & Qt). I guess there's a win api call to get this information, but I couldn't find anything.
On Windows you could use GetDeviceCaps with the BITSPIXEL flag but you'll need a screen DC first (GetDC could fetch you one). HDC dc = GetDC(NULL); int bitsPerPixel = GetDeviceCaps(dc, BITSPIXEL); ReleaseDC(NULL, dc);