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
174,449
174,728
To STL or !STL, that is the question
Unquestionably, I would choose to use the STL for most C++ programming projects. The question was presented to me recently however, "Are there any cases where you wouldn't use the STL?"... The more I thought about it, the more I realized that perhaps there SHOULD be cases where I choose not to use the STL... For example, a really large, long term project whose codebase is expected to last years... Perhaps a custom container solution that precisely fits the projects needs is worth the initial overhead? What do you think, are there any cases where you would choose NOT to STL?
Projects with strict memory requirements such as for embedded systems may not be suited for the STL, as it can be difficult to control and manage what's taken from and returned to the heap. As Evan mentioned, writing proper allocators can help with this, but if you're counting every byte used or concerned with memory fragmentation, it may be wiser to hand-roll a solution that's tailored for your specific problem, as the STL has been optimized for the most general usage. You may also choose not to use STL for a particular case because more applicable containers exist that are not in the current standard, such as boost::array or boost::unordered_map.
175,100
175,325
C++ thread/process identifier
Is there a portable way of getting thread and/or process identifier (string, int, ...) with C++?
There is no portable way when portable means a way that works on every platform for that a C++ compiler exists. Such a way had to be part of the C++ standard, in which case it really would work everywhere (just like the other parts of the C++ standard work everywhere). Everything not in the standard is not guaranteed to work on any platform, unless the platform states to support this standard. Every solution people have suggested here is a solution that uses an external library and thus can only work on platforms supported by that library; and no library is available for every existing platform. Probably the one that will get you farthest is POSIX, after all every UNIX like system tries to support at least some POSIX (the more the better), very little can call themselves really being 100% POSIX-compliant platforms (e.g. A/UX, AIX, HP-UX, IRIX, Mac OS X 10.5, MINIX, QNX, Solaris, UnixWare, VxWorks, ... to name a few, there are more of course). However, there are quite a couple of platforms that offer at least some POSIX support, some more, some less and some are almost POSIX-compliant (e.g. FreeBSD, Linux, NetBSD, BeOS, OpenBSD, ... and others). Windows is unfortunately far away from being one. NT used to be partly POSIX conform, but now it has more or less vanished (Win2000/20003, WinXP, and Vista can still be set into a POSIX emulating mode, translating some POSIX call to internal API calls by installing Microsoft Windows Services for UNIX - SFU 3.5 or higher), however there are ways to get some POSIX functionality on Windows through external libraries as well (Cygwin offers LGPL libraries you can link with your app to enable a fair amount of POSIX functions on Windows). The advantage of POSIX is not only that it is relatively widespread, but also that it is standardized and you can easily look up the standard on the Internet. Using POSIX calls you can get a thread id and a process id.
175,228
175,243
Which is more appropriate: getters and setters or functions?
Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious? For example, imagine I have this class in C++: public class SomeClass { private: bool mIsVisible; public: void draw(); void erase(); } I could add functions to get/set "mIsVisible" like this: bool getVisible() { return mIsVisible; }; void setVisible(bool visible) { if (!mIsVisible && visible) { draw(); } else if (mIsVisible && !visible) { erase(); } mIsVisible = visible; } However, it would be equally possible to use the following methods instead: bool isVisible() { return mIsVisible; }; void show() { if (!mIsVisible) { mIsVisible = true; draw(); } } void hide() { if (mIsVisible) { mIsVisible = false; erase(); } } In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?
Have a read of the article "Tell, Don't Ask" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go. Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely: get current visibility value, make decision based on value, update object.
175,689
175,926
Can you use keyword explicit to prevent automatic conversion of method parameters?
I know you can use C++ keyword 'explicit' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method? I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function with an int, the compiler converted the param to a bool and called the wrong method. I know eventually I'll replace the bool, but for now don't want to break the other routines as this new routine is developed.
No, you can't use explicit, but you can use a templated function to catch the incorrect parameter types. With C++11, you can declare the templated function as deleted. Here is a simple example: #include <iostream> struct Thing { void Foo(int value) { std::cout << "Foo: value" << std::endl; } template <typename T> void Foo(T value) = delete; }; This gives the following error message if you try to call Thing::Foo with a size_t parameter: error: use of deleted function ‘void Thing::Foo(T) [with T = long unsigned int]’ In pre-C++11 code, it can be accomplished using an undefined private function instead. class ClassThatOnlyTakesBoolsAndUIntsAsArguments { public: // Assume definitions for these exist elsewhere void Method(bool arg1); void Method(unsigned int arg1); // Below just an example showing how to do the same thing with more arguments void MethodWithMoreParms(bool arg1, SomeType& arg2); void MethodWithMoreParms(unsigned int arg1, SomeType& arg2); private: // You can leave these undefined template<typename T> void Method(T arg1); // Below just an example showing how to do the same thing with more arguments template<typename T> void MethodWithMoreParms(T arg1, SomeType& arg2); }; The disadvantage is that the code and the error message are less clear in this case, so the C++11 option should be selected whenever available. Repeat this pattern for every method that takes the bool or unsigned int. Do not provide an implementation for the templatized version of the method. This will force the user to always explicitly call the bool or unsigned int version. Any attempt to call Method with a type other than bool or unsigned int will fail to compile because the member is private, subject to the standard exceptions to visibility rules, of course (friend, internal calls, etc.). If something that does have access calls the private method, you will get a linker error.
176,062
176,091
How do I disable and then enable the Retry button in a MessageBox?
I have the following unmanaged C++ code: MessageBox( NULL, strMessage, "Cool Product", MB_RETRYCANCEL | MB_ICONEXCLAMATION); I want to disable the RETRY button for 10 seconds (for example), then enable it. How can I do this?
Like @ffpf says, you need to make your own dialog to do this, using MFC, ATL, raw Win32, etc. Then create a timer that would enable and disable the button.
176,158
176,173
STL non-copying wrapper around an existing array?
Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements? For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find_if, count_if, or sort directly on this array. Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.
You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,: int ary[100]; // init ... std::sort(ary, ary+100); // sorts the array std::find(ary, ary+100, pred); find some element I think you'll find that most stuff works just as you would expect.
176,376
176,395
With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key?
Suppose I have a set of values, stored in a std::set: {1, 2, 6, 8} and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6. The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case?
Yes: upper_bound(X) returns an iterator pointing to the first element greater than X. There is also a lower_bound(X) function which returns an iterator pointing to the first element not less than X. Thus, all of the elements in the half-open interval [lower_bound(X), upper_bound(X)) will be equal to X.
176,459
176,509
C++ SQLBindParameter
Here are the declarations of the variables: string strFirstName; string strLastName; string strAddress; string strCity; string strState; double dblSalary; string strGender; int intAge; ...Do some "cin" statements to get data... retcode = SQLPrepare(StatementHandle, (SQLCHAR *)"INSERT INTO EMPLOYEE ([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES (?,?,?,?,?,?,?,?)", SQL_NTS); retcode = SQLBindParameter(StatementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0 &strFirstName,0, NULL); retcode = SQLBindParameter(StatementHandle, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0, &strLastName,0, NULL); retcode = SQLBindParameter(StatementHandle, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 30, 0, &strAddress,0, NULL); retcode = SQLBindParameter(StatementHandle, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 30, 0, &strCity,0, NULL); retcode = SQLBindParameter(StatementHandle, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 3, 0, &strState,0, NULL); retcode = SQLBindParameter(StatementHandle, 6, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_DOUBLE, 0, 0, &dblSalary,0, NULL); retcode = SQLBindParameter(StatementHandle, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 2, 0, &strGender,0, NULL); retcode = SQLBindParameter(StatementHandle, 8, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &intAge,0, NULL); retcode = SQLExecute(StatementHandle); The int and double work fine and get stored in the table...but I can't figure out how to get the strings to store...
MSDN documentation for SQLBindParameter says you are meant to pass a buffer containing the data for ParameterValuePtr and the length of the buffer in bytes for BufferLength: retcode = SQLBindParameter(StatementHandle, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 50, 0, strFirstName.c_str(), strFirstName.length(), NULL); ParameterValuePtr [Deferred Input] A pointer to a buffer for the parameter's data. For more information, see "ParameterValuePtr Argument" in "Comments." BufferLength [Input/Output] Length of the ParameterValuePtr buffer in bytes. For more information, see "BufferLength Argument" in "Comments."
176,559
176,728
"You can't forward declare classes that overload operator&"?
In the Google C++ Style Guide, there's a section on Operator Overloading that has a curious statement: Overloading also has surprising ramifications. For instance, you can't forward declare classes that overload operator&. This seems incorrect, and I haven't been able to find any code that causes GCC to have a problem with it. Does anyone know what that statement is referring to?
5.3.1 of the Standard has "The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator&() as a member function, then the behavior is undefined (and no diagnostic is required)." I didn't know this either, but as another poster has pointed out, it's easy to see how it could cause a compiler to generate incorrect code.
176,989
177,007
Do you use NULL or 0 (zero) for pointers in C++?
In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0. You could not assign NULL to any pointer other than void*, which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers. To this day, I have continued to use zero as a null pointer but those around me insist on using NULL. I personally do not see any benefit to giving a name (NULL) to an existing value - and since I also like to test pointers as truth values: if (p && !q) do_something(); then using zero makes more sense (as in if you use NULL, you cannot logically use p && !q - you need to explicitly compare against NULL, unless you assume NULL is zero, in which case why use NULL). Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference? Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.
Here's Stroustrup's take on this: C++ Style and Technique FAQ In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days. If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, nullptr will be a keyword. That said, don't sweat the small stuff.
177,037
177,044
C++ Convert SQLVARCHAR to string
I need to convert from a SQLVARCHAR to a string data type Variable definitions as follows: string strFirstName; SQLVARCHAR rtnFirstName[50]; Want to be able to accomplish the following: if (strFirstName.empty()) strFirstName = rtnFirstName; Gives an error that the binary '=': no operator found which takes a right-hand operand of type 'SQLVARCHAR[50]' (or there is no acceptable conversion)
What database API are you using? All the Google hits I can find for SQLVARCHAR say it's an unsigned char, so you can do something like this: strFirstName = reinterpret_cast<char*>(rtnFirstName);
177,363
177,367
Hash of a string to be of specific length
Is there a way to generate a hash of a string so that the hash itself would be of specific length? I've got a function that generates 41-byte hashes (SHA-1), but I need it to be 33-bytes max (because of certain hardware limitations). If I truncate the 41-byte hash to 33, I'd probably (certainly!) lost the uniqueness. Or actually I suppose an MD5 algorithm would fit nicely, if I could find some C code for one with your help. EDIT: Thank you all for the quick and knowledgeable responses. I've chosen to go with an MD5 hash and it fits fine for my purpose. The uniqueness is an important issue, but I don't expect the number of those hashes to be very large at any given time - these hashes represent software servers on a home LAN, so at max there would be 5, maybe 10 running.
The way hashes are calculated that's unfortunately not possible. To limit the hash length to 33 bytes, you will have to cut it. You could xor the first and last 33 bytes, as that might keep more of the information. But even with 33 bytes you don't have that big a chance of a collision. md5: http://www.md5hashing.com/c++/ btw. md5 is 16 bytes, sha1 20 bytes and sha256 is 32 bytes, however as hexstrings, they all double in size. If you can store bytes, you can even use sha256.
177,437
177,451
What does 'const static' mean in C and C++?
const static int foo = 42; I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant foo from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it private?
It has uses in both C and C++. As you guessed, the static part limits its scope to that compilation unit. It also provides for static initialization. const just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only. All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const on there will warn you if any code would try to modify that. If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).
177,464
177,487
How to apply the MVC pattern to GUI development
I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly. My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?
If I was you I would expose events from an interface of your view. This would allow you to make the controller central to the entire interaction. The controller would load first and instantiate the view, I would use dependency injection so that you don't create a dependency on the view itself but only on the interface. The controller would access the model and load data into the view. The controller would bind to events defined on the view interface. The controller would then handle saving of data back to the model via an event. If you wanted to you could also use an event broker which would void the need to declare an interface per view. This way you could bind to events through attributes. This would leave you with the Controller being dependent on the model and the view interface, the view being dependent on the data only and the model having no dependencies. Some examples of the above design thinking can be found in CAB and the Smart Client Software Factory Link To Smart Client. They use the MVP pattern but it could equally easily be applied to the MVC pattern.
177,468
177,557
Qt and no moc_*.cpp file
I'm developing a simple Qt 4 app and making my own dialog. I subclassed QDialog, inserted the Q_OBJECT macro in the class declaration block, and... I get [Linker error] undefined reference to `vtable for MyDialog' and there is no moc_MyDialog.cpp generated by the moc compiler. I am using Qt 4.1.3 on Windows XP and mingw. I followed the build process from the Qt-supplied build shell. I used qmake to create make files and compiled everything with a make command. I have other classes that subclass QPushButton and QObject respectively, but they compile OK. I can't find any differences between them and the broken one. There must be missing something in the broken class, but I'm unable to spot it.
The undefined reference to "vtable for MyDialog" is caused because there is no moc file. Most c++ compilers create the vtable definition in the object file containing the first virtual function. When subclassing a qt object and using the Q_OBJECT macro, this will be in the moc*.cpp file. Therefore, this error means that the moc file is missing. The possible problems I can think of are: The header file for the class MyDialog.h is not added to HEADERS in the qmake file. You ran qmake to generate the make file before adding the Q_OBJECT macro. This created a make file without the moc rules. This is easily fixed by simply running qmake again. Your dialog derives from more than one class and QDialog is not the first class that it derives from. For qmake to work correctly, the QObject derived base class needs to be the first class that is inherited from. If you are using Qt Creator, you might get this error if your previous deployment was failed due to some reason (like application already running). In that case, simply do a 'Clean Project' and then 'Rebuild Project' and then 'Run' to deploy.
177,559
180,715
Getting rid of the evil delay caused by ShellExecute
This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to solve or work around this? EDIT: And as the tags might indicate, this is on Win32 using C++.
Are you multithreaded? I've seen issues with opening files with ShellExecute. Not executables, but files associated an application - usually MS Office. Applications that used DDE to open their files did some of broadcast of a message to all threads in all (well, I don't know if it was all...) programs. Since I wasn't pumping messages in worker threads in my application I'd hang the shell (and the opening of the file) for some time. It eventually timed out waiting for me to process the message and the application would launch and open the file. I recall using PeekMessage in a loop to just remove messages in the queue for that worker thread. I always assumed there was a way to avoid this in another way, maybe create the thread differently as to never be the target of messages? Update It must have not just been any thread that was doing this but one servicing a window. Raymond (link 1) knows all (link 2). I bet either CoInitialize (single threaded apartment) or something in MFC created a hidden window for the thread.
177,640
177,646
Lock / Prevent edit of source files on Linux using C++
How can I programmatically lock/unlock, or otherwise prevent/enable editing, a source file on Linux using C++. I want to be able to lock source file so that if I open it in an editor it will not allow me to save back to the same source file. I am thinking of maybe changing the permissions to read-only (and change it back to read-write later): how do I do that from C++?
Try man fchmod: NAME chmod, fchmod - change permissions of a file SYNOPSIS #include <sys/types.h> #include <sys/stat.h> int chmod(const char *path, mode_t mode); int fchmod(int fildes, mode_t mode);
177,677
177,793
How to convert a number to a bytearray in bit endian order
I am trying to uncompress some data created in VB6 using the zlib API. I have read this is possible with the qUncompress function: http://doc.trolltech.com/4.4/qbytearray.html#qUncompress I have read the data in from QDataStream via readRawBytes into a char array, which I then converted to a QByteArray for decompression. I have the compressed length and the expected decompressed length but am not getting anything back from qUncompress. However I need to prepend the expected decompressed length in big endian format. Has anybody done this and have an example?
I haven't used VB6 in ages, so I hope this is approximately correct. I think that vb6 used () for array indexing. If I got anything wrong, please let me know. Looking at the qUncompress docs, you should have put your data in your QByteArray starting at byte 5 (I'm going to assume that you left the array index base set to 1 for this example). Let's say the array is named qArr, and the expected uncompressed size is Size. In a "big-endian" representation, the first byte is at the first address. qArr(1) = int(Size/(256*256*256)) qArr(2) = 255 And int(Size/256*256) qArr(3) = 255 And int(Size/256) qArr(4) = 255 And int(Size) Does that make sense? If you needed little endian, you could just reverse the order of the indexes (qArr(4) - qArr(1)) and leave the calculations the same.
178,173
181,012
Reading the Exchange server time via MAPI
I'd like to calculate the age of the messages in an Exchange mailbox to make sure they sit there for at least a minute before our program (C++, MAPI) processes them. This way the spam filter we use should have enough time to do its job. Because the time on the PC where our program runs might be different from the time used by the Exchange server, our program has to read the server time via MAPI. Is there an elegant solution to it? One way I can think of is to modify some Item and immediately read its PR_LAST_MODIFICATION_TIME, but I'd like to avoid that. Edit: Our program is a batch job that runs every 10 minutes and reads the journal mailbox.
I presume you are getting a MAPI event notification when the message arrives in the Exchange mailbox. I would suggest pushing these messages into a queue and waiting n seconds (e.g. 60s) before processing the message. Since the time is relative to the notification event there will be no issue with respect to clock drift between the computers. On start up of your application you would be forced to do this for existing messages again but I would not imagine that this would pose an issue.
178,265
179,225
What is the most hard to understand piece of C++ code you know?
Today at work we came across the following code (some of you might recognize it): #define GET_VAL( val, type ) \ { \ ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); \ val = ( *((type *&)(pIP))++ ); \ } Basically we have a byte array and a pointer. The macro returns a reference to a variable of type and advance the pointer to the end of that variable. It reminded me of the several times that I needed to "think like a parser" in order to understand C++ code. Do you know of other code examples that caused you to stop and read it several times till you managed to grasp what it was suppose to do?
The inverse square root implementation in Quake 3: float InvSqrt (float x){ float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x; } Update: How this works (thanks ryan_s)
178,326
178,443
Sizing an MFC Window
I have an MFC app which I have been working on for a few weeks now, I want to manually set the dimensions of the main frame when it is loaded, can someone give me a hand with this, specifically where to put the code as well? Thanks!
You can also set the size (with SetWindowPos()) from within CMainFrame::OnCreate(), or in the CWinApp-derived class' InitInstance. Look for the line that says pMainFrame->ShowWindow(), and call pMainFrame->SetWindowPos() before that line. That's where I always do it.
178,449
178,515
Getting selected members from multiselect list view ctrl
I have a list view control which at the moment only allows one item to be selected. I then read this via the following code: void CApp::OnNMClickList1(NMHDR *pNMHDR, LRESULT *pResult) { int nSelected = (m_List.GetSelectionMark()); ... However, now I want to make this list able to multiselect, GetSelectionMark() always returns one index. Can anyone help me recode this to return a list of selected indexes?
Use GetFirstSelectedItemPosition() to find first selected item, then GetNextSelectedItem() for the rest and you're done. :)
178,838
178,877
Dereferencing Variable Size Arrays in Structs
Structs seem like a useful way to parse a binary blob of data (ie a file or network packet). This is fine and dandy until you have variable size arrays in the blob. For instance: struct nodeheader{ int flags; int data_size; char data[]; }; This allows me to find the last data character: nodeheader b; cout << b.data[b.data_size-1]; Problem being, I want to have multiple variable length arrays: struct nodeheader{ int friend_size; int data_size; char data[]; char friend[]; }; I'm not manually allocating these structures. I have a file like so: char file_data[1024]; nodeheader* node = &(file_data[10]); As I'm trying to parse a binary file (more specifically a class file). I've written an implementation in Java (which was my class assignment), no I'm doing a personal version in C++ and was hoping to get away without having to write 100 lines of code. Any ideas? Thanks, Stefan
You cannot have multiple variable sized arrays. How should the compiler at compile time know where friend[] is located? The location of friend depends on the size of data[] and the size of data is unknown at compile time.
178,934
178,992
Iterators.. why use them?
In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g. for ( int i=0; i < vecVector.size(); i++ ) { .. } Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?
Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings. Genericity Iterators increase the genericity of your code. For example: typedef std::vector<int> Container ; void doSomething(Container & p_aC) { for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it) { int & i = *it ; // i is now a reference to the value iterated // do something with "i" } } Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code. Should you have used index-based code instead, it would have needed to be re-written. Access The iterator should be viewed like a kind of super pointer. It "points" to the value (or, in case of maps, to the pair of key/value). But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque). Algorithms Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here.
179,105
179,121
Why shouldn't you use references to smart pointers?
I recall reading somewhere that using references to smart pointers can cause memory corruption. Is this simply because of using the reference of the smart pointer after its been destroyed? Or does the reference counting get messed up? Thanks for clarifying
Assuming you are talking about shared_ptr here... Is this simply because of using the reference of the smart pointer after its been destroyed? This is a good answer. You may not know absolutely the lifetime of the pointer your reference refers too. To get around this, you'd want to look into boost::weak_ptr. It doesn't participate in reference counting. When you need to use it, it gives you a shared_ptr which goes away once your done with it. It will also let you know when the refered to pointer has been collected. From the weak_ptr documentation The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock. When the last shared_ptr to the object goes away and the object is deleted, the attempt to obtain a shared_ptr from the weak_ptr instances that refer to the deleted object will fail: the constructor will throw an exception of type boost::bad_weak_ptr, and weak_ptr::lock will return an empty shared_ptr. Note the method expired() will also tell you if your ptr is still around.
179,643
179,662
Optimize Frustum Culling
i am writing a game in C++ and have a level consisting of many seperate meshes, each with their own vertex buffer. i am using vmmlib ( brilliant free gl compat. vector/matrix library ) to create my frustum culler and testing it against the bounding sphere of every mesh in the level. sadly my level can consist of up to 800 meshes and iterating through all of them each frame is slow. what is the best way of optimizing the code so that i don't have to look at all of the meshes on every iteration? Bounding volumes inside the frustum?
Yes bounding object is the way to go, you should take care in choosing an adequate bounding volume, for example for meshes that move about the scene like bots and dont lie down a cylinder is the best volume, other are better represented by cubes (axis aligned or not). Then you create a quadtree or octree to hierarchically divide the mesh data. This works very well for outdoor frustrum culling. For indoors a BSP is the best way to go since you have lots of walls to partition your space. You should still volume bound your meshes that have more than 10 polygons.
179,653
179,694
How do I get the integer value of a char in C++?
I want to take the value stored in a 32 bit unsigned int, put it into four chars and then store the integer value of each of these chars in a string. I think the first part goes like this: char a = orig << 8; char b = orig << 8; char c = orig << 8; char d = orig << 8;
If you really want to extract the individual bytes first: unsigned char a = orig & 0xff; unsigned char b = (orig >> 8) & 0xff; unsigned char c = (orig >> 16) & 0xff; unsigned char d = (orig >> 24) & 0xff; Or: unsigned char *chars = (unsigned char *)(&orig); unsigned char a = chars[0]; unsigned char b = chars[1]; unsigned char c = chars[2]; unsigned char d = chars[3]; Or use a union of an unsigned long and four chars: union charSplitter { struct { unsigned char a, b, c, d; } charValues; unsigned int intValue; }; charSplitter splitter; splitter.intValue = orig; // splitter.charValues.a will give you first byte etc. Update: as friol pointed out, solutions 2 and 3 are not endianness-agnostic; which bytes a, b, c and d represent depend on the CPU architecture.
179,684
179,899
Is C++ CLI a superset of C++?
Would a C++ CLI compiler be able to compile some large sets of C++ classes without modifications? Is C++ CLI a superset of C++?
technically no, but depending how standard the C++ code is, you'll probably be just fine. when you get into windows stuff you may run into issues. I compiled the whole game engine we use at work in C++/CLI once and it worked just fine. A colleague did the same for all of mozilla and no such luck.
179,723
179,733
What is the best way of implementing assertion checking in C++?
By that I mean, what do I need to do to have useful assertions in my code? MFC is quite easy, i just use ASSERT(something). What's the non-MFC way? Edit: Is it possible to stop assert breaking in assert.c rather than than my file which called assert()? Edit: What's the difference between <assert.h> & <cassert>? Accepted Answer: Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).
#include <cassert> assert(something); and for compile-time checking, Boost's static asserts are pretty useful: #include <boost/static_assert.hpp> BOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit
179,735
180,753
What are some good resources on 2D game engine design?
I'm messing around with 2D game development using C++ and DirectX in my spare time. I'm finding that the enterprisey problem domain modeling approach doesn't help as much as I'd like ;) I'm more or less looking for a "best practices" equivalent to basic game engine design. How entities should interact with each other, how animations and sounds should be represented in an ideal world, and so on. Anyone have good resources they can recommend?
Gamedev.net is usually where I turn to get an idea of what other people in the game development community are doing. That said, I'm afraid that you'll find that the idea of "best practices" in game development is more volatile than most. Games tend to be such specialized applications that it's near impossible to give any "one size fits all" answers. What works great for Tetris is going to be useless with Asteroids, and a model that works perfectly for Halo is likely to fail miserably for Mario. You'll also find quickly that there's no such thing as an "industry standard" for texture, mesh, level, sound, or animation formats. Everyone just rolls their own or uses whatever is convenient to the platform. You do occasionally see things like COLLADA, which is nice, but it's still just an intermediate format designed to make writing exporters easier. If you're new to game development, my advice would be this: Don't kill yourself over your code structure on your first go. Try a simple game, like asteroids, and just hack away until it works, no matter how "ugly" the code is. Use simple formats that you are familiar with without worrying about how well they'll hold up in larger projects. Don't worry about plugins, skins, editors, or any of that other fluff. Just make it WORK! Then, when you're done with that first, all important game, pick another, and this time around clean up one or two aspects of your code (but don't go overboard!) From there, iterate! I promise you that this will get you farther faster than any amount of poking around online for the "right way" ever could (this coming from someone who's done a LOT of poking). And one last thought for you: If you feel more comfortable working in a more well defined space, take a look at XNA or a similar library. They'll pre-define some of the "best" formats to use and give you tools to work with them, which takes some of the initial guesswork out. Good luck, and above all else remember: Games (and their development) are supposed to be FUN! Don't get too caught up on the small stuff!
179,907
179,926
How do I work with Multiple Recordsets in C++ ODBC
I am trying to streamline a complex process of storing information in multiple tables and them linking them to a central table. The linking occurs using IDENTITY values generated in each table to provide the unique linking. I know I can use a combination of SET NOCOUNT ON and SELECT @@identity to get each identity, but that still requires me to call a separate SQLExecute() for each table. I have read dozens of articles saying ADO can handle multiple recordsets using an ODBC driver, so the question is how do I do it without ADO? I have already encapsulated all of the standard ODBC stuff for similar behavior to ADO. I basically just need to know what ODBC API calls will allow me to recreate ADO's NextRecorset(). I am working on a combination of MS SQL 7 and MS SQL 2005, using either the SQL Server ODBC, or SQL Native Client Drivers as appropriate. End Goal: SET NOCOUNT ON; INSERT INTO TableA (data) VALUES ('a'); SELECT @@identity AS NewID; INSERT INTO TableB (data) VALUES ('b'); SELECT @@identity AS NewID; INSERT INTO TableC (data) VALUES ('c'); SELECT @@identity AS NewID; ... RS = DB.OpenRecordset() RS.MoveFirst() A_ID = RS.GetValue("id") RS.NextRecordset() RS.MoveFirst() B_ID = RS.GetValue("id") RS.NextRecordset() RS.MoveFirst() C_ID = RS.GetValue("id")
Use the SQLMoreResults() call as the analog to the NextRecordSet() function. However you probably don't need that if you are willing to make your executes consist of INSERT ...; SELECT @@IDENTITY Since the only result returned from this statement is the identity, you don't need to bother with the SQLMoreResults().
180,172
181,463
Default constructor with empty brackets
Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++? MyObject object; // ok - default ctor MyObject object(blah); // ok MyObject object(); // error I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?
Most vexing parse This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration. Another instance of the same problem: std::ifstream ifs("file.txt"); std::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>()); v is interpreted as a declaration of function with 2 parameters. The workaround is to add another pair of parentheses: std::vector<T> v((std::istream_iterator<T>(ifs)), std::istream_iterator<T>()); Or, if you have C++11 and list-initialization (also known as uniform initialization) available: std::vector<T> v{std::istream_iterator<T>{ifs}, std::istream_iterator<T>{}}; With this, there is no way it could be interpreted as a function declaration.
180,277
184,228
Change Windows Mobile 6.1 Theme Programmatically
I am trying to figure out the proper procedure for applying a new tsk based theme file in windows mobile 6.1. I have tried working off of the page http://www.pocketpcdn.com/articles/changetodaytheme.html But this only changes the background, not the system colors for things such as the top and bottom bars on the screen. wceload.exe seems to work perfectly for some tsk's and partially for others. Does anyone know more about tsk files and applying them programmatically in Windows Mobile 6.1? My application is an open source application, the code is avail;able via read only svn, feel free to check it out @ google code
I ended up finding a solution, I don't think it is a universal solution though. Calling "\Windows\cusTSK.exe \Windows\ThemeName.tsk" changes the top and bottom bars, but does not change all apsects of the theme... so calling wceload.exe and then calling cuTSK.exe in that order seems to be able to change the theme using all tsk files that I have tested. The cusTSK.exe binary does not exist on the Windows Mobile 6.1 Professional emulator image that you can download from msdn, so I think that this file that exists on custom roms and HTC made devices, that is why I do not think this is a universal solution, but it works for my purposes
180,327
180,845
Equation Solvers for linear mathematical equations
I need to solve a few mathematical equations in my application. Here's a typical example of such an equation: a + b * c - d / e = a Additional rules: b % 10 = 0 b >= 0 b <= 100 Each number must be integer ... I would like to get the possible solution sets for a, b, c, d and e. Are there any libraries out there, either open source or commercial, which I can use to solve such an equation? If yes, what kind of result do they provide?
Solving linear systems can generally be solved using linear programming. I'd recommend taking a look at Boost uBLAS for starters - it has a simple triangular solver. Then you might checkout libraries targeting more domain specific approaches, perhaps QSopt.
180,358
193,869
Delphi versus C++ Builder - Which is Better Choice for a Java Programmer Doing Win32
I'm a pretty experienced Java programmer that's been doing quite a bit of Win32 stuff in the last couple of years. Mainly I've been using VB6, but I really need to move to something better. I've spent a month or so playing with Delphi 2009. I like the VCL GUI stuff, Delphi seems more suited to Windows API calls than VB6, I really like the fact that it's much better at OO than VB6, and I like the unit-testing framework that comes with the IDE. But I really struggle with the fact that there's no widely-used garbage collector for Delphi - having to free every object manually or use interfaces for everything seems to have a pretty big impact on the way that you can do things effectively in an object oriented way. Also I'm not particularly keen on the syntax, or the fact that you have to declare variables all at the top of a method. I can handle Delphi, but I'm wondering if C++ Builder 2009 might be a better choice for me. I know very little about C++ Builder and C++, but then I know very little about Delphi either. I know there's a lot to the C++ language, but I suspect it's only necessary to know a subset of it to get things done productively... I have heard that the C++ of today is a lot more productive to program in than the C++ of 10 years ago. I'll be doing new development only so I wouldn't need to master every aspect of the C++ language - if I can find an equivalent for each of Java's language features I'll be happy enough, and as I progress I could start looking at the more advanced stuff a bit more. (Sorry if that sounds painfully naive - if so please set me straight!) So, for a Java programmer that's new to both Delphi and C++ Builder, which would you consider to be a better choice for productive development of Win32 exes and dlls, and why? What do you see to be the pros and cons of each?
Delphi or C++ Builder - it's a difficult choice! As you're aware, they're basically very similar, from the IDE and RAD point of view. The pros and cons of each - irrespective of background - are a bit like this. Both share a great 2-way RAD form designer and framework (VCL) that are ideal for native Windows development. Delphi: FOR: Large, active, enthusiastic community FOR: Delphi 2009 is the best version for many years FOR: Delphi "units" make C source/header file pairs seem archaic AGAINST: No automatic destruction as objects leave scope, hence lots of 'finally's in your code AGAINST: Language can be 'wordy', which is a matter of taste AGAINST: Using third-party DLL's or libraries in other languages (esp. C) requires Delphi header files to be written C++Builder FOR: C++Builder 2009 is probably the best version ever FOR: RAII idiom simplifies memory management hugely FOR: Templates are incredibly useful and powerful, even if the C++Builder implementation has some bugs with them. FOR: Support for BOOST and other modern template-based libraries (even though the Boost support is not 100%) FOR: Great interop with Delphi means most Delphi components can easily be used. FOR: Easy to use with third-part DLLs/libraries with C/C++ headers. FOR: C++ may look better on a CV than Delphi. AGAINST: CB2009 is "unicode only" - the implications of this for code portability are different and less well thought-out than for Delphi AGAINST: C++Builder user-base is much smaller than Delphi. Maybe 20% or less. AGAINST: Borland/Inprise nearly killed BCB a few years ago, and it was only resurrected after major efforts from the community. (However, Codegear/Embarcadero commitment does seem impressive) AGAINST: C++Builder is not top of the pile within Codegear. AGAINST: Third-party component vendors don't always understand/support C++Builder That's about it. Just to state my position, I'm a happy BCB2007/2009 user (since BCB5), and I also infrequently use Delphi. A few years back, I considered a switch from C++ to Delphi, but the lack of RAII idiom was the one thing that I found difficult to come to terms with.
180,401
180,409
Placement of the asterisk in pointer declarations
I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition. How about these examples: int* test; int *test; int * test; int* test,test2; int *test,test2; int * test,test2; Now, to my understanding, the first three cases are all doing the same: Test is not an int, but a pointer to one. The second set of examples is a bit more tricky. In case 4, both test and test2 will be pointers to an int, whereas in case 5, only test is a pointer, whereas test2 is a "real" int. What about case 6? Same as case 5?
4, 5, and 6 are the same thing, only test is a pointer. If you want two pointers, you should use: int *test, *test2; Or, even better (to make everything clear): int* test; int* test2;
180,516
180,616
How to filter items from a std::map?
I have roughly the following code. Could this be made nicer or more efficient? Perhaps using std::remove_if? Can you remove items from the map while traversing it? Can we avoid using the temporary map? typedef std::map<Action, What> Actions; static Actions _actions; bool expired(const Actions::value_type &action) { return <something>; } void bar(const Actions::value_type &action) { // do some stuff } void foo() { // loop the actions finding expired items Actions actions; BOOST_FOREACH(Actions::value_type &action, _actions) { if (expired(action)) bar(action); else actions[action.first]=action.second; } } actions.swap(_actions); }
You could use erase(), but I don't know how BOOST_FOREACH will handle the invalidated iterator. The documentation for map::erase states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop: Actions::iterator it = _actions.begin(); while (it != _actions.end()) { if (expired(*it)) { bar(*it); Actions::iterator toerase = it; ++it; _actions.erase(toerase); } else ++it; }
180,601
180,633
Using "super" in C++
My style of coding includes the following idiom: class Derived : public Base { public : typedef Base super; // note that it could be hidden in // protected/private section, instead // Etc. } ; This enables me to use "super" as an alias to Base, for example, in constructors: Derived(int i, int j) : super(i), J(j) { } Or even when calling the method from the base class inside its overridden version: void Derived::foo() { super::foo() ; // ... And then, do something else } It can even be chained (I have still to find the use for that, though): class DerivedDerived : public Derived { public : typedef Derived super; // note that it could be hidden in // protected/private section, instead // Etc. } ; void DerivedDerived::bar() { super::bar() ; // will call Derived::bar super::super::bar ; // will call Base::bar // ... And then, do something else } Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated. The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword. So, my questions: is this use of typedef super common/rare/never seen in the code you work with? is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)? should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already? Edit: Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?). Edit 2: Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.
Bjarne Stroustrup mentions in Design and Evolution of C++ that super as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized. Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced. After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem. Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post. So, no, this will probably never get standardized. If you don't have a copy, Design and Evolution is well worth the cover price. Used copies can be had for about $10.
180,947
180,949
Base64 decode snippet in C++
Is there a freely available Base64 decoding code snippet in C++?
See Encoding and decoding base 64 with C++. Here is the implementation from that page: /* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger rene.nyffenegger@adp-gmbh.ch */ static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; }
181,037
191,269
Case-insensitive UTF-8 string collation for SQLite (C/C++)
I am looking for a method to compare and sort UTF-8 strings in C++ in a case-insensitive manner to use it in a custom collation function in SQLite. The method should ideally be locale-independent. However I won't be holding my breath, as far as I know, collation is very language-dependent, so anything that works on languages other than English will do, even if it means switching locales. Options include using standard C or C++ library or a small (suitable for embedded system) and non-GPL (suitable for a proprietary system) third-party library. What I have so far: strcoll with C locales and std::collate/std::collate_byname are case-sensitive. (Are there case-insensitive versions of these?) I tried to use a POSIX strcasecmp, but it seems to be not defined for locales other than "POSIX" In the POSIX locale, strcasecmp() and strncasecmp() do upper to lower conversions, then a byte comparison. The results are unspecified in other locales. And, indeed, the result of strcasecmp does not change between locales on Linux with GLIBC. #include <clocale> #include <cstdio> #include <cassert> #include <cstring> const static char *s1 = "Äaa"; const static char *s2 = "äaa"; int main() { printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); assert(setlocale(LC_ALL, "en_AU.UTF-8")); printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); assert(setlocale(LC_ALL, "fi_FI.UTF-8")); printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2)); printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2)); } This is printed: strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == -32 strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == 7 strcasecmp('Äaa', 'äaa') == -32 strcoll('Äaa', 'äaa') == 7 P. S. And yes, I am aware about ICU, but we can't use it on the embedded platform due to its enormous size.
What you really want is logically impossible. There is no locale-independent, case-insensitive way of sorting strings. The simple counter-example is "i" <> "I" ? The naive answer is no, but in Turkish these strings are unequal. "i" is uppercased to "İ" (U+130 Latin Capital I with dot above) UTF-8 strings add extra complexity to the question. They're perfectly valid multi-byte char* strings, if you have an appropriate locale. But neither the C nor the C++ standard defines such a locale; check with your vendor (too many embedded vendors, sorry, no genearl answer here). So you HAVE to pick a locale whose multi-byte encoding is UTF-8, for the mbscmp function to work. This of course influences the sort order, which is locale dependent. And if you have NO locale in which const char* is UTF-8, you can't use this trick at all. (As I understand it, Microsoft's CRT suffers from this. Their multi-byte code only handles characters up to 2 bytes; UTF-8 needs 3) wchar_t is not the standard solution either. It supposedly is so wide that you don't have to deal with multi-byte encodings, but your collation will still depend on locale (LC_COLLATE) . However, using wchar_t means you now choose locales that do not use UTF-8 for const char*. With this done, you can basically write your own ordering by converting strings to lowercase and comparing them. It's not perfect. Do you expect L"ß" == L"ss" ? They're not even the same length. Yet, for a German you have to consider them equal. Can you live with that?
181,050
181,058
Can you allocate a very large single chunk of memory ( > 4GB ) in c or c++?
With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them? Why??? I'm working on processing some openstreetmap xml data and these files are huge. I'm currently streaming them in since I can't load them all in one chunk but I just got curious about the upper limits on malloc or new.
Short answer: Not likely In order for this to work, you absolutely would have to use a 64-bit processor. Secondly, it would depend on the Operating System support for allocating more than 4G of RAM to a single process. In theory, it would be possible, but you would have to read the documentation for the memory allocator. You would also be more susceptible to memory fragmentation issues. There is good information on Windows memory management.
181,064
202,877
EnumDisplayDevices vs WMI Win32_DesktopMonitor, how to detect active monitors?
For my current C++ project I need to detect a unique string for every monitor that is connected and active on a large number of computers. Research has pointed to 2 options Use WMI and query the Win32_DesktopMonitor for all active monitors. Use the PNPDeviceID for unique identification of monitors. Use the EnumDisplayDevices API, and dig down to get the device ID. I'm interested in using the device id for unique model identification because monitors using the default plug and play driver will report a generic string as the monitor name "default plug and play monitor" I have been experiencing issues with the WMI method, it seems to be only returning 1 monitor on my Vista machine, looking at the doco it turns out it does not work as expected on non WDDM devices. The EnumDisplayDevices seems to be a little problematic to get going when it runs from a background service (especially on Vista), If it's in session 0 it will return no info. Has anyone else had to do something similar (find unique model string for all connected active monitors?) What approach worked best?
This is my current work-in-progress code for detecting the monitor device id, reliably. CString DeviceID; DISPLAY_DEVICE dd; dd.cb = sizeof(dd); DWORD dev = 0; // device index int id = 1; // monitor number, as used by Display Properties > Settings while (EnumDisplayDevices(0, dev, &dd, 0)) { DISPLAY_DEVICE ddMon; ZeroMemory(&ddMon, sizeof(ddMon)); ddMon.cb = sizeof(ddMon); DWORD devMon = 0; while (EnumDisplayDevices(dd.DeviceName, devMon, &ddMon, 0)) { if (ddMon.StateFlags & DISPLAY_DEVICE_ACTIVE && !(ddMon.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)) { DeviceID.Format (L"%s", ddMon.DeviceID); DeviceID = DeviceID.Mid (8, DeviceID.Find (L"\\", 9) - 8); } devMon++; ZeroMemory(&ddMon, sizeof(ddMon)); ddMon.cb = sizeof(ddMon); } ZeroMemory(&dd, sizeof(dd)); dd.cb = sizeof(dd); dev++; }
181,213
181,224
How to build a solution to target 64 bit environment?
Is there anyway to build a solution to target 64 bit environment in vs2003? My solution is native c++ not visual c++. Any help would be greatly appreciated. cheers, RWendi
This page on 2003's lack of 64-bit targeting seems to address your issue: http://www.toymaker.info/Games/html/64_bit.html. The first step was to set up my development environment for 64 bit development. I use Visual Studio 2003 which has little built in support for 64 bit development. In order to create 64 bit applications you need to install the latest Platform SDK from Microsoft (Microsoft Platform SDK for Windows Server 2003). The SDK, as well as having libraries for 32 bit programming, has 64 bit versions for AMD64 and IA64 (Intel) development. Getting the correct library and header file paths set up in Visual Studio proved surprisingly difficult. I wanted the choice of developing 32 bit or 64 bit projects. While the platform SDK comes with command files to set up the correct paths they wipe out any other paths. Since T2 uses DirectX I also needed the DirectX paths setting correctly. Upgrading to a newer edition of Visual Studio looks like the safer, non-hackish solution, if possible.
181,624
186,026
C++: what regex library should I use?
I'm working on a commercial (not open source) C++ project that runs on a linux-based system. I need to do some regex within the C++ code. (I know: I now have 2 problems.) QUESTION: What libraries do people who regularly do regex from C/C++ recommend I look into? A quick search has brought the following to my attention: 1) Boost.Regex (I need to go read the Boost Software License, but this question is not about software licenses) 2) C (not C++) POSIX regex (#include <regex.h>, regcomp, regexec, etc.) 3) http://freshmeat.net/projects/cpp_regex/ (I know nothing about this one; seems to be GPL, therefore not usable on this project)
Thanks for all the suggestions. I tried out a few things today, and with the stuff we're trying to do, I opted for the simplest solution where I don't have to download any other 3rd-party library. In the end, I #include <regex.h> and used the standard C POSIX calls regcomp() and regexec(). Not C++, but in a pinch this proved to be the easiest.
181,629
181,666
How can I set the /baseaddress to a "good" value?
We have a project with many dll files which get loaded when the application starts. The baseaddresses of the dll files do overlap so that the memory image gets relocated. Is there a possibility to assign the baseaddresses automatically or a way to calculate a "good" baseaddress for each dll file?
You can use the REBASE utility which ships with the platform SDK and with Visual studio I think to set the base addresses of a whole bunch of DLLS loaded by the appliction You supply REBASE with a list of the DLLS that make up your program, not including system Dlls, it then performs a dummy load of all the DLLs and assigns them new base addresses. This can be performed as part of a final build step. There is a Dr Dobbs article on rebasing here and a Microsoft article on rebasing in general here
181,630
181,802
What's a good and stable C++ tree implementation?
I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is stl compatible if at all possible. For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the goal here. Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within. So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable.
I don't know about your requirements, but wouldn't you be better off with a graph (implementations for example in Boost Graph) if you're interested mostly in the structure and not so much in tree-specific benefits like speed through balancing? You can 'emulate' a tree through a graph, and maybe it'll be (conceptually) closer to what you're looking for.
181,693
26,395,804
What are the complexity guarantees of the standard containers?
Apparently ;-) the standard containers provide some form of guarantees. What type of guarantees and what exactly are the differences between the different types of container? Working from the SGI page (about STL) I have come up with this: Container Types: ================ Container: Forward Container Reverse Container Random Access Container Sequence Front Insert Sequence Back Insert Sequence Associative Container Simple Associative Container Pair Associative Container Sorted Associative Container Multiple Associative Container Container Types mapped to Standard Containers ============================================= std::vector: Sequence Back Sequence Forward/Reverse/Random Container std::deque: Sequence Front/Back Sequence Forward/Reverse/Random Container std::list: Sequence Front/Back Sequence Forward/Reverse Container std::set: Sorted/Simple/Unique Associative Container Forward Container std::map: Sorted/Pair/Unique Associative Container Forward Container std::multiset: Sorted/Simple/Multiple Associative Container Forward Container std::multimap: Sorted/Pair/Multiple Associative Container Forward Container Container Guarantees: ===================== Simp or For Rev Rand Front Back Assoc Sort Mult Cont: Cont: Cont Cont: Sequ: Sequ: Sequ: Cont: Cont: Cont: Copy Const: O(n) Fill Const: O(n) begin() O(1) end() O(1) rbegin() O(1) rend() O(1) front() O(1) push_front() O(1) pop_front() O(1) push_back() O(1) pop_back() O(1) Insert() O(ln(n)) Insert: fill O(n) Insert: range O(n) O(kln(n)+n) size() O(1) swap() O(1) erase key O(ln(n)) erase element O(1) erase range O(ln(n)+S) count() O(log(n)+k) find() O(ln(n)) equal range O(ln(n)) Lower Bound/Upper Bound O(ln(n)) Equality O(n) InEquality O(n) Element Access O(1)
I found the nice resource Standard C++ Containers. Probably this is what you all looking for. VECTOR Constructors vector<T> v; Make an empty vector. O(1) vector<T> v(n); Make a vector with N elements. O(n) vector<T> v(n, value); Make a vector with N elements, initialized to value. O(n) vector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n) Accessors v[i] Return (or set) the I'th element. O(1) v.at(i) Return (or set) the I'th element, with bounds checking. O(1) v.size() Return current number of elements. O(1) v.empty() Return true if vector is empty. O(1) v.begin() Return random access iterator to start. O(1) v.end() Return random access iterator to end. O(1) v.front() Return the first element. O(1) v.back() Return the last element. O(1) v.capacity() Return maximum number of elements. O(1) Modifiers v.push_back(value) Add value to end. O(1) (amortized) v.insert(iterator, value) Insert value at the position indexed by iterator. O(n) v.pop_back() Remove value from end. O(1) v.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n) v.erase(iterator) Erase value indexed by iterator. O(n) v.erase(begin, end) Erase the elements from begin to end. O(n) For other containers, refer to the page.
181,731
181,843
Texture Sampling in Open GL
i need to get the color at a particular coordinate from a texture. There are 2 ways i can do this, by getting and looking at the raw png data, or by sampling my generated opengl texture. Is it possible to sample an opengl texture to get the color (RGBA) at a given UV or XY coord? If so, how?
Off the top of my head, your options are Fetch the entire texture using glGetTexImage() and check the texel you're interested in. Draw the texel you're interested in (eg. by rendering a GL_POINTS primitive), then grab the pixel where you rendered it from the framebuffer by using glReadPixels. Keep a copy of the texture image handy and leave OpenGL out of it. Options 1 and 2 are horribly inefficient (although you could speed 2 up somewhat by using pixel-buffer-objects and doing the copy asynchronously). So my favourite by FAR is option 3. Edit: If you have the GL_APPLE_client_storage extension (ie. you're on a Mac or iPhone) then that's option 4 which is the winner by a long way.
182,278
316,838
Is there a way to simulate the C++ 'friend' concept in Java?
I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?
The 'friend' concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the 'Friend Accessor' pattern as detailed below: The class exposed through the API: package api; public final class Exposed { static { // Declare classes in the implementation package as 'friends' Accessor.setInstance(new AccessorImpl()); } // Only accessible by 'friend' classes. Exposed() { } // Only accessible by 'friend' classes. void sayHello() { System.out.println("Hello"); } static final class AccessorImpl extends Accessor { protected Exposed createExposed() { return new Exposed(); } protected void sayHello(Exposed exposed) { exposed.sayHello(); } } } The class providing the 'friend' functionality: package impl; public abstract class Accessor { private static Accessor instance; static Accessor getInstance() { Accessor a = instance; if (a != null) { return a; } return createInstance(); } private static Accessor createInstance() { try { Class.forName(Exposed.class.getName(), true, Exposed.class.getClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } return instance; } public static void setInstance(Accessor accessor) { if (instance != null) { throw new IllegalStateException( "Accessor instance already set"); } instance = accessor; } protected abstract Exposed createExposed(); protected abstract void sayHello(Exposed exposed); } Example access from a class in the 'friend' implementation package: package impl; public final class FriendlyAccessExample { public static void main(String[] args) { Accessor accessor = Accessor.getInstance(); Exposed exposed = accessor.createExposed(); accessor.sayHello(exposed); } }
182,408
182,456
Manual for cross-compiling a C++ application from Linux to Windows?
Is there a manual for cross-compiling a C++ application from Linux to Windows? Just that. I would like some information (links, reference, examples...) to guide me to do that. I don't even know if it's possible. My objective is to compile a program in Linux and get a .exe file that I can run under Windows.
The basics are not too difficult: sudo apt-get install mingw32 cat > main.c <<EOF int main() { printf("Hello, World!"); } EOF i586-mingw32msvc-cc main.c -o hello.exe Replace apt-get with yum, or whatever your Linux distro uses. That will generate a hello.exe for Windows. Once you get your head around that, you could use autotools, and set CC=i586-mingw32msvc-cc CC=i586-mingw32msvc-cc ./configure && make Or use CMake and a toolchain file to manage the build. More difficult still is adding native cross libraries. Usually they are stored in /usr/cross/i586-mingw32msvc/{include,lib} and you would need to add those paths in separately in the configure step of the build process.
182,739
182,798
Is it possible to enumerate the wxFrame children in wxWidgets?
I'm using the wxGlade designer to generate the GUI for a small application. It generates a class, inherited from wxFrame, which is the main application window. In order to facilitate the maintenance, I'd like to avoid writing additional code in this generated class. But all the widgets created with the wxGlade are actually created in the auto-generated method do_layout() and it is not possible to access them outside the scope of that generated method in the generated class. Is there a way to get pointer of certain widget outside that generated class - by name, by type, by enumerating the children or something like that?
All classes inherited from wxWindow (wxFrame being one of them) have a function "GetChildren", which returns a list of child windows that you can then enumerate over. If you are looking for a specific field by name then use the "FindWindow" function.
182,910
182,935
Determine highest .NET Framework version
I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code. Looks like I can iterate the folders under %systemroot%\Microsoft.NET\Framework, but that seems kind of error prone. Is there a better way? Perhaps a registry key I can inspect? Thanks.
Use the Windows Registry location HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP.
182,957
182,973
Position in Vector using STL
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here? int value = *min_element(v2.begin(), v2.end()); cout << "min value at position " << *find(v2.begin(), v2.end(), value);
min_element already gives you the iterator, no need to invoke find (additionally, it's inefficient because it's twice the work). Use distance or the - operator: cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
183,108
183,235
Is object code generated for unused template class methods?
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types. Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?
Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called. This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below) An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement (9.4.1), unless such instantiation is required Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example: template <class T> class Xyzzy { public: void CallFoo() { t.foo(); } // Invoke T::foo() void CallBar() { t.bar(); } // Invoke T::bar() private: T t; }; class FooBar { public: void foo() { ... } void bar() { ... } }; class BarOnly { public: void bar() { ... } }; int main(int argc, const char** argv) { Xyzzy<FooBar> foobar; // Xyzzy<FooBar> is instantiated Xyzzy<BarOnly> baronly; // Xyzzy<BarOnly> is instantiated foobar.CallFoo(); // Calls FooBar::foo() foobar.CallBar(); // Calls FooBar::bar() baronly.CallBar(); // Calls BarOnly::bar() return 0; } This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool. Note, however, that "instantiation" of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.
183,447
187,408
Any way to determine speed of a removable drive in windows?
Is there any way to determine a removable drive speed in Windows without actually reading in a file. And if I do have to read in a file, how much needs to be read to get a semi accurate speed (e.g. determine whether a device is USB2 or USB1)? EDIT: Just to clarify, USB2 and USB1 were an example. These could be Compact Flash, could be SSD, could be a removable drive. And I am trying to determine this as fast as possible as it has a real effect on the responsiveness of the application. EDIT: Should also clarify, this has to be done programatically. It will probably be done in C++. EDIT: Boost answer is kind of what I was looking for (though I haven't written any WMI in C++). But I need to know what properties I have to check to determine relative speed. I don't need exact speed (like I said about the difference in speed between USB1 and USB2), but I need to know if it is going to be SLLOOOOWWW.
WMI - Physical Disks Properties is an article I found which would at least help you figure out what you have connected. I foresee things heading toward tables equating particular manufacturers and models to speeds, which is not as simple a solution as you may have hoped for.
183,606
183,678
Comparison Functor Types vs. operator<
In the Google C++ Style Guide, the section on Operator Overloading recommends against overloading any operators ("except in rare, special circumstances"). Specifically, it recommends: In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. I'm a little fuzzy on what such a functor would look like, but my main question is, why would you want to write your own functors for this? Wouldn't defining operator<, and using the standard std::less<T> function, be simpler? Is there any advantage to using one over the other?
Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation. Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes before who? You might just take the order in which the customers registered – in that case, the less-than operation would compare the check-in times. You might also consider the price customers paid for their tickets – less-than would now compare ticket prices. … and so on. All in all, it's just not meaningful to define an operator < on the Passenger class although it may be required to have passengers in a sorted container. I think that's what Google warns against.
183,788
183,805
C / C++ compiler warnings: do you clean up all your code to remove them or leave them in?
I've worked on many projects where I've been given code by others to update. More often than not I compile it and get about 1,000+ compiler warnings. When I see compiler warnings they make me feel dirty, so my first task is to clean up the code and remove them all. Typically I find about a dozen problems like uninitialized variables such. I don't understand why people leave them in and don't have perfectly clean compiles with no warnings. Am I missing something? Is there any valid reason to just leave them? Any horror stories to share?
I would clean up any warning. Even the ones that you know are harmless (if such a thing exists) will give a bad impression of you to whoever will compile the code. It one of the "smelly" signs I would look for if I had to work on someone else code. If not real errors or potential future issues, it would be a sign of sloppiness
183,898
183,908
Forward Referencing or Declaration in C++
How do I do forward referencing / declaration in C++ to avoid circular header file references? I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how.
You predeclare the class without including it. For example: //#include "Foo.h" // including Foo.h causes circular reference class Foo; class Bar { ... };
183,991
184,607
Setting a data breakpoint in Visual Studio 2005 on the address of a dereferenced pointer
I wonder if there's a way to do the following: I have a structure containing a member which is a pointer to a block of memory allocated by the kernel when I pass the structure to an API function (the structure is a WAVEHDR, the member is the reserved field.) I can set a data breakpoint on the value of the reserved member - that in itself is not very helpful. What I'd like to do, when the breakpoint is hit, is to dereference the pointer stored in reserved and set a new data breakpoint on the memory pointed to by that pointer. I would like VisualStudio to break when that memory is set to a known value. I know how to set a breakpoint from a macro, and how to have Visual Studio invoke that macro from a breakpoint when it's hit, but I don't know whether I can pass the pointer value to the macro so that it can set the breakpoint on the right address. The UI doesn't provide a way to do it. Is there a way for the macro to access information about the running program, and do things like evaluate global variables or other expressions? I could accomplish what I'm trying to do if I had that kind of programmatic access to the running code (during a breakpoint) from the macro.
A macro can evaluate anything that you can in the watch window: Dim e As EnvDTE.Expression e = DTE.Debugger.GetExpression("<my expression>", True) If e.IsValidValue Then ... use e.Value to do something End If The value you get back in e.Value is exactly the string you would see in the watch window, so you may have to pull it apart. There are also a bunch of other properties on the Expression object you can use. See the MSDN documentation.
184,253
203,016
Converting registry access to db calls from MFC Feature Pack
We may start converting an old VS2003 MFC project to use the fancy new features provided by the MFC Feature Pack and VS2008. Several of the new UI controls would be very nice except for one thing - they automatically save their information to the registry. I don't have a problem with the registry, but for the multiple environments the users use out program from, it's much easier to save user data to the database. So, I'm hoping that there is one main "access the registry" function that could be overloaded to point the database. But brief investigation hasn't turned up anything. Has anyone else had any success doing something similar?
It seems like it should be possible to do what you're suggesting, according to the information on this page in MSDN. I haven't tried this myself, so I don't know how difficult it will be in practice. According to the documentation, you should create a class that inherits CSettingsStore to read and write the settings, and call CSettingsStoreSP::SetRuntimeClass so that the framework uses your class instead of the default.
184,373
184,413
What is the best HTML Rendering Engine to embed in an application?
At the moment, our application uses the Trident Win32 component, but we want to move away from that for a few reasons, chief among them being our desire to go cross-platform. We're looking at WebKit and Gecko, but I'd love to get some feedback before I make a decision. Here are some of the most important requirements: It should be relatively fast, with a small footprint. Ideally, we would be able to trim away anything we don't need without too much effort. Decent documentation is important. I don't anticipate needing to do anything too unusual with it, but you never know. We're using C++, and would like to work with a well-designed object-oriented architecture, if possible. Cross-platform is a must, and good performance would be helpful in the long run (we may end up porting to mobile platforms). Are there any considerations I need to take into account before making a decision? Has anyone worked with WebKit or Gecko before? If so, are there any articles or tutorials I might find useful? Update: Thanks for the responses guys. We ended up going with Qt 4.5, which includes WebKit. We're really pleased with it so far, in fact I think Qt is probably the best UI framework I've ever used; the difference between coding with the native Win32 APIs and this is staggering. It's also real easy to learn, the only major issue we had was getting used to the signals/slots paradigm.
A little history might help in your decision. When Apple was considering which engine to use in making Safari they looked at Gecko, but decided to go with KHTML, fork it and called it WebKit. Their reasons for doing this was that Gecko had tons of legacy cruft still leftover from Netscape and was far more complicated. KHTML/WebKit was newer, and thus had less legacy. It was also cleaner, quicker, and better documented. One of the goals of Firefox 3 was to clean up the codebase and simplify it. From what I've heard they did do this, but I don't know how it compares with current iterations of WebKit. It apparently wasn't enough for Google when they made Chrome, and they have a significant stake in Firefox. See here for more details.
184,777
184,794
Passing data between C++ (MFC) app and C#
We have a monolithic MFC GUI app that is nearing the end of it's life in C++. We are planning to build new functionality in C# and pass data between each app. Question is: What is the best approach for passing data between C++ and C#? Notes: Both ends will have a GUI front end and will probably only need to pass simple data like Id's and possibly have a mechanism where it indicates to the other app what process/functionality to use. Eg One of the applications will be a CRM system in C# that when a row in a grid is double clicked would pass say the customerId and a message to open that customer in the Customer Form of the MFC app. I have done a little bit of research, the options seem to be Windows Messaging, Memory Mapping, Named Pipes or something like Windows Sockets. At this stage we are leaning towards Named Pipes, but would really appreciate other advice or tips or other peoples experiences.
Personally I'd be thinking of using something like named pipes as they are easy to use from the C++ side and the System.IO.Pipes on the .NET side also. It would also be the path of probably least resistance if you're planning to replace the other non .NET bits of the app over time.
185,050
186,074
C++ testing framework: recommendation sought
I'm looking for a "quick and dirty" C++ testing framework I can use on my Windows/Visual Studio box. It's just me developing, so it doesn't have to be enterprise class software. Staring at a list of testing frameworks, I am somewhat befuddled... http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.2B.2B
Here's a great article about C++ TDD frameworks. For the record, my personal preference is CxxTest, which I have been happily using for about six months now.
185,445
185,580
FileLoadException on windows 2003 for managed c++ dll
My company has login integration with GroupWise, and Exchange 5.5/2000+. The Exchange 5.5/GroupWise logic is done using wldap32.dll (win32), and so the login code is in a managed c++ class. When the configuration tool (or the backend service) tries to load the dll built off this managed c++ project on my XP development box, it works fine. On QA/Customer Windows 2003 boxes, a FileLoadException is thrown. First off, this used to work fine. Secondly, I've validated the same working code on my box fails on the qa box. How can I track down the cause of this exception?
Have you changed your development environment recently? In particular have you installed a service pack or new release of Visual Studio? It appears you are linking against a C++ runtime that is not available on the client's server. You can use the Windows Event Viewer to identify the DLL failing to load, or if this shows nothing, use depends.exe to see what runtime DLLs are dependencies for your managed code. Microsoft has moved to using side-by-side installation to handle "DLL hell", basically this allows multiple versions of a DLL to be installed (side-by-side) concurrently on a Windows installations and have applications load the correct version of the DLL at run-time. Recent releases of Visual Studio make use of this technology so I suspect this is the cause of your 'sudden' incompatibility.
185,844
185,848
How to initialize private static members in C++?
What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors: class foo { private: static int i; }; int foo::i = 0; I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
The class declaration should be in the header file (Or in the source file if not shared). File: foo.h class foo { private: static int i; }; But the initialization should be in source file. File: foo.cpp int foo::i = 0; If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files. The initialisation of the static int i must be done outside of any function. Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const integer type (bool, char, char8_t [since C++20], char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.). You can then declare and initialize the member variable directly inside the class declaration in the header file: class foo { private: static int const i = 42; };
185,862
185,913
New project: I am having troubles picking a language to use
I am starting my first independent for profit venture. I am having a hard time deciding what language to use. I want to write my app in Perl, but I don't think it will be simple enough to compile. If I don't write it in Perl I will write it in C++. The application will have many features, including wxwidgets interface, Deal with SDL, timers, some threading, and audio processing. The program itself will be somewhat complex, but not terribly large. So my question's are: Can PAR, Perl2exe, or equivalent compile more than a basic test cases? Speed, and compilation aside why should I use C++ over Perl? Edit: Some of my project specifications. Multi Platform. I am expecting 50% or more of my users to own macs, with Most of the rest being Windows users. If possible I also want to support Linux since It is my everyday operating system. Since it's multi Platform I need a unified GUI creation tool. It needs to be able to use basic types, and allow me to create custom event handlers, and custom GUI objects. It needs audio processing. Read and play, wav's and/or mp3's. Also I will be using some custom algorithms to determine special properties of the audio files; things like tempo, patterns, and so on. I would like but don't require SDL/OpenGL support. Everything else is pretty mundane. Some different classes and containers. A few custom GUI controls.
Why not use a hybrid of both? It's generally the way a lot of development is going these days. I'd suggest a Lua/C++ or a Python/C++ combo (I'm not sure how well a Perl/C++ combo works, but that may be a good option too). Personally I've done a bunch with the Lua/C++ combo and it's pretty fantastic.
185,883
185,921
Qt: difference between moc output in debug and release?
Using the Qt Visual studio integration, adding a new Qt class adds two separate moc.exe generated files - one for debug and one for release (and one for any other configuration currently existing). Yet the two eventual generated files seem to be identical. On the other hand when adding a UI class, the uic.exe generated files don't have this separation and are the same file for all configurations. Does anybody have an idea why there's a need for a separate moc file for every configuration? When is there a difference between the two?
My guess would be that separate debug and release versions are needed because the moc output is generated from user-defined source code. So the moc output might be different between debug and release builds if the preprocessed class source differs between debug and release (for example, a signal that exists only in the debug build). This doesn't apply to the uic-generated files because those are generated from the .ui XML, which can't vary between debug and release configurations.
186,073
186,414
What are some good DirectX resources for a beginner?
I'm learning DirectX as part of a hobby project. I've been looking for some good online resources for DirectX9 (using C++, if that distinction matters), but haven't found anything that's a) great for a beginner and b) up to date. Any recommendations?
When I started using DirectX I found this to be the best resource around for basic stuff: http://www.directxtutorial.com/ When you start reaching an intermediate level they want you to pay a subscription but all the good basic stuff is free. Tutorials are clear and literally step-by-step. This is website is not bad at all either: http://www.toymaker.info/ - with some good project downloads. If you have problems the best place to go in my experience is http://www.gamedev.net/ , they have great articles and forums with plenty of so-called gurus.
186,232
186,834
Exporting DLL C++ Class , question about .def file
I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section . Could anyone point me in the right direction ? The error message is the following : NMAKE : U1073: don't know how to make 'DLLCLASS.def' P.S: I'm trying to build using Windows CE Platform Builder .
You can always find the decorated name for the member function by using dumpbin /symbols myclass.obj in my case class A { public: A( int ){} }; the dumpbin dump showed the symbol ??0A@@QAE@H@Z (public: __thiscall A::A(int)) Putting this symbol in the .def file causes the linker to create the A::A(int) symbol in the export symbols. BUT! as @paercebal states in his comment: the manual entry of decorated (mangled) names is a chore - error prone, and sadly enough, not guarenteed to be portable across compiler versions.
186,237
186,285
Program only crashes as release build -- how to debug?
I've got a "Schroedinger's Cat" type of problem here -- my program (actually the test suite for my program, but a program nonetheless) is crashing, but only when built in release mode, and only when launched from the command line. Through caveman debugging (ie, nasty printf() messages all over the place), I have determined the test method where the code is crashing, though unfortunately the actual crash seems to happen in some destructor, since the last trace messages I see are in other destructors which execute cleanly. When I attempt to run this program inside of Visual Studio, it doesn't crash. Same goes when launching from WinDbg.exe. The crash only occurs when launching from the command line. This is happening under Windows Vista, btw, and unfortunately I don't have access to an XP machine right now to test on. It would be really nice if I could get Windows to print out a stack trace, or something other than simply terminating the program as if it had exited cleanly. Does anyone have any advice as to how I could get some more meaningful information here and hopefully fix this bug? Edit: The problem was indeed caused by an out-of-bounds array, which I describe more in this post. Thanks everybody for your help in finding this problem!
In 100% of the cases I've seen or heard of, where a C or C++ program runs fine in the debugger but fails when run outside, the cause has been writing past the end of a function local array. (The debugger puts more on the stack, so you're less likely to overwrite something important.)
186,494
186,505
if(str1==str2) versus if(str1.length()==str2.length() && str1==str2)
I've seen second one in another's code and I suppose this length comparison have been done to increase code productivity. It was used in a parser for a script language with a specific dictionary: words are 4 to 24 letters long with the average of 7-8 lettets, alphabet includes 26 latin letters plus "@","$" and "_". Length comparison were used to escape == operator working with STL strings, which obviously takes more time then simple integer comparison. But in the same time first letter distribution in the given dictionary is simply wider than a distribution of words size, so two first letters of comparing strings will be generally more often different, than the sizes of that strings. That makes length comparison unnecessary. I've ran some tests and that is what I've found out: While testing two random strings comparison million times, second way is much faster, so length comparison seems to be helpful. But in a working project it works even slower in a debug mode and insufficiantly faster in a release mode. So, my question is: why length comparison can fasten the comparison and why can it slow it down? UPD: I don't like that second way either, but it had been done for a reason, I suppose, and I wonder, what is this reason. UPD2: Seriously, the question is not how to do best. I'm not even using STL strings in this case anymore. There's no wonder that length comparison is unnecessary and wrong etc. The wonder is - it really tends to work slightly better in one certain test. How is this possible?
In your random test the strings might have been long enough to show the gain while in your real case you may deal with shorter strings and the constant factor of two comparison is not offset by any gain in not performing the string comparison part of the test.
187,057
195,803
glBlendFunc and alpha blending
I want to know how the glBlendFunc works. For example, i have 2 gl textures, where the alpha is on tex1, i want to have alpha in my final image. Where the color is on tex1, i want the color from tex2 to be.
Sadly, this is for openGL ES on the iPhone, so no shaders, but point taken. My problem was a very simplified version of the questions, i needed to apply a simple color ( incl alpha ), to a part of a defined texture. As Lee pointed out, texture blending is to allow alpha to show up on the framebuffer. The solution was to insist that the artist makes the "action bit" of the texture white, and then assigning a color to the vertices that i render. Something like this. glTexCoordPointer( 2, GL_FLOAT, 0, sprite->GetTexBuffer() ); glVertexPointer( 3, GL_FLOAT, 0, sprite->GetVertexBuffer() ); glColorPointer( 4, GL_FLOAT, 0, sprite->GetColorBuffer() ); glDrawArrays( GL_TRIANGLES, 0, 6 ); // Draw 2 triangles Where even tho it has a texture, having the color means it adds to the texture's color, so where it's an alpha, it remains alpha, and where it is white ( as i had to make it ), it becomes the color of the color pointer at the point.
187,421
187,525
Virtual List Controls (MFC)
I am using a List Control to display a representation of elements within a vector. When the list is clicked on another control shows information about that element. The index of the element is currently determined by its index in the control, however if I wish to sort or filter the results this will no longer work. I have been told that I could use a virtual list control, but the MSDN is not very friendly, can someone run me through how I could use a virtual list control for this?
Frankly - tying data (the position in your data vector) to the presentation of the data in the list control (the position in the list ctrl) is something I would stay away from. In MFC each control has a "Data" DWORD member variable - when coding in MFC I Always called "SetItemData" for each item added and passed in a pointer that the relevant row referred to e.g. YourListCtrl.SetItemData((DWORDPTR)&YourData); Then when the ListCtrl item is selected, you just call DataTypeYouWant* pData = (DataTypeYouWant*)(YourListCtrl.GetItemData(indexofselecteditem)); Or somesuch thing. Alternatively - if you don't want to use pointers - hold the index of the item in your original vector in the itemdata for your row (just pass it into the above fns).
187,567
187,931
How can I stop my MFC application from calling OnFileNew() when it starts?
I used Visual Studio's Application Wizard to create a skeleton MFC program with a multi-document interface. When I start this program, it automatically creates a child frame, which I don't want it to do - I need the main frame's client area to be empty until the user chooses to open a file. The debugger tells me that a CChildFrame object is created when the application class's InitInstance() function calls ProcessShellCommand(), but what is a good entry point for me to override this behaviour?
This worked for me -- change if (!ProcessShellCommand(cmdInfo)) to if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew && !ProcessShellCommand(cmdInfo)) in your app's InitInstance() function.
187,583
187,591
Do I need to protect read access to an STL container in a multithreading environment?
I have one std::list<> container and these threads: One writer thread which adds elements indefinitely. One reader/writer thread which reads and removes elements while available. Several reader threads which access the SIZE of the container (by using the size() method) There is a normal mutex which protects the access to the list from the first two threads. My question is, do the size reader threads need to acquire this mutex too? should I use a read/write mutex? I'm in a windows environment using Visual C++ 6. Update: It looks like the answer is not clear yet. To sum up the main doubt: Do I still need to protect the SIZE reader threads even if they only call size() (which returns a simple variable) taking into account that I don't need the exact value (i.e. I can assume a +/- 1 variation)? How a race condition could make my size() call return an invalid value (i.e. one totally unrelated to the good one)? Answer: In general, the reader threads must be protected to avoid race conditions. Nevertheless, in my opinion, some of the questions stated above in the update haven't been answered yet. Thanks in advance! Thank you all for your answers!
Yes, the read threads will need some sort of mutex control, otherwise the write will change things from under it. A reader/writer mutex should be enough. But strictly speaking this is an implmentation-specific issue. It's possible that an implementation may have mutable members even in const objects that are read-only in your code.
187,640
187,650
Default parameters with C++ constructors
Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example: // Use this... class foo { private: std::string name_; unsigned int age_; public: foo(const std::string& name = "", const unsigned int age = 0) : name_(name), age_(age) { ... } }; // Or this? class foo { private: std::string name_; unsigned int age_; public: foo() : name_(""), age_(0) { } foo(const std::string& name, const unsigned int age) : name_(name), age_(age) { ... } }; Either version seems to work, e.g.: foo f1; foo f2("Name", 30); Which style do you prefer or recommend and why?
Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor. One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info.
187,713
187,808
Converting floating point to fixed point
In C++, what's the generic way to convert any floating point value (float) to fixed point (int, 16:16 or 24:8)? EDIT: For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type. Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts. I hope that clears things up.
Here you go: // A signed fixed-point 16:16 class class FixedPoint_16_16 { short intPart; unsigned short fracPart; public: FixedPoint_16_16(double d) { *this = d; // calls operator= } FixedPoint_16_16& operator=(double d) { intPart = static_cast<short>(d); fracPart = static_cast<unsigned short> (numeric_limits<unsigned short> + 1.0)*d); return *this; } // Other operators can be defined here }; EDIT: Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out): template <class BaseType, size_t FracDigits> class fixed_point { const static BaseType factor = 1 << FracDigits; BaseType data; public: fixed_point(double d) { *this = d; // calls operator= } fixed_point& operator=(double d) { data = static_cast<BaseType>(d*factor); return *this; } BaseType raw_data() const { return data; } // Other operators can be defined here }; fixed_point<int, 8> fp1; // Will be signed 24:8 (if int is 32-bits) fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits)
187,797
187,951
Are data members allocated in the same memory space as their objects in C++?
Say I've got a class like this: class Test { int x; SomeClass s; } And I instantiate it like this: Test* t = new Test; Is x on the stack, or the heap? What about s?
Each time you "instantiate" an object/symbol using a new (we are speaking C++ here), a new memory zone will be allocated for this object. If not, it will be put on the "local" memory zone. The problem is that I have no standard definition for "local" memory zone. An example This means that, for example: struct A { A() { c = new C() ; } B b ; C * c ; } void doSomething() { A aa00 ; A * aa01 = new A() ; } The object aa00 is allocated on the stack. As aa00::b is allocated on a "local" memory according to aa00, aa00::b is allocated inside the memory range allocated by the new aa00 instruction. Thus, aa00::b is also allocated on stack. But aa00::c is a pointer, allocated with new, so the object designed by aa00::c is on the heap. Now, the tricky example: aa01 is allocated via a new, and as such, on the heap. In that case, as aa01::b is allocated on a "local" memory according to aa01, aa01::b is allocated inside the memory range allocated by the new aa01 instruction. Thus, aa01::b is on the heap, "inside" the memory already allocated for aa01. As aa01::c is a pointer, allocated with new, the object designed by aa01::c is on the heap, in another memory range than the one allocated for aa01. Conclusion So, the point of the game is: 1 - What's the "local" memory of the studied object: Stack of Heap? 2 - if the object is allocated through new, then it is outside this local memory, i.e., it is elsewhere on the heap 3 - if the object is allocated "without new", then it is inside the local memory. 4 - If the "local" memory is on the stack, then the object allocated without new is on the stack, too. 5 - If the "local" memory is on the heap, then the object allocated without new is on the heap, too, but still inside the local memory. Sorry, I have no better vocabulary to express those concepts.
188,299
188,407
Marshal C++ struct array into C#
I have the following struct in C++: #define MAXCHARS 15 typedef struct { char data[MAXCHARS]; int prob[MAXCHARS]; } LPRData; And a function that I'm p/invoking into to get an array of 3 of these structures: void GetData(LPRData *data); In C++ I would just do something like this: LPRData *Results; Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData)); GetData( Results ); And it would work just fine, but in C# I can't seem to get it to work. I've created a C# struct like this: public struct LPRData { /// char[15] [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)] public string data; /// int[15] [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)] public int[] prob; } And if I initialize an array of 3 of those (and all their sub-arrays) and pass it into this: GetData(LPRData[] data); It returns with success, but the data in the LPRData array has not changed. I've even tried to create a raw byte array the size of 3 LPRData's and pass that into a function prototype like this: GetData(byte[] data); But in that case I will get the "data" string from the very first LPRData structure, but nothing after it, including the "prob" array from the same LPRData. Any ideas of how to properly handle this?
I would try adding some attributes to your struct decloration [StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable] public struct LPRData { /// char[15] [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)] public string data; /// int[15] [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)] public int[] prob; } *Note TotalBytesInStruct is not intended to represent a variable JaredPar is also correct that using the IntPtr class could be helpful, but it has been quite awhile since I have used PInvoke so I'm rusty.
188,393
188,557
Prevent views stealing focus/setting focus to a view
I have an MFC sdi app that uses a splitter window to contain a tree control alongside the main view showing the data. When the user selects something in the tree, that view keeps focus until the user deliberately clicks in the main data window. This means that any toolbar buttons associated with the main view are disabled. Is there any way to programmatically switch focus back to the main view after the user has clicked the tree control? Or am I doing something fundamentally wrong using a CSplitterWnd and 2 views?
You don't want to bring the focus back to the other view as soon as someone clicks the tree: It would make your app unusable. e.g. It would prevent users from navigating through the tree using the keyboard since the tree would never keep the focus long enough. I you really want the toolbar to keep reflecting the state of your 2nd view (I'm not sure it's a good idea), you have a few options. Make your pick. 2 come to mind: Your tree view should NOT be a CView. Use a simple CTreeCtrl. Not very nice because it kind of break the doc/view paradigm (e.g. no more tree's OnUpdate() called whenever an UpdateAllViews() is called). Prevent the tree from becoming the active view. To do so: 2.a. When you view gets the focus (OnSetFocus()): STATIC_DOWNCAST(CFrameWnd, AfxGetMainWnd())->SetActiveView(pTheOtherView); 2.b. Derive a CMySplitterWnd class from CSplitterWnd, then override CMySplitterWnd::SetActivePane() to prevent it from setting the treeview as the active view. In all cases, welcome to the wonderful world of MFC internals where diving into the source code is the mandatory daily sport ;-)
188,449
188,454
What are some techniques for limiting compilation dependencies in C++ projects?
In a C++ project, compilation dependencies can make a software project difficult to maintain. What are some of the best practices for limiting dependencies, both within a module and across modules?
Forward Declarations Abstract Interfaces The Pimpl Idiom
188,591
266,785
Is there a fix or a workaround for the memory leak in getpwnam?
Is there a fix or a workaround for the memory leak in getpwnam?
getpwnam() does not suffer of memory leak. Subsequent calls, indeed, will overwrite its static internal buffer. Such kind of functions are instead non-reentrant and therefore non-thread safe. Paul suggested the use of getpwnam_r() which is the reentrant version, that is safe to be used in a multithread context. That said, memory leaks are caused by those system calls that allocate memory by means of malloc() and leave the application the responsability to free() the memory once the returned data has used. In these cases the RAII idiom is advisable in order to not forget to free the allocated memory -- see exception safety. std::tr1::shared_ptr<> is also a viable way: For the shared_ptr a custom deleter must be provided to free() the raw pointer when the shared_ptr goes out of the scope. Under this perspective some dangerous functions are scandir(), asprintf(), vasprintf() etc.
188,693
188,882
Is the destructor called if the constructor throws an exception?
Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')
Preamble: Herb Sutter has a great article on the subject: http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/ C++ : Yes and No While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called. As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way. For example: struct Class { Class() ; ~Class() ; Thing * m_pThing ; Object m_aObject ; Gizmo * m_pGizmo ; Data m_aData ; } Class::Class() { this->m_pThing = new Thing() ; this->m_pGizmo = new Gizmo() ; } The order of creation will be: m_aObject will have its constructor called. m_aData will have its constructor called. Class constructor is called Inside Class constructor, m_pThing will have its new and then constructor called. Inside Class constructor, m_pGizmo will have its new and then constructor called. Let's say we are using the following code: Class pClass = new Class() ; Some possible cases: Should m_aData throw at construction, m_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated. Should m_pThing throw at new Thing (out of memory), m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Should m_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Should m_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Note that m_pThing leaked If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost): struct Class { Class() ; ~Class() ; std::auto_ptr<Thing> m_pThing ; Object m_aObject ; std::auto_ptr<Gizmo> m_pGizmo ; Data m_aData ; } Class::Class() : m_pThing(new Thing()) , m_pGizmo(new Gizmo()) { } Or even: Class::Class() { this->m_pThing.reset(new Thing()) ; this->m_pGizmo.reset(new Gizmo()) ; } if you want/need to create those objects inside the constructor. This way, no matter where the constructor throws, nothing will be leaked.
188,942
188,948
How do you iterate backwards through an STL list?
I'm writing some cross-platform code between Windows and Mac. If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse backwards? This code workson the Mac but not on Windows (can't decrement beyond first element): list<DVFGfxObj*>::iterator iter = m_Objs.end(); for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ? { } this works on Windows: list<DVFGfxObj*>::iterator iter = m_Objs.end(); do{ iter--; } while (*iter != *m_Objs.begin()); Is there another way to traverse backward that could be implemented in a for loop?
Use reverse_iterator instead of iterator. Use rbegin() & rend() instead of begin() & end(). Another possibility, if you like using the BOOST_FOREACH macro is to use the BOOST_REVERSE_FOREACH macro introduced in Boost 1.36.0.
189,055
189,077
Is Iterator initialization inside for loop considered bad style, and why?
Typically you will find STL code like this: for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter) { } But we actually have the recommendation to write it like this: SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end(); for (; Iter != IterEnd; ++Iter) { } If you're worried about scoping, add enclosing braces: { SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end(); for (; Iter != IterEnd; ++Iter) { } } This is supposed to give a speed and efficiency gain, especially if you are programming consoles, because the .end() function is not called on each iteration of the loop. I just take the performance improvement for granted, it sounds reasonable but i don't know how much and it certainly depends on the type of container and actual STL implementation in use. But having used this style for a couple months now i actually prefer it over the first anyway. The reason being readability: the for line is neat and tidy. With qualifiers and member variables in real production code it is quite easy to have really long for lines if you use the style in the first example. That's why i intentionally made it to have a horizontal scrollbar in this example, just so you see what i'm talking about. ;) On the other hand, you suddenly introduce the Iter variables to the outer scope of the for loop. But then, at least in the environment i work in, the Iter would have been accessible in the outer scope even in the first example. What is your take on this? Are there any pro's to the first style other than possibly limiting the scope of Iter?
If you wrap your code into lines properly, the inline form would be equally readable. Besides, you should always do the iterEnd = container.end() as an optimization: for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(), IterEnd = m_SomeMemberContainerVar.end(); Iter != IterEnd; ++Iter) { } Update: fixed the code per paercebal's advice.
189,172
189,444
C++ templates Turing-complete?
I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in this post and also on wikipedia. Can you provide a nontrivial example of a computation that exploits this property? Is this fact useful in practice?
Example #include <iostream> template <int N> struct Factorial { enum { val = Factorial<N-1>::val * N }; }; template<> struct Factorial<0> { enum { val = 1 }; }; int main() { // Note this value is generated at compile time. // Also note that most compilers have a limit on the depth of the recursion available. std::cout << Factorial<4>::val << "\n"; } That was a little fun but not very practical. To answer the second part of the question: Is this fact useful in practice? Short Answer: Sort of. Long Answer: Yes, but only if you are a template daemon. To turn out good programming using template meta-programming that is really useful for others to use (ie a library) is really really tough (though do-able). To Help boost even has MPL aka (Meta Programming Library). But try debugging a compiler error in your template code and you will be in for a long hard ride. But a good practical example of it being used for something useful: Scott Meyers has been working extensions to the C++ language (I use the term loosely) using the templating facilities. You can read about his work here 'Enforcing Code Features'
189,350
189,524
Detect GCC compile-time flags of a binary
Is there a way to find out what gcc flags a particular binary was compiled with?
A quick look at the GCC documentation doesn't turn anything up. The Boost guys are some of the smartest C++ developers out there, and they resort to naming conventions because this is generally not possible any other way (the executable could have been created in any number of languages, by any number of compiler versions, after all). (Added much later): Turns out GCC has this feature in 4.3 if asked for when you compile the code: A new command-line switch -frecord-gcc-switches ... causes the command line that was used to invoke the compiler to be recorded into the object file that is being created. The exact format of this recording is target and binary file format dependent, but it usually takes the form of a note section containing ASCII text.
189,622
189,628
What is the purpose of the cbSize member in Win32API structs
I frequently encounter some definitions for Win32API structures (but not limited to it) that have a cbSize member as in the following example. typedef struct _TEST { int cbSize; // other members follow } TEST, *PTEST; And then we use it like this: TEST t = { sizeof(TEST) }; ... or TEST t; t.cbSize = sizeof(TEST); ... My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the cbSize member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you. What is the purpose of the cbSize member in some C++ structures on Win32API?
My initial guess is that this could potentially be used for versioning. That's one reason. I think it's the more usual one. Another is for structures that have variable length data. I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.
189,892
189,907
Best practices for handling variable size arrays in c / c++?
If I have an array of a fixed size depending on how it is defined and used, I typically use one of two ways to reference it. Array type 1: Since it is a fixed size based on a define, I just use that define in all my loops referencing it. #define MAXPLAYERS 4 int playerscores[MAXPLAYERS]; for(i=0;i<MAXPLAYERS;++i) { .... do something with each player } Array type 2: Since this array can grow as items are added to it, I use the sizeof to count the number of entries in it. The size would be converted to a constant by the compiler so there shouldn't be any runtime penalty to doing it this way. typedef struct { fields.... }MYSTRUCT_DEF; MYSTRUCT_DEF mystruct[]={ {entry 1}, {entry 2}, {entry 3...n} }; for(i=0;i<(sizeof(mystruct)/sizeof(MYSTRUCT_DEF));++i) { ..... do something with each entry } Is there a more elegant solution to handling processing of arrays without going past the end or stopping too early. Thoughts? Comments?
This will work for both of your cases, regardless of array element type: #define ARRAY_COUNT(x) (sizeof(x)/sizeof((x)[0])) ... struct foo arr[100]; ... for (i = 0; i < ARRAY_COUNT(arr); ++i) { /* do stuff to arr[i] */ }
190,059
190,163
Building windows c++ libraries without a runtime?
I'm trying to create a c++ library for use on windows/MSVC. My problem is that it seems that in order to link properly, I need to distribute a bunch of different versions, linked against different versions of MSVC's c++ runtimes - single and multi-threaded, debug and release, different compiler versions, various other security and other options. I'd love to just distribute maybe two, 32 bit and 64 bit. My idea is to maybe use a different new operator (say, mynew) and custom allocators for all my STL types. When creating the lib, /nodefaultlib. Then, when linking in from a parent project, require them to thunk mynew to new, and my stl allocator to the standard one (or one of their choosing). I guess I'd need to do delete, and a few other functions. Naturally I'd provide an example thunking implementation with the library, but this would hopefully save everyone a lot of headache. Is this possible? Has anyone ever tried this? Is there a best practices for library creation/distribution on windows/MSVC?
You want static linking, as a general answer. Quick note on Chris' answer (don't want to de-boost cause it's mostly good, but...): DO NOT link to msvcrt.dll (the unversioned one); this is the OS-specific version DLL, and if you link to it, your app probably will not work on other versions of Windows. You should always be linking to msvcrt##.dll, as far as I know. The DDK may contain a lib for it, but don't link to it unless you really know what you're doing.
190,184
190,208
execv() and const-ness
I often use the execv() function in C++, but if some of the arguments are in C++ strings, it annoys me that I cannot do this: const char *args[4]; args[0] = "/usr/bin/whatever"; args[1] = filename.c_str(); args[2] = someparameter.c_str(); args[3] = 0; execv(args[0], args); This doesn't compile because execv() takes char *const argv[] which is not compatible with const char *, so I have to copy my std::strings to character arrays using strdup(), which is a pain. Does anyone know the reason for this?
The Open Group Base Specifications explains why this is: for compatibility with existing C code. Neither the pointers nor the string contents themselves are intended to be changed, though. Thus, in this case, you can get away with const_cast-ing the result of c_str(). Quote: The statement about argv[] and envp[] being constants is included to make explicit to future writers of language bindings that these objects are completely constant. Due to a limitation of the ISO C standard, it is not possible to state that idea in standard C. Specifying two levels of const- qualification for the argv[] and envp[] parameters for the exec functions may seem to be the natural choice, given that these functions do not modify either the array of pointers or the characters to which the function points, but this would disallow existing correct code. Instead, only the array of pointers is noted as constant. The table and text after that is even more insightful. However, Stack Overflow doesn't allow tables to be inserted, so the quote above should be enough context for you to search for the right place in the linked document.
190,232
190,268
Can a recursive function be inline?
inline int factorial(int n) { if(!n) return 1; else return n*factorial(n-1); } As I was reading this, found that the above code would lead to "infinite compilation" if not handled by compiler correctly. How does the compiler decide whether to inline a function or not ?
First, the inline specification on a function is just a hint. The compiler can (and often does) completely ignore the presence or absence of an inline qualifier. With that said, a compiler can inline a recursive function, much as it can unroll an infinite loop. It simply has to place a limit on the level to which it will "unroll" the function. An optimizing compiler might turn this code: inline int factorial(int n) { if (n <= 1) { return 1; } else { return n * factorial(n - 1); } } int f(int x) { return factorial(x); } into this code: int factorial(int n) { if (n <= 1) { return 1; } else { return n * factorial(n - 1); } } int f(int x) { if (x <= 1) { return 1; } else { int x2 = x - 1; if (x2 <= 1) { return x * 1; } else { int x3 = x2 - 1; if (x3 <= 1) { return x * x2 * 1; } else { return x * x2 * x3 * factorial(x3 - 1); } } } } In this case, we've basically inlined the function 3 times. Some compilers do perform this optimization. I recall MSVC++ having a setting to tune the level of inlining that would be performed on recursive functions (up to 20, I believe).
190,263
190,366
Localization testing, formatting all strings with XXXXX
We are trying to look at optimizing our localization testing. Our QA group had a suggestion of a special mode to force all strings from the resources to be entirely contained of X. We already API hijack LoadString, and the MFC implementation of it, so doing it should not be a major hurdle. My question is how would you solve the formatting issues? Examples - CString str ; str . LoadString ( IDS_MYSTRING ) ; where IDS_MYSTRING is "Hello World", should return "XXXXX XXXXX" where IDS_MYSTRING is "Hello\nWorld", should return "XXXXX\nXXXXX" where IDS_MYSTRING is "Hello%dWorld", should return "XXXXX%dXXXXX" where IDS_MYSTRING is "Hello%.2fWorld", should return "XXXXX%.2fXXXXX" where IDS_MYSTRING is "Hello%%World", should return "XXXXX%%XXXXX" So in summary the string should work if used in a printf or Format statement, it should honor escape characters. So this is a pure code question, C++/MFC, CString ConvertStringToXXXX ( const CString& aSource ) { CString lResult = aSource ; // Insert your code here return lResult ; } I know this could be done using tools on the .RC files, but we want to build English, then run like so - application -L10NTEST
If this approach is to highlight formatted strings (or format sequences) in the application (i.e. all text appearing other than XXXX), you could locate the escape sequence (using regex perhaps) and insert block quotes around the formatted (substituted) values, e.g. Some\ntext -> Some[\n]text You get readability (all strings as XXX might be hard to use the application) and also get to detect non-resource (hardcoded) strings. Having said that, if you're looking to detect non resource loaded strings (hardcoded strings), instead of substituting Xs, why not just prefix the string? You'll easily be able to tell resource loaded strings from hardcoded strings easily, e.g. Some\ntext -> [EN]Some\ntext Hope it helps?
190,553
190,565
What's the Difference Between func(int &param) and func(int *param)?
In the following code, both amp_swap() and star_swap() seems to be doing the same thing. So why will someone prefer to use one over the other? Which one is the preferred notation and why? Or is it just a matter of taste? #include <iostream> using namespace std; void amp_swap(int &x, int &y) { int temp = x; x = y; y = temp; } void star_swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int a = 10, b = 20; cout << "Using amp_swap(): " << endl; amp_swap(a, b); cout << "a = " << a << ", b = " << b << endl; cout << "Using star_swap(): " << endl; star_swap(&a, &b); cout << "a = " << a << ", b = " << b << endl; return 0; } Thanks for your time! See Also Difference between pointer variable and reference variable in C++
One is using a reference, one is using a pointer. I would use the one with references, because you can't pass a NULL reference (whereas you can pass a NULL pointer). So if you do: star_swap(NULL, NULL); Your application will crash. Whereas if you try: amp_swap(NULL, NULL); // This won't compile Always go with references unless you've got a good reason to use a pointer. See this link: http://www.google.co.uk/search?q=references+vs+pointers
190,681
190,697
When is loop unwinding effective?
Loop unwinding is a common way to help the compiler to optimize performance. I was wondering if and to what extent the performance gain is affected by what is in the body of the loop: number of statements number of function calls use of complex data types, virtual methods, etc. dynamic (de)allocation of memory What rules (of thumb?) do you use to decide whether or not to unwind a performance critical loop? What other optimisation do you consider in these cases?
In general unrolling loops by hand is not worth the effort. The compiler knows better how the target architecture works and will unroll the loop if it is beneficial. There are code-paths that benefit when unrolled for Pentium-M type CPU's but don't benefit for Core2 for example. If I unroll by hand the compiler can't make the decision anymore and I may end up with less than optimal code. E.g. exactly the opposite I tried to achieve. There are several cases where I do unroll performance critical loops by hand, but I only do this if I know that the compiler will - after manual unrolling - be able to use architectural specific feature such as SSE or MMX instructions. Then, and only then I do it. Btw - modern CPUs are very efficient at executing well predictable branches. This is exactly what a loop is. The loop overhead is so small these days that it rarely makes a difference. Memory latency effects that may occur due to the increase in code-size will however make a difference.
190,748
191,876
Why can't I put a variable declaration in the test portion of a while loop?
You can, obviously, put a variable declaration in a for loop: for (int i = 0; ... and I've noticed that you can do the same thing in if and switch statements as well: if ((int i = f()) != 0) ... switch (int ch = stream.get()) ... But when I try to do the same thing in a while loop: while ((int ch = stream.get()) != -1) ... The compiler (VC++ 9.0) does not like it at all. Is this compliant behavior? Is there a reason for it? EDIT: I found I can do this: while (int ch = stream.get() != -1) ... but because of precedence rules, that's interpreted as: while (int ch = (stream.get() != -1)) ... which is not what I want.
The grammar for a condition in the '03 standard is defined as follows: condition: expression type-specifier-seq declarator = assignment-expression The above will therefore only allow conditions such as: if ( i && j && k ) {} if ( (i = j) ==0 ) {} if ( int i = j ) {} The standard allows the condition to declare a variable, however, they have done so by adding a new grammar rule called 'condition' that can be an expression or a declarator with an initializer. The result is that just because you are in the condition of an if, for, while, or switch does not mean that you can declare a variable inside an expression.
191,020
191,140
QDockWidget initial width
How do I set the initial width of a QDockWidget? I have implemented the sizeHint function but what next?
The documentation for QDockWidget says: A QDockWidget acts as a wrapper for its child widget, set with setWidget(). Custom size hints, minimum and maximum sizes and size policies should be implemented in the child widget. QDockWidget will respect them, adjusting its own constraints to include the frame and title. Size constraints should not be set on the QDockWidget itself, because they change depending on wether it is docked; a docked QDockWidget has no frame and a smaller title bar. So the size hint is taken from whatever you put in the dock widget. Have you tried setting the size of the QDockWidget's child? But, I agree with Marius, the best thing to do is probably to use QSettings to save and restore the widths of all the dock windows when the application starts. Have a look at QMainWindow::saveState Apart from getting the data from saveState rather than from individual functions my save function looks very similar to the one given by Marius.
191,253
191,272
What are some convincing arguments to upgrade from Visual Studio 6?
I have a client who is still using Visual Studio 6 for building production systems. They write multi-threaded systems that use STL and run on mutli-processor machines. Occasionally when they change the spec of or increase the load on one of their server machines they get 'weird' difficult to reproduce errors... I know that there are several issues with Visual Studio 6 development and I'd like to convince them to move to Visual Stuio 2005 or 2008 (they have Visual Studio 2005 and use it for some projects). The purpose of this question is to put together a list of known issues or reasons to upgrade along with links to where these issues are discussed or reported. It would also be useful to have real life 'horror stories' of how these issues have bitten you.
Not supported on 64-bit systems, compatibility issues with Vista, and it was moved out of extended support by Microsoft on April 8, 2008 http://msdn.microsoft.com/en-us/vbrun/ms788708.aspx
191,493
192,008
Avoiding Dialog Boilerplate in Delphi and /or C++
I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this. Dialog.Edit1.Text := MyObject.Username; Dialog.Edit2.Text := MyObject.Password; // ... many more of the same if (Dialog.ShowModal = mrOk) begin MyObject.Username := Dialog.Edit1.Text; MyObject.Password := Dialog.Edit2.Text; // ... again, many more of the same end; I also often need similar code for marshalling objects to/from xml/ini-files/whatever. Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?
well, something that I feel completely invaluable is the GExperts plugin wizard "Reverse Statement" which is invoked after installing GExperts by pressing Shift + ALT + R What it does is automatically switch the assignments around for the highlighted block. For example: edit1.text := dbfield.asString; becomes dbField.asString := edit1.text; Not exactly what your looking for, but a huge time saver when you have a large number of assignments.
191,687
191,712
How Can I Build wxWidgets With Eclipse On Windows
I installed wxWidgets 2.8.9 on a Windows XP SP2 box and built the library according to the directions and now I'm trying to get the Hello World! tutorial app to build from within Eclipse and I'm just missing something apparently. Any idea how to get Cygwin, Eclipse and wxWidgets to play nice together?
This answer was posted by Lars Uffmann to the comp.soft-sys.wxwindows newsgroup. In a nutshell: Add c:/cygwin/usr/local/bin to the path in the Eclipse project configuration Add ``wx-config --cxxflags`‘ to the GCC C++ Compiler command Move the ${FLAGS} variable to the end of the GCC C++ Linker Command Line Pattern Add ``wx-config --libs`‘ to the GCC C++ Linker flags. Thank goodness for Mr. Uffmann sharing this information; this problem has been giving me headaches for days. EDIT: Note that there is a literal backtick at each end of the wx-config strings. The method of escaping the backtick doesn't seem to work correctly. Refer to the linked answer for more details on exact syntax.