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 exampl...
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 ...
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 t...
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 ad...
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 ba...
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...
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; } templ...
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: cop...
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 fo...
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], [LastN...
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()...
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 ...
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, ...
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...
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 cod...
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-ha...
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. O...
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+...
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...
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 m...
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...
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...
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...
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 tha...
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 sol...
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 ...
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 ba...
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 decompressio...
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 se...
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 ...
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 drif...
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 a...
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() al...
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: nodeh...
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 s...
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(Conta...
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 ...
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 ...
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 hierarchica...
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]; unsig...
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>? Accepte...
#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, ...
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 a...
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, b...
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_iterato...
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...
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...
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, eith...
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 ...
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...
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...
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) { ...
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 != _acti...
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 constructo...
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 a...
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 fr...
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 la...
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 comp...
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 curr...
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 allocat...
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 EnumDispla...
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 d...
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 applica...
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 atte...
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 thi...
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 as...
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...
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)...
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 Revers...
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); Ma...
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 textur...
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 thr...
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 c...
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 actu...
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...
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),...
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...
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 Compac...
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,...
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 befo...
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 uninitial...
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 s...
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 memb...
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 w...
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 ...
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, a...
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: ...
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. ...
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 simpl...
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 developme...
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 sho...
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 ...
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 fil...
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,...
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...
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...
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 ...
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....
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 i...
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 deter...
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 "_". Le...
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 t...
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 h...
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 p...
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 ...
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 acces...
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-onl...
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...
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 param...
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 ...
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); f...
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...
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 = ...
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, Size...
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 dis...
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 ...
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 s...
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 s...
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 decreme...
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(); Som...
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; ++...
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 av...
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 versi...
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(TE...
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 ef...
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) { ....
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 ...
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 ...
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 ...
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...
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...
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 yo...
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 st...
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 ...
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 referen...
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 r...
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 m...
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()) != ...
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 ...
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...
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 kno...
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....
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...
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...