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
790,687
790,689
Using a free "char const*" at static initialization time
Initialization order of free objects is undefined in C++. But what about the following? namespace foo { char const* str = "hey"; struct A { A() { cout << str; } } obj; } Is this still undefined behavior, or is there a special provision for pointers initialized with string literals? Aside from that: what if str was of type "char const[]"? And if it was a std::string?
The initialisation order is defined - they are initialised in the order they appear in a compilation unit - see section 3.6.2 of the C++ Standard. The type of the things being initialised has no effect.
791,002
791,067
joySetCapture doesn't work with fChanged = false
I am using joySetCapture with fChanged (4'th parameter) = true. I am getting the messages only when position is changed, as I should. However, I am not getting any message when a joystick button is pressed. If I use fChanged = false, the wParam of the periodic messages is updated correctly. How can I get messages only when either position or button is changed, without using periodic messages?
The documentation for joySetCapture says that if fChanged is true, then messages are only sent when the position changes by more than the threshold. Since it doesn't mention the buttons, I would assume that it doesn't send messages when buttons are pressed. This seems like poor design to me, but if that's how it is, then you have to deal with it. Why don't you want to use periodic polling messages? As long as you set the polling interval to something reasonable (such as 16 ms for a 60 Hz refresh rate), I can assure you that polling the joystick is NOT going to be the bottleneck in your application, so it's not a question of performance. There's no reason to set the polling interval to something really small, because the hardware simply doesn't send out updates that fast, so you'd just be wasting cycles processing the same data. Finally, the multimedia joystick API is somewhat dated and has been superseded by DirectX. You should use DirectInput instead so that you can handle joysticks with more than 4 buttons or more than 2 axes. Furthermore, if you're using Xbox 360 controllers, you should use the XInput library to process those.
791,097
795,790
Is there a decent C++ wrapper around Win32's lockless SList out there?
Windows provides a lockless singly linked list, as documented at this page: Win32 SList I'm wondering if there's an existing good C++ wrapper around this functionality. When I say good, I mean it exports the usual STL interface as much as possible, supports iterators, etc. I'd much rather use someone else's implementation than sit down to write an STL-type container.
You could quickly get up and running with boost and ::boost::iterator_facade. No it wouldn't be optimal or portable and iterator semantics are something you should hear Alexandrescou suddenly come out against at DevCon. You are not locking the container, you are locking (and potentially relocking and unlocking ) the operations. And locking the operation means serial execution, very simple. There is plenty of iterator manipulation that will be an unnecessary penalty for the abstraction being created. From Mars view, iterator is hiding the pointer, and hiding under a semi-OO concept that is as odds as OO-vs-Distributed development is.. I'd use a 'procedural' interface for sure and make the users/maintainers pay attention to why it is necessary. Lock-free ops are only as good as 'all the parallel code' surrounding it. And classic examples as people keep giving scoped_lock wrapping reinvention since '96 credit, it produces pretty serial code. Or use the atomic and Sutter's DDJ entries as reference for poor man way forward (and more than 10 years of unorderedness of Pentium Pro later). (all that is really happening is that boost and DDJ is running after a .net and MS CCR train that is running after immutability, as well as intel train that is running after a good OO-similar abstraction for lockfree development. The problem is it cannot be done well and some people fight it time and time again; much like concurrent_vector nonsense of TBB. The same reason exceptions never materialised as non-problematic, especially across environments, and the same reason why vector-processing in CPUs is underutilised by C++ compilers and so on and on..)
791,108
791,176
Is it worth forward-declaring library classes?
I've just started learning Qt, using their tutorial. I'm currently on tutorial 7, where we've made a new LCDRange class. The implementation of LCDRange (the .cpp file) uses the Qt QSlider class, so in the .cpp file is #include <QSlider> but in the header is a forward declaration: class QSlider; According to Qt, This is another classic trick, but one that's much less used often. Because we don't need QSlider in the interface of the class, only in the implementation, we use a forward declaration of the class in the header file and include the header file for QSlider in the .cpp file. This makes the compilation of big projects much faster, because the compiler usually spends most of its time parsing header files, not the actual source code. This trick alone can often speed up compilations by a factor of two or more. Is this worth doing? It seems to make sense, but it's one more thing to keep track of - I feel it would be much simpler just to include everything in the header file.
Absolutely. The C/C++ build model is ...ahem... an anachronism (to say the best). For large projects it becomes a serious PITA. As Neil notes correctly, this should not be the default approach for your class design, don't go out of your way unless you really need to. Breaking Circular include references is the one reason where you have to use forward declarations. // a.h #include "b.h" struct A { B * a; } // b.h #include "a.h" // circlular include reference struct B { A * a; } // Solution: break circular reference by forward delcaration of B or A Reducing rebuild time - Imagine the following code // foo.h #include <qslider> class Foo { QSlider * someSlider; } now every .cpp file that directly or indirectly pulls in Foo.h also pulls in QSlider.h and all of its dependencies. That may be hundreds of .cpp files! (Precompiled headers help a bit - and sometimes a lot - but they turn disk/CPU pressure in memory/disk pressure, and thus are soon hitting the "next" limit) If the header requires only a reference declaration, this dependency can often be limited to a few files, e.g. foo.cpp. Reducing incremental build time - The effect is even more pronounced, when dealing with your own (rather than stable library) headers. Imagine you have // bar.h #include "foo.h" class Bar { Foo * kungFoo; // ... } Now if most of your .cpp's need to pull in bar.h, they also indirectly pull in foo.h. Thus, every change of foo.h triggers build of all these .cpp files (which might not even need to know Foo!). If bar.h uses a forward declaration for Foo instead, the dependency on foo.h is limited to bar.cpp: // bar.h class Foo; class Bar { Foo * kungFoo; // ... } // bar.cpp #include "bar.h" #include "foo.h" // ... It is so common that it is a pattern - the PIMPL pattern. It's use is two-fold: first it provides true interface/implementation isolation, the other is reducing build dependencies. In practice, I'd weight their usefulness 50:50. You need a reference in the header, you can't have a direct instantiation of the dependent type. This limits the cases where forward declarations can be applied. If you do it explicitely, it is common to use a utility class (such as boost::scoped_ptr) for that. Is Build Time worth it? Definitely, I'd say. In the worst case build time grows polynomial with the number of files in the project. other techniques - like faster machines and parallel builds - can provide only percentage gains. The faster the build, the more often developers test what they did, the more often unit tests run, the faster build breaks can be found fixed, and less often developers end up procrastinating. In practice, managing your build time, while essential on a large project (say, hundreds of source files), it still makes a "comfort difference" on small projects. Also, adding improvements after the fact is often an exercise in patience, as a single fix might shave off only seconds (or less) of a 40 minute build.
791,258
791,262
Inserting and removing commas from integers in c++
Very much a noob here, so it's best to assume I know nothing in any answers. I've been writing a little app, and it's working well, but readability is a nightmare with my numbers. Essentially, all I want to do is to add commas into the numbers displayed on the screen to make it easier to read. Is there a quick and easy way to do this? I've been using stringstream to grab my numbers (I'm not sure why this is even suggested at this point, it was simply advised in the tutorial I worked through), such as(cropping out the irrelevent bits): #include <iostream> #include <string> #include <sstream> using namespace std; int items; string stringcheck; ... cout << "Enter how many items you have: "; getline (cin, stringcheck); stringstream(stringcheck) >> items; ... cout << "\nYou have " << items << " items.\n"; When that number is typed as something large, amongst everything else it becomes quite a headache to read. Is there any quick and easy way to make it print "13,653,456" as opposed to "13653456" like it would right now (assuming that's what was input of course)? Note: If it matters, I'm making this as a console application in Microsoft Visual C++ 2008 Express Edition.
Try the numpunct facet and overload the do_thousands_sep function. There is an example. I also hacked up something that just solves your problem: #include <locale> #include <iostream> class my_numpunct: public std::numpunct<char> { std::string do_grouping() const { return "\3"; } }; int main() { std::locale nl(std::locale(), new my_numpunct); std::cout.imbue(nl); std::cout << 1000000 << "\n"; // does not use thousands' separators std::cout.imbue(std::locale()); std::cout << 1000000 << "\n"; // uses thousands' separators }
791,539
791,547
How can I have folds for C++/Java in Emacs?
I know the thread about having folds for LaTex. However, I want folds for C++/Java when I code. How can you have either automatic or manual folds in Emacs for C++/Java?
Make sure you have folding-mode.el. Then, insert // {{{ // }}} Around your code. Reload your buffer, and voila! You'll have folds.
791,636
791,655
Undefined Symbol: _sf_open (Simple audio stuff on OSX)
I'm trying to get into C++ programming, and I'm quite struggling against the little details. Right now, I'm trying to get the snippet below to work, and apparently it will compile, but not link. (error message is a the bottom of this post) I'm using libsndfile to open audio files, and the linker doesn't seem to find the corrent library files for it. This is on OS X 10.5. I've downloaded libsndfile from mega-nerd.com and installed it via the ususal configure, make, sudo make install procedure. Is there anything else I need to do? Edit: I have macports installed on my system, if that's of any concern. Here's my code: #include <iostream> #include <string> #include <sndfile.h> #include "stereoSplit.h" using namespace std; int stereoSplit(string filename) { cout << filename; SF_INFO sfinfo; sfinfo.format = 0; SNDFILE * soundfile; soundfile = sf_open( filename.c_str(), SFM_READ, &sfinfo ); return 0; } int main (int argc, char const *argv[]) { return stereoSplit("testStereo.wav"); } And here's the complete error message: Undefined symbols: "_sf_open", referenced from: stereoSplit(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)in cc3hvkkk.o ld: symbol(s) not found collect2: ld returned 1 exit status
You need to link in the library. Your compiler command should look something like: g++ mystuff.cpp -lsndfile
791,687
791,730
OpenGL: glTexImage2D conflicts with glGenLists & glCallList?
I have a simple OpenGL application where I have 2 objects displayed on screen: 1) particle system, where each particle is texture mapped with glTexImage2D() call. In the drawEvent function, I draw it as a GL_TRIANGLE_STRIP with 4 glVertex3f. 2) a 3D text loaded from an object file, where each point is loaded using glNewList/glGenLists and store each point as glVertex. I draw it by making call to glCallList. The problem is as soon as I call glTexImage2D() to map my particle with a .bmp file, the 3D text would not show on the screen. The particle would look fine. (this is not expected) If I dont call glTexImage2D, I see both the 3D text and particle system. In this case, particle system looks horrible because I didnt texture map with anything. (this is expected) Does anyone know why using call list and glTexImage2D might conflict with each other? EDIT i also forgot to mention: I do call glBindTexture(GL_TEXTURE_2D, this->texture); inside the drawLoop before particle system is called. EDIT2 i only call glTexImage2D() once at system start up (when I texture mapped the bitmap)
glTexImage2D uploads the texture to the video-ram (simplified said). If OpenGL would allow you to place a glTexImage2D call inside the list it had to store the pixel-data in the list as well. Now what happends if you would execute the list? You would upload the same image data into the same texture all over gain. That makes no sense, therefore it's left out. If you want to change textures between draw calls use glBindTexure. That call sets the current texture. It's much faster. Regarding your image-upload via glTexImage2D: Do that only once for each texture. Either at the start of your program (if it's small) or each time you load new content from disk.
791,856
791,879
Which Windows GUI system should I choose with C++?
There are now so many ways to write windows apps, win32, MFC, ATL, .NET, WinForms, and probably some others that I don't know of. Which one should I choose? I'd like one that works on a fresh install of Vista, and is modern and easy to use.
If you are amateur with C++ you'll have much easier time learning WinForms than any of the native Visual C++ frameworks (Win32, MVC, etc.). WPF will give you best versatily. It's a bit harder to master than WinForms but managed and so keeps you away from the nasty Win32 stuff. The native frameworks are good mainly if you want to crunch the last bits of performance or need to keep the footprint small for stuff such as shell extensions. I'd recommend checking WinForms at least first to get some quick understanding of the principles. If WinForms doesn't suit you, you can then move to either C++ if you feel you need more low level control or WPF if you wish more shiny features like skinning and theming. Edit: Though if you have a look at WPF, remember that fresh Vista contains only .Net 3.0 so 3.5 and 3.5 SP1 features require a separate runtime installation.
791,937
791,943
When is it safe to add object values to vectors on the heap?
Let's say I have a structure named vertex with a method that adds two vertices: struct vertex { float x, y, z; // constructs the vertex with initial values vertex(float ix, float iy, float iz); // returns the value c = this + b vertex operator+(vertex b); }; vertex::vertex(float ix, float iy, float iz){ this->x = ix; this->y = iy; this->z = iz; } vertex vertex::operator+(vertex b){ vertex c; c.x = this->x + b.x; c.y = this->y + b.y; c.z = this->z + b.z; return c; } In another calling function I want to add two vertices together and add the result to a vector<vertex*>. When is it safe to use the returned value to add to the given vector? If never, how would I implement it? For example, vector<vertex*> v; vertex a(1, 2, 3); vertex b(4, 5, 6); v.push_back(&(a + b));
This is not safe, since you are storing a pointer to an automatic or temporary variable, which will be reclaimed when the current function terminates. Mixing dynamically allocated objects with automatically-allocated ones is a serious risk. Sometimes the best strategy is to completely disallow automatic allocation (e.g., by making the constructor private and using a factory method to create new instance). You would then be responsible for eliminating these at some point. A second option (not necessarily what you want) is to do everything by value. Have a vector of Vertex rather than Vertex*, and just have the vertices copied when they are stored. The way your class is written, all the fields are primitives, so this might be good enough and you wouldn't run into performance or deep-copy semantic problems.
791,953
791,969
When using Win32 code in your modern C++ app, should you use proper casting?
For example the following cast can be found littered throughout the MSDN documentation: (LPTSTR)&lpMsgBuf Should I bother converting that to: static_cast<LPTSTR>(&lpMsgBuf); Or should I just leave all the idiomatic C-esque Win32 portions as they are typically found in the docs, and save the more idiomatic C++ style/usage for the rest of my code?
New style casts were introduced for a reason: they're safer, more explanatory/self-commenting, easier to see, and easier to grep for. So use them. By more explanatory, we mean that you can't just cast to something, you have to say why you're casting (I'm casting in an inheritance hierarchy (dynamic_cast), my cast is implementation defined and possibly not portable (reinterpret_cast), I'm casting away constness (const_cast), etc.). They're purposefully long and ugly so that the cast jumps out at the reader (and to discourage a programming style that employs too much casting). They're safer because, e.g., you can't cast away constness without explicitly doing that.
792,040
792,078
fstream replace portion of a file
When I do fstream someFile("something.dat", ios::binary|ios::out); someFile.seekp(someLocation, ios::beg); someFile.write(someData, 100); It seems to replace the entire file with those 100 bytes instead of replacing only the appropriate 100 bytes, as if I had specified ios::trunc. Is there a portable way to not have it truncate the file? Edit: adding ios::in seems to do the trick, by why is this required, and is that standard behavior? Edit #2: I am not trying to append to the existing file. I need to replace the 100 bytes while leaving the rest unaffected.
You want the append flag, ios::app, if you want to write at the end of the file. To do it somewhere arbitrarily in the middle of the file, you need to seek to the right place. You CAN do this by opening the file for in and out, but if I were you I'd create a temp file, copy input up to mark, write your new data, copy the rest to EOF, close the files and replace the previous version with the temp file. This is called a "Master File update".
792,145
794,866
Is there a grammar parser (similar to yapps for python) for C++?
I'm writing an experimental language, which is very close to pseudocode, for fun and to learn more about C++. One of the problems is that I need to parse some grammar, and my search to find a good C++ grammar parser has been unsuccessful (I couldn't find anything). What I want to accomplish is this: set a to 4 And I want the parser to return a map containing something similar to: command = "set" var = "a" value = 4 based on a set of rules I give it. I ultimately would have to roll my own if I don't find anything useful, but I would like to prevent re-inventing the wheel as much as I can. So, does anyone here know of a good/sane grammar parser that generates C++ code? It's much better if it's widely used. Thanks!
Rolling your own can be as easy as writing the grammar in the first place! It's a great way to learn about parsing, glean a more intimate knowledge of your programming language, and most of all it's fun. The method is called Recursive Descent. It usually comes out much more simple and elegant than what a parser generater, and you'll never have to find a Yacc port/fork again :) For a great tutorial, check out Jack Crenshaw's Let's Build a Compiler Otherwise, Lex and Yacc are the tradional tools while Boost::Spirit is C++ specific and more modern. I would recommend Boost::Spirit as it will help cement the C++ paradigms in your programming.
792,152
792,156
How similar is an std::vector to a raw array in C++?
I'm writing a hangman game. I'm having a logic fail, both with myself and my game logic. Char guess (the letter the person guessed) isn't being added into the correct memory slot of the vector guessArray. Assume that word is an inputted word by the user. I assume this would work if guessArray were a raw array. Is there some reason this isn't working with a vector? //assume that attempts is num of attempts left void coutWord(int attempts, std::string word, char guess) { std::vector<char> guessArray(word.length()); //this is supposed to add the guess to the correct area of guessArray; //It's not. for (int i = 0; i < word.length(); i++) { if (guess == word[i]) { guessArray[i] = guess; std::cout << " " << guessArray[i] << " "; continue; } std::cout << " _ "; } std::cout << std::endl << std::endl; } EDIT: My objective with this code is to cout all the unguessed spaces AND the guessed spaces in the same for loop. I just need to "remember" previous guesses so that I get correct output. Given word = "Applesauce": Input: a a _ _ _ _ _ a _ _ _ Input: p a p p _ _ _ a _ _ _ etc.
A vector can be indexed with subscript notation [], and it is stored in contiguous memory. It is an STL container so, like an array, you can have one of any type. A vector is automatically resized. An array is 'statically' sized, and cannot be easily resized (with the exception of a manual function called to realloc.) You can use a push_back function to handle this, and you can also .reserve() memory ahead of time to save on reallocation. An array does not track it's own size, whereas a vector has functions that can check this. If you're unsure of the size of a vector, just go ahead and use .push_back() to add items to handle the matter of automatically sizing. If you reserve a chunk of memory through resize() and then index into it, it's easier to use as an array, but you lose some of the syntatic benefit of using it as a dynamically-sized object.
792,209
792,238
Compact and Repair Database programmatically
How can I call Access's Compact and Repair Database utility from within C++? I'm already using ADO and ADOX, so a solution using either of those would be handy.
Similiar to: How can I programmatically repair (not merely compact) an Access .mdb file? You can do this using COM to access the JRO.JetEngine object. There is an example in C# at CodeProject which shouldn't be too hard to convert to C++. UPDATE: Thanks to @le dorfier, here is an article with C++ example.
792,217
792,322
Simple makefile with release and debug builds - Best practices
I am new to makefiles. I learned makefile creation and other related concepts from "Managing projects with GNU make" book. The makefile is ready now and I need to make sure the one which I created is OK. Here is the makefile #Main makefile which does the build #makedepend flags DFLAGS = #Compiler flags #if mode variable is empty, setting debug build mode ifeq ($(mode),release) CFLAGS = -Wall else mode = debug CFLAGS = -g -Wall endif CC = g++ PROG = fooexe #each module will append the source files to here SRC := main.cpp #including the description include bar/module.mk include foo/module.mk OBJ := $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC))) .PHONY:all all: information fooexe information: ifneq ($(mode),release) ifneq ($(mode),debug) @echo "Invalid build mode." @echo "Please use 'make mode=release' or 'make mode=debug'" @exit 1 endif endif @echo "Building on "$(mode)" mode" @echo ".........................." #linking the program fooexe: $(OBJ) $(CC) -o $(PROG) $(OBJ) %.o:%.cpp $(CC) $(CFLAGS) -c $< -o $@ depend: makedepend -- $(DFLAGS) -- $(SRC) .PHONY:clean clean: find . -name "*.o" | xargs rm -vf rm -vf fooexe Questions The above given makefile works well with release and debug builds. But is it in the correct format? Or do you see any flaws in that? Above makefile does debug build by default when invoked using make. For release builds, make mode=release is required. Is this the correct approach? Is the debug and release compiler flags supplied to g++ is correct? For debug, I use -g -Wall and for release, just -Wall. Is this right? Any help would be great.
It is one reasonable format. It is tied specifically to GNU Make, but that's a relatively minor problem if you have chosen to use GNU Make on every platform. If there is a flaw, it is that you could end up linking object files built in debug mode to create the final build. Some might argue that a 'mode=release' option is non-standard; they'd be right, but there isn't a standard alternative that I'm aware of. You just need to be aware that your convention might not suit everyone (but it doesn't have to - it just has to suit you and your users). Building a debug build by default is probably sensible - and more sensible than building the release build by default. Dropping the -g flag for the release build is not automatically bad, but if your code ever produces a core dump, it is easier to make head or tail of the core dump if the program file includes debugging information. The primary cost of debugging information is extra sections in the program file that do not need to be loaded into system memory - the runtime cost is small. You should consider whether to include optimization flags in there. With the GCC tool set, you can use both -g and -O. It is harder to debug optimized code, but it gives you (often significant) performance benefits.
792,355
792,797
Custom widget plugin for qt designer is invisible
I've tried to create a custom widget plugin for QT Designer following this (http://doc.trolltech.com/4.3/designer-creating-custom-widgets.html) tutorial and was somewhat successful. Basically, I can place my new widget in Designer, but it doesn't draw (I get an empty square instead of whatever I try to draw in my paintEvent method, I started with some custom code but reverted to copy pasting from the tutorial when that didn't work). While placing the custom widget my system log fills up with: full_path/Designer: CGAffineTransformInvert: singular matrix. Any suggestions? I have built the example plugin that came with the qt sdk and there were no problems.
without the source it's very hard to help you. Further I would prefer Qt 4.4 - it's much more reliable and faster. Here some common problems/hints: your DLL / .so file is not in /plugins/designer/ you have a buggy paint() method your app or lib is missing some libs Can you post your paint method? ciao, Chris
792,679
795,151
How to write a regular expression for html parsing?
I'm trying to write a regular expression for my html parser. I want to match a html tag with given attribute (eg. <div> with class="tab news selected" ) that contains one or more <a href> tags. The regexp should match the entire tag (from <div> to </div>). I always seem to get "memory exhausted" errors - my program probably takes every tag it can find as a matching one. I'm using boost regex libraries.
You may also find these questions helpful: Can you provide some examples of why it is hard to parse XML and HTML with a regex? Can you provide an example of parsing HTML with your favorite parser?
793,327
795,466
fixing glCopyTexSubImage2D upside down textures
Since I have started learning about rendering to a texture I grew to understand that glCopyTexSubImage2D() will copy the designated portion of the screen upside down. I tried a couple of simple things that came to mind in order to prevent/work around this but couldn't find an elegant solution. there are two problems with doing a ::glScalef(1.0f, -1.0f, 1.0f) before rendering the texture to the screen: 1, I have to do this every time I'm using the texture. 2, I'm mostly working with 2D graphics and have backface culling turned off for GL_BACKsides. As much as possible I'd love to save switching this on and off. tried switching matrix mode to GL_TEXTURE and doing the ::glScalef(1.0f, -1.0f, 1.0f) transformation on capturing, but the results were the same. (I'm guessing the texture matrix only has an effect on glTexCoord calls?) So, How can I fix the up-down directions of textures captured with glCopyTexSubImage2D?
What are you going to be using the texture images for? Actually trying to render them upside down would usually take more work than moving that code somewhere else. If you're trying to use the image without exporting it, just flipping the texture coordinates wherever you're using the result would be the most efficient way. If you're trying to export it, then you either want to flip them yourself, after rendering. On a related note, if you are making a 2D game, why is backface culling turned on?
793,351
793,460
Weird bug while inserting into C++ std::map
I'm trying to insert some value pairs into a std::map. In the first case, I receive a pointer to the map, dereference it and use the subscript operator to assign a value. i.e. (*foo)[index] = bar; Later, when I try to iterate over the collection, I'm returned key/value pairs which contain null for the value attribute in all cases except for the first (map.begin()) item. The weird thing is, if I do the insertion via the map's insert function, everything is well, i.e: foo->insert(std::pair<KeyType,ValueType>(myKey, myValue)); Why would this be? Aren't the two methods functionally equivalent? I've pasted some snippets of actual code below for context ... typedef std::map<int, SCNode*> SCNodeMap; ... void StemAndCycle::getCycleNodes(SCNodeMap* cycleNodes) { (*cycleNodes)[root->getId()] = root; SCNode* tmp = root->getSucc(); while(tmp->getId() != root->getId()) { // (*cycleNodes)[tmp->getId()] == tmp; // crashes (in loop below) cycleNodes->insert(std::pair<int, SCNode*>(tmp->getId(), tmp));//OK std::pair<int, SCNode*> it = *(cycleNodes->find(tmp->getId())); tmp = tmp->getSucc(); } // debugging; print ids of all the SCNode objects in the collection std::map<int, SCNode*>::iterator it = cycleNodes->begin(); while(it != cycleNodes->end()) { std::pair<int, SCNode*> p = (*it); SCNode* tmp = (*it).second; // null except for it = cycleNodes->begin() std::cout << "tmp node id: "<<tmp->getId()<<std::endl; it++; } } I'm all out of ideas. Does anyone have a suggestion please?
In your actual code you have: (*cycleNodes)[tmp->getId()] == tmp; This will not assign tmp into the map, but will instead reference into the map creating an empty value (see @Neil Butterworth) - you have == instead of =. What you want is: (*cycleNodes)[tmp->getId()] = tmp;
793,375
793,972
What could cause DAMAGE: after normal block error?
I keep getting this error after my application is running for 2 days. I've been told it's been some kind of buffer overflow, but is it the only option? The app is written in C++ using Visual C++ 6.0.
In debug, when you get dynamic buffer by new, a special code gets inserted before and after the buffer to guard the buffer. Ex: <Guard>=====buffer allocated on heap of required size=======<Guard> If you overrun the buffer, the guard inserted gets corrupted and when you try to delete the buffer, then debugger would assert after detecting buffer overrun. Its bit difficult to find the buffer overrun in large code base. I would suggest couple of ways which can help you to detect this scenario: Using tools like Rational Purify: Its good tool to detect memory corruption. Debugging by Windbg with GFlags enabled: Refer my answer to similar question here
793,469
794,514
How to force the compiler to use explicit copy constructor?
I wrote a small test program with a sample class containing also self-defined constructor, destructor, copy constructor and assignment operator. I was surprised when I realized that the copy constructor was not called at all, even though I implemented functions with return values of my class and lines like Object o1; Object o2(o1); innerclass.hpp: #include <iostream> class OuterClass { public: OuterClass() { std::cout << "OuterClass Constructor" << std::endl; } ~OuterClass() { std::cout << "OuterClass Destructor" << std::endl; } OuterClass(const OuterClass & rhs) { std::cout << "OuterClass Copy" << std::endl; } OuterClass & operator=(const OuterClass & rhs) { std::cout << "OuterClass Assignment" << std::endl; } class InnerClass { public: InnerClass() : m_int(0) { std::cout << "InnerClass Constructor" << std::endl; } InnerClass(const InnerClass & rhs) : m_int(rhs.m_int) { std::cout << "InnerClass Copy" << std::endl; } InnerClass & operator=(const InnerClass & rhs) { std::cout << "InnerClass Assignment" << std::endl; m_int = rhs.m_int; return *this; } ~InnerClass() { std::cout << "InnerClass Destructor" << std::endl; } void sayHello() { std::cout << "Hello!" << std::endl; } private: int m_int; }; InnerClass innerClass() { InnerClass ic; std::cout << "innerClass() method" << std::endl; return ic; } }; innerclass.cpp: #include "innerclass.hpp" int main(void) { std::cout << std::endl << "1st try:" << std::endl; OuterClass oc; OuterClass oc2(oc); oc.innerClass().sayHello(); std::cout << std::endl << "2nd try:" << std::endl; OuterClass::InnerClass ic(oc.innerClass()); ic = oc.innerClass(); } Output: 1st try: OuterClass Constructor OuterClass Copy InnerClass Constructor innerClass() method Hello! InnerClass Destructor 2nd try: InnerClass Constructor innerClass() method InnerClass Constructor innerClass() method InnerClass Assignment InnerClass Destructor InnerClass Destructor OuterClass Destructor OuterClass Destructor After some research I read that there is no guarantee that the compiler will use the explicitely defined copy constructor. I do not understand this behavior. Why does the copy constructor even exist then, if we do not know that it is called? How does the compiler decide if it uses it? Or, even better, is there a way to force the compiler to use the self-defined copy constructor?
Just for completeness with the other answers, the standard allows the compiler to omit the copy constructor in certain situations (what other answers refer to as "Return Value Optimization" or "Named Return Value Optimization" - RVO/NRVO): 12.8 Copying class objects, paragraph 15 (C++98) Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cv-unqualified type, an implementation is permitted to treat the original and the copy as two different ways of referring to the same object and not perform a copy at all, even if the class copy constructor or destructor have side effects. For a function with a class return type, if the expression in the return statement is the name of a local object, and the cv-unqualified type of the local object is the same as the function return type, an implementation is permitted to omit creating the temporary object to hold the function return value, even if the class copy constructor or destructor has side effects. In these cases, the object is destroyed at the later of times when the original and the copy would have been destroyed without the optimization. So in your innerClass() method, the copy constructor you might think would be called at the return is permitted to be optimized away: InnerClass innerClass() { InnerClass ic; std::cout << "innerClass() method" << std::endl; return ic; // this might not call copy ctor }
794,015
794,116
What do people mean when they say C++ has "undecidable grammar"?
What do people mean when they say this? What are the implications for programmers and compilers?
This is related to the fact that C++'s template system is Turing complete. This means (theoretically) that you can compute anything at compile time with templates that you could using any other Turing complete language or system. This has the side effect that some apparently valid C++ programs cannot be compiled; the compiler will never be able to decide whether the program is valid or not. If the compiler could decide the validity of all programs, it would be able to solve the Halting problem. Note this has nothing to do with the ambiguity of the C++ grammar. Edit: Josh Haberman pointed out in the comments below and in a blog post with an excellent example that constructing a parse tree for C++ actually is undecideable. Due to the ambiguity of the grammar, it's impossible to separate syntax analysis from semantic analysis, and since semantic analysis is undecideable, so is syntax analysis. See also (links from Josh's post): C++ grammar: the type name vs object name issue C++ grammar: type vs object and template specializations
794,244
794,261
How should I correct this code that causes "value computed not used" warning?
I have an array of doubles and need to do a calculation on that array and then find the min and max value that results from that calculation. Here is basically what I have: double * array; double result; double myMin; double myMax; // Assume array is initialized properly... for (int i = 0; i < sizeOfArray; ++i) { result = transmogrify(array[i]); if (i == 0) { myMin = result; myMax = result; } else if (result < myMin) { myMin = result; } else if (result > myMax) { myMax = result; } } I'm getting a warning that the value computed for result is never used, and since we treat all warnings as errors, this doesn't compile. How can I fix this code to avoid the warning? I'm using g++ for my compiler. Here's the warning text: cc1plus: warnings being treated as errors foo.cc:<lineno of transmogrify call>: error: value computed is not used Edit: I don't understand the down votes, but I've got things working now. Thanks to everyone for taking the time to help me out.
Assuming you don't need result outside of the loop, you could declare result inside the loop thusly: for( int i=0; i < sizeOfArray; ++i ) { double result = transmogrify( array[i] ); ... }
794,320
794,365
are they adding copy_if to c++0x?
It's very annoying that copy_if is not in C++. Does anyone know if it will be in C++0x?
Since the C++0x is not yet finalized, you can only take a look at the most recent draft.
794,462
794,470
POSIX threads experience? (Or recommend better one)
I am looking for lightweight multi-threading framework for C++. I found POSIX Threads. Please, share you practical experience with POSIX threads: before I start with it I want to know its pros and cons from real people, not from wiki. If you practically compared it with anything (maybe, better), it would be interesting to know either. UPD: cross platform features are really important for me, so I would appreciate this direction described. UPD2: I already have an experience with one framework for QNX / Win32, but it is not lightweight and - oh, I forgot to mention, - it is commercial, not free, but I need a free one.
I found Boost.Threads to be really nice, especially after the 1.35 rewrite. POSIX threads on Windows is not so trivial, and it's a C API, so I would definitely prefer Boost to it. It has all the stuff you need, is portable and requires little setup.
794,601
794,673
Prefix search in a radix tree/patricia trie
I'm currently implementing a radix tree/patricia trie (whatever you want to call it). I want to use it for prefix searches in a dictionary on a severely underpowered piece of hardware. It's supposed to work more or less like auto-completion, i. e. showing a list of words that the typed prefix matches. My implementation is based on this article, but the code therein doesn't include prefix searches, though the author says: [...] Say you want to enumerate all the nodes that have keys with a common prefix "AB". You can perform a depth first search starting at that root, stopping whenever you encounter back edges. But I don't see how that is supposed to work. For example, if I build a radix tree from these words: illness imaginary imagination imagine imitation immediate immediately immense in I will get the exact same "best match" for the prefixes "i" and "in" so that it seems difficult to me to gather all matching words just by traversing the tree from that best match. Additionally, there is a radix tree implementation in Java that has an implemented prefix search in RadixTreeImpl.java. That code explicitly checks all nodes (starting from a certain node) for a prefix match - it actually compares bytes. Can anyone point me to a detailed description on implementing a prefix search on radix trees? Is the algorithm used in the Java implementation the only way to do it?
Think about what your trie encodes. At each node, you have the path that lead you to that node, so in your example, you start at Λ (that's a capital Lambda, this greek font kind of sucks) the root node corresponding to an empty string. Λ has children for each letter used, so in your data set, you have one branch, for "i". Λ Λ→"i" At the "i" node, there are two children, one for "m" and one for "n". The next letter is "n", so you take that, Λ→"i"→"n" and since the only word that starts "i","n" in your data set is "in", there are no children from "n". That's a match. Now, let's say the data set, instead of having "in", had "infindibulum". (What SF I'm referencing is left as an exercise.) You'd still get to the "n" node the same way, but then if the next letter you get is "q", you know the word doesn't appear in your data set at all, because there's no "q" branch. At that point, you say "okay, no match." (Maybe you then start adding the word, maybe not, depending on the application.) But if the next letter is "f", you can keep going. You can short circuit that with a little craft, though: once you reach a node that represents a unique path, you can hang the whole string off that node. When you get to that node, you know that the rest of the string must be "findibulum", so you've used the prefix to match the whole string, and return it. How your you use that? in a lot of non-UNIX command interpreters, like the old VAX DCL, you could use any unique prefix of a command. So, the equivalent of ls(1) was DIRECTORY, but no other command started with DIR, so you could type DIR and that was as good as doing the whole word. If you couldn't remember the correct command, you could type just 'D', and hit (I think) ESC; the DCL CLI would return you all the commands that started with D, which it could search extremely fast.
794,625
794,659
Boost linkage error in Eclipse
I've been banging my head fruitlessly against the wall attempting to include boost's thread functionality in my Eclipse C++ project on Ubuntu. Steps so far: Download boost from boost.org ./configure --with-libraries=system,thread make sudo make install sudo ldconfig -v In the eclipse project, set the include directory to: /usr/local/include/boost-1_38/ In the linker set the library(-l) to "boost_thread" Set the search path (-L) to /usr/local/lib Linker runs, returns with ld error /usr/bin/ld: cannot find -lboost_thread as follows: Invoking: GCC C++ Linker g++ -L/usr/local/lib -o"boostHello3" ./src/boostHello3.o -lboost_thread /usr/bin/ld: cannot find -lboost_thread collect2: ld returned 1 exit status Here are relevant entries from /usr/local/lib: libboost_system-gcc43-mt-1_38.a libboost_system-gcc43-mt-1_38.so libboost_system-gcc43-mt-1_38.so.1.38.0 libboost_system-gcc43-mt.a libboost_system-gcc43-mt.so libboost_thread-gcc43-mt-1_38.a libboost_thread-gcc43-mt-1_38.so libboost_thread-gcc43-mt-1_38.so.1.38.0 libboost_thread-gcc43-mt.a libboost_thread-gcc43-mt.so Here are the contents of /etc/ld.so.conf include /etc/ld.so.conf.d/*.conf /usr/local/lib How is the linker missing this?
Your linker line should be saying -lboost_thread-gcc43-mt-1_38.
794,632
70,814,302
Programmatically get the cache line size?
All platforms welcome, please specify the platform for your answer. A similar question: How to programmatically get the CPU cache page size in C++?
You can use std::hardware_destructive_interference_size since C++17. Its defined as: Minimum offset between two objects to avoid false sharing. Guaranteed to be at least alignof(std::max_align_t)
795,286
795,289
What does the question mark character ('?') mean in C++?
int qempty() { return (f == r ? 1 : 0); } In the above snippet, what does "?" mean? What can we replace it with?
This is commonly referred to as the conditional operator, and when used like this: condition ? result_if_true : result_if_false ... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false. It is syntactic sugar, and in this case, it can be replaced with int qempty() { if(f == r) { return 1; } else { return 0; } } Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.
795,391
795,433
LoadLibrary fails: First chance exception 0xC0000139 (DLL Not Found) - How to debug?
I have a dll "mytest.dll" that when loaded via LoadLibrary(), returns NULL (and 127 as the GetLastError()). If I use DependencyWalker on "mytest.dll", it reports that it should load correctly and that all DLLs are found correctly. Running the profiler option of DependencyWalker on the host exe gives me this relevant section in the log: 00:00:55.099: Loaded "mytest.DLL" at address 0x07860000 by thread 0xBBC. Successfully hooked module. 00:00:55.115: First chance exception 0xC0000139 (DLL Not Found) occurred in "NTDLL.DLL" at address 0x76E24285 by thread 0xBBC. 00:00:55.115: Unloaded "mytest.DLL" at address 0x07860000 by thread 0xBBC. 00:00:55.115: LoadLibraryW("mytest.dll") returned NULL by thread 0xBBC. Error: The specified procedure could not be found (127). Is there a way to debug this to find out what the DLL Not Found message that NTDLL.DLL reports is trying to look for? Or should I be looking elsewhere for the source of the problem? Note that loading this same "mytest.DLL" from another application seems to work correctly.
Could your application be trying to call a specific DLL function via GetProcAddress after the initial load (perhaps) which is not found? Is it a 32 or 64 bit application? If it is loading correctly in another application as you suggest, then it probably has a correct entry point. A quick google search suggests that the error code you are getting back is likely from a missing function name (or specific function's ordinal value) in the DLL. I'd suggest opening the DLL in something like Exescope and inspect the exports list. It might also explain why the DLL works with another application (perhaps the other application uses different exported functions in the DLL)?
795,443
795,482
using BOOST_FOREACH with std::map
I'd like to iterate over a std::map using BOOST_FOREACH and edit the values. I can't quite get it. typedef std::pair<int, int> IdSizePair_t; std::map<int,int> mmap; mmap[1] = 1; mmap[2] = 2; mmap[3] = 3; BOOST_FOREACH( IdSizePair_t i, mmap ) i.second++; // mmap should contain {2,3,4} here Of course this doesn't change anything because I'm not iterating by reference. So I substitute this line instead (as per the example in the Boost docs): BOOST_FOREACH( IdSizePair_t &i, mmap ) and I get the compiler error: error C2440: 'initializing' : cannot convert from 'std::pair<_Ty1,_Ty2>' to 'IdSizePair_t &' with [ _Ty1=const int, _Ty2=int ] Any suggestions?
The problem is with the first member of the pair, which should be const. Try this: typedef std::map<int, int> map_t; map_t mmap; BOOST_FOREACH( map_t::value_type &i, mmap ) i.second++;
795,496
795,534
C++: How is it possible that reading data can affect memory?
I've been going deeper into C++ recently and my bugs seem to get complex. I have a vector of objects, each object contains a vector of floats. I decided I needed to create a further flat array containing all the float values of all objects in one. It's a little more complex than that but the gist of the problem is that as I loop through my objects extracting the float values, at some point my vector of objects is changed, or corrupted in some strange way. (My read operations are all const functions) Another example was with MPI. I was just getting started so I just wanted to run the exact same code on two different nodes with their own memory and with no data transfer happening, all very simple. To my surprise I got segmentation errors and after hours tracking, I found that one assignment of one variable was setting an entirely different variable to NULL. So I am curious, how is it possible that read operations can affect my data structures. Similarly how can a seemingly unrelated operation affect another. I couldn't expect solutions to my problems with those brief descriptions but any advice will be greatly appreciated. Update: Here's a segment of the code, I didn't post originally because I am not sure how much can be extracted from it without understanding the whole system. One thing I just found out though was that when I stopped assigning the value to my flat array and just cout'ed instead, the seg errors disappeared. So perhaps I am declaring my array wrong, but even if I was I'm not sure how it would affect the object vector. void xlMasterSlaveGpuEA::FillFlatGenes() { int stringLength = pop->GetGenome(0).GetLength(); for (int i=0;i<pop->GetPopSize();i++) for (int j=0;j<stringLength;j++) flatGenes[(i*stringLength)+j]<< pop->GetGenome(i).GetFloatGene(j); } float xlVectorGenome::GetFloatGene(unsigned int i) const { return GetGene(i); } my flat array is a member function float * flatFitness; initailsed in the constructor like so: flatFitness = new float(popSize); Update 2: I just want to point out that the two examples above are not related, the first one is not multi threaded. The second MPI example is technically, but MPI is distributed memory and I deliberately attempted the most simple implementation I could think of, which is both machines running code independently. There is however one extra detail, I put in a condtional saying if node 1 then do bottom half of loop if node 1 then do top half Again the memory should be isolated, they should be working as if they know nothing about each other.. but removing this conditional and making both loops do all cubes, eliminates the error
This is not an array constructor: float * flatFitness; flatFitness = new float(popSize); You're creating one float on the heap here, initialized with value popSize. If you want an array of floats you need to use brackets instead of parentheses: float *flatFitness = new float[popSize]; This could easily be causing the problems you describe. Also, remember when you create arrays, you need to delete using delete [] (eventually): delete [] flatFitness; If you just use delete, it might work, but the behavior is undefined. If you want to avoid using array syntax altogether, why not use std::vector? You can create a vector of popSize elements like this: #include <vector> std::vector<float> flatFitness(popSize); This will be freed automatically when it falls out of scope, so you don't have to worry about new or delete. Update (re: comment): If you're already using std::vectors elsewhere in your code, take a look at std::vector::swap(). You may be able to avoid copying things altogether and just swap a couple vectors back and forth between buffering for CUDA and the processing you're doing here.
795,504
795,552
List of study topics
I have experience developing MFC applications with C++ using Visual Studio 6.0. You can guess how long ago that was (hint: going on 10 years). I am trying to update my skills but a lot has changed. How would one go about bringing these skills up to date?
in C++? boost is definitely worth playing with. C# is a good complimentary language. WPF is a good MFC alternative. There have also been improvements to MFC so you can create modern looking apps, worth looking at. Still a number of people who create native code windows apps. pick up a scripting language of somesort, lua, python, ruby... pick up a functional language of somesort, haskell, F#, or something learn about ORMs Design Patterns TDD and Unit testing Refactoring
795,674
795,748
Which are the implications of return a value as constant, reference and constant reference in C++?
I'm learning C++ and I'm still confused about this. What are the implications of return a value as constant, reference and constant reference in C++ ? For example: const int exampleOne(); int& exampleTwo(); const int& exampleThree();
Here's the lowdown on all your cases: • Return by reference: The function call can be used as the left hand side of an assignment. e.g. using operator overloading, if you have operator[] overloaded, you can say something like a[i] = 7; (when returning by reference you need to ensure that the object you return is available after the return: you should not return a reference to a local or a temporary) • Return as constant value: Prevents the function from being used on the left side of an assignment expression. Consider the overloaded operator+. One could write something like: a + b = c; // This isn't right Having the return type of operator+ as "const SomeType" allows the return by value and at the same time prevents the expression from being used on the left side of an assignment. Return as constant value also allows one to prevent typos like these: if (someFunction() = 2) when you meant if (someFunction() == 2) If someFunction() is declared as const int someFunction() then the if() typo above would be caught by the compiler. • Return as constant reference: This function call cannot appear on the left hand side of an assignment, and you want to avoid making a copy (returning by value). E.g. let's say we have a class Student and we'd like to provide an accessor id() to get the ID of the student: class Student { std::string id_; public: const std::string& id() const; }; const std::string& Student::id() { return id_; } Consider the id() accessor. This should be declared const to guarantee that the id() member function will not modify the state of the object. Now, consider the return type. If the return type were string& then one could write something like: Student s; s.id() = "newId"; which isn't what we want. We could have returned by value, but in this case returning by reference is more efficient. Making the return type a const string& additionally prevents the id from being modified.
795,827
797,175
Testing the performance of a C++ app
I'm trying to find a way to test how long it takes a block of C++ code to run. I'm using it to compare the code with different algorithms and under different languages, so ideally I would like a time in seconds / milliseconds. In Java I'm using something like this: long startTime = System.currentTimeMillis(); function(); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; Is there a good way to get an accurate time like that in C++ (Or should I use some other means of benchmarking)?
Use the best counter available on your platform, fall back to time() for portability. I am using QueryPerformanceCounter, but see the comments in the other reply. General advise: The inner loop should run at least about 20 times the resolution of your clock, to make the resolution error < 5%. (so, when using time() your inner loop should run at least 20 seconds) Repeat these measurements, to see if they are consistent. I use an additional outer loop, running ten times, and ignoring the fastest and the slowest measurement for calculating average and deviation. Deviation comes handy when comparing two implementations: if you have one algorithm taking 2.0ms +/-.5, and the other 2.2 +/- .5, the difference is not significant to call one of them "faster". (max and min should still be displayed). So IMHO a valid performance measurement should look something like this: 10000 x 2.0 +/- 0.2 ms (min = 1.2, , max=12.6), 10 repetitions If you know what you are doing, purging the cache and setting thread affinity can make your measurements much more robust. However, this is not without pifalls. The more "stable" the measurement is, the less realistic it is as well. Any implementation will vary strongly with time, depending on the state of data and instruction cache. I'm lazy here, useing the max= value to judge first run penalty, this might not be sufficient for some scenarios.
795,972
826,558
Chi-Squared Probability Function in C++
The following code of mine computes the confidence interval using Chi-square's 'quantile' and probability function from Boost. I am trying to implement this function as to avoid dependency to Boost. Is there any resource where can I find such implementation? #include <boost/math/distributions/chi_squared.hpp> #include <boost/cstdint.hpp> using namespace std; using boost::math::chi_squared; using boost::math::quantile; vector <double> ConfidenceInterval(double x) { vector <double> ConfInts; // x is an estimated value in which // we want to derive the confidence interval. chi_squared distl(2); chi_squared distu((x+1)*2); double alpha = 0.90; double lower_limit = 0; if (x != 0) { chi_squared distl(x*2); lower_limit = (quantile(distl,((1-alpha)/2)))/2; } double upper_limit = (quantile(distu,1-((1-alpha)/2)))/2; ConfInts.push_back(lower_limit); ConfInts.push_back(upper_limit); return ConfInts; }
If you're looking for source code you can copy/paste, here are some links: AlgLib Koders YMMV...
795,987
797,405
C++ iterators & loop optimization
I see a lot of c++ code that looks like this: for( const_iterator it = list.begin(), const_iterator ite = list.end(); it != ite; ++it) As opposed to the more concise version: for( const_iterator it = list.begin(); it != list.end(); ++it) Will there be any difference in speed between these two conventions? Naively the first will be slightly faster since list.end() is only called once. But since the iterator is const, it seems like the compiler will pull this test out of the loop, generating equivalent assembly for both.
I'll just mention for the record that the C++ standard mandates that calling begin() and end() on any container type (be it vector, list, map etc.) must take only constant time. In practice, these calls will almost certainly be inlined to a single pointer comparison if you compile with optimisations turned on. Note that this guarantee does not necessarily hold for additional vendor-supplied "containers" that do not actually obey the formal requirements of being a container laid out in the chapter 23 of the standard (e.g. the singly-linked list slist).
796,099
804,935
C++ new operator thread safety in linux and gcc 4
Soon i'll start working on a parallel version of a mesh refinement algorithm using shared memory. A professor at the university pointed out that we have to be very careful about thread safety because neither the compiler nor the stl is thread aware. I searched for this question and the answer depended on the compiler (some try to be somewhat thread-aware) and the plattform (if the system calls used by the compiler are thread-safe or not). So, in linux, the gcc 4 compiler produces thread-safe code for the new operator? If not, what is the best way to overcome this problem? Maybe lock each call to the new operator?
You will have to look very hard to find a platform that supports threads but doesn't have a thread safe new. In fact, the thread safety of new (and malloc) is one of the reasons it's so slow. If you want a thread safe STL on the other hand, you may consider Intel TBB which has thread aware containers (although not all operations on them are thread safe).
796,106
796,117
Replacing getpid with my own implementation
I have an application where I need to write a new getpid function to replace the original one of the OS. The implementation would be similar to: pid_t getpid(void) { if (gi_PID != -1) { return gi_PID; } else { // OS level getpid() function } } How can I call the original getpid() implementation of the OS through this function? EDIT: I tried: pid_t getpid(void) { if (gi_PID != -1) { return gi_PID; } else { return _getpid(); } } as Jonathan has suggested. This gave me the following errors when compiling with g++: In function pid_t getpid()': SerendibPlugin.cpp:882: error: _getpid' undeclared (first use this function) SerendibPlugin.cpp:882: error: (Each undeclared identifier is reported only once for each function it appears in.) EDIT 2: I've managed to get this to work by using a function pointer and setting it to the next second symbol with the id "getpid", using dlsym(RTLD_NEXT, "getpid"). Here's my sample code: vi xx.c "xx.c" 23 lines, 425 characters #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <iostream> #include <dlfcn.h> using namespace std; pid_t(*___getpid)(); pid_t getpid(void) { cout << "My getpid" << endl; cout << "PID :" << (*___getpid)() << endl; return (*___getpid)(); } int main(void) { ___getpid = (pid_t(*)())dlsym(RTLD_NEXT, "getpid"); pid_t p1 = getpid(); printf("%d \n", (int)p1); return(0); } g++ xx.c -o xout My getpid PID :7802 7802
On many systems, you will find that getpid() is a 'weak symbol' for _getpid(), which can be called in lieu of getpid(). The first version of the answer mentioned __getpid(); the mention was removed swiftly since it was erroneous. This code works for me on Solaris 10 (SPARC) - with a C++ compiler: #include <sys/types.h> #include <unistd.h> #include <stdio.h> extern "C" pid_t _getpid(); pid_t getpid(void) { return(-1); } int main(void) { pid_t p1 = getpid(); pid_t p2 = _getpid(); printf("%d vs %d\n", (int)p1, (int)p2); return(0); } This code works for me on Solaris 10 (SPARC) - with a C compiler: Black JL: cat xx.c #include <sys/types.h> #include <unistd.h> #include <stdio.h> pid_t getpid(void) { return(-1); } int main(void) { pid_t p1 = getpid(); pid_t p2 = _getpid(); printf("%d vs %d\n", (int)p1, (int)p2); return(0); } Black JL: make xx && ./xx cc xx.c -o xx "xx.c", line 13: warning: implicit function declaration: _getpid -1 vs 29808 Black JL:
796,198
796,252
How to create a boost thread with data?
I'm running into some issues with boost::bind and creating threads. Essentially, I would like to call a "scan" function on a "Scanner" object, using bind. Something like this: Scanner scanner; int id_to_scan = 1; boost::thread thr1(boost::bind(&scanner::scan)); However, I'm getting tripped up on syntax. How do I pass the data into scan? As part of the constructor?
Keep in mind that the first argument to any member function is the object. So if you wanted to call: scanner* s; s->scan() with bind you would use: boost::bind(&scanner::scan, s); If you wanted to call: s->scan(42); use this: boost::bind(&scanner::scan, s, 42); Since I often want bind to be called on the object creating the bind object, I often do this: boost::bind(&scanner::scan, this); Good luck.
796,321
796,330
Strange C++ std::string behavior... How can I fix this?
This is driving me nuts. I have been at it for over 2 hours trying to figure this out... Here is my problem. I am working on a fairly large program that works with Bayesian networks. Here is the main function: using namespace std; int main() { DSL_network net; initializeNetwork(net); setEvidence(net); net.SetDefaultBNAlgorithm(7); net.SetNumberOfSamples(80000); cout << "Samples:\t" << net.GetNumberOfSamples() << endl; updateEvidence(net); //net.WriteFile("test.dsl"); return(DSL_OKAY); } This all works fine. The problem comes when I want to print out a string: using namespace std; int main() { //simple string creation string a = "test"; //should print out "test" cout << a << endl; DSL_network net; initializeNetwork(net); setEvidence(net); net.SetDefaultBNAlgorithm(7); net.SetNumberOfSamples(80000); cout << "Samples:\t" << net.GetNumberOfSamples() << endl; updateEvidence(net); //net.WriteFile("test.dsl"); return(DSL_OKAY); } Here is the output (just from printing the string a...):    ▀ÇΦy♠≈6 ♦ What could be going on? UPDATE: int main() { //simple string creation string a = "test"; //should print out "test" cout << a << endl; return(DSL_OKAY); } still prints ▀ÇΦy♠≈6 ♦ BIG UPDATE: Here is the recent. I created a brand new project and pasted the code that Neil Butterworth posted (thanks btw). I ran the code and it printed correctly. Then I added the two .lib files to the Linker in the new project (smile.lib for the SMILE library, and wsock32.lib for socket use.) I tried the code again, and it printed the first "test" correctly, then it printed the giberish. It is a problem with one of the .libs I am linking together. I tried each on their own to see if they are just clashing, and it seems that the smile.lib library is causing the problem. I will need to go into their documentation and figure out why. Any ideas? Thanks all for the help Thanks
That's bizarre. I always like to break a problem down to it's minimal case. What does the following program do when you run it? using namespace std; int main() { string a = "test"; cout << a << endl; return 0; } If that works, then there's something else wrong and you need to add in one line at a time until it fails. Then examine that line very carefully ("I'm hunting wabbits"). Based on your edit, it may be a different string class being used. Try this: int main() { std::string a = "test"; std::cout << a << std::endl; return 0; } Update: Since it works in a new project and not the current one, check the following. Make sure you're linking with the standard C++ runtimes. make sure you don't #define string as something else (and the includes a -Dstring=somethingelse command line option to the compiler). check the behavior using std::string, not just string.
796,364
796,462
Fast Cross-Platform C/C++ Image Processing Libraries
What are some cross platform and high performance image libraries for image processing (resizing and finding the color/hue histograms). No gui needed. This is for C/C++. So far I have looked in to OpenCV GIL as part of Boost DevIL CImg My questions How's the performance of the ones I have listed above What are some other libraries Your input much appreciated.
OpenCV has quite good performance. It should be sufficient for most cases. To improve performance, you can also use OpenCV together with Intel IPP, which is however a non-free commercial product. If OpenCV detects that IPP is installed it will use it where possible. As a third option you can use IPP directly. IPP was designed with high performance (on Intel architectures) as a goal. It is optimized to use the intel SIMD instructions.
797,079
797,083
How do I declare an array of strings in C++?
In C++ how can I declare an array of strings? I tried to declare it as an array of char but that was not correct.
#include <string> std::string my_strings[100]; That is C++, using the STL. In C, you would do it like this: char * my_strings[100]; This reads as "my strings is an array of 100 pointer to char", and the latter is how strings are represented in C.
797,230
797,418
Qt4 existing slots are not recognized
I am currently trying to complete a project using Qt4 and C++. I am using buttons to switch between states. While trying to connect the buttons' clicked() signals to the textEdit to display the relevant state, I got stuck on an error: Object::connect No such slot QTextEdit::append("move state") Object::connect No such slot QTextEdit::append("link state") Only, QTextEdit definitely has an append(QString) slot. Any ideas? Some code samples: QPushButton *move = new QPushButton("Move"); connect(move, SIGNAL(clicked()), textEdit, SLOT(append("move state")));
You can't pass in an argument (literally) to the append() slot when making a signal to slot connection. You refer to it like a method signature: SLOT(append(QString)) //or const QString, I'm not sure If you need the textbox to append the words "move state" every time that button is clicked, then you should define your own slot that will do the append.
797,574
797,580
Resources for C++ Templates
I'm new to C++ Templates, and am finding it hard to understand and debug them. What are some good resources for doing both/either?
I recommend the excellent book C++ Templates - The Complete Guide by Vandevoorde and Josuttis.
797,582
797,597
Strange output after reading from a file
Using this code, the following execution yields strange results: C 100 R W The text file's first line defines the number of elements to read from it, and it contains a few values under 15, but every time I run this, the first value in my array is always printed out as 87 (the ASCII value for 'W'). If I change the 'W' functionality to 'X', then the first result in the array is 88. #include <iostream> #include <fstream> using namespace std; int arrayLength; class ELEMENT { public: int key; }; class HEAP { public: int capacity; int size; ELEMENT H []; }; HEAP initialize(int n) { HEAP h; h.capacity = n; h.size = 0; return h; } void buildHeap(HEAP &h, ELEMENT *a) { h.size = arrayLength; for (int i = 1; i <= arrayLength; i++) { h.H[i] = a[i]; } for (int i = h.size/2; i >= 1; i--) { // HEAPIFY HERE } } void printHeap(HEAP &h) { cout << "Capacity:\t" << h.capacity << endl; cout << "Size:\t\t" << h.size << endl; cout << "|"; for (int i = 1; i <= h.size; i++) { cout << " "; cout << h.H[i].key << " |"; } cout << endl; } int main() { char c; int val; HEAP h; while (c != 'S') { cin >> c; switch (c) { case 'S': break; case 'C': cin >> val; h = initialize(val); break; case 'W': printHeap(h); break; case 'R': { ifstream infile; infile.open("HEAPinput.txt"); infile >> arrayLength; ELEMENT* a = new ELEMENT[arrayLength]; for (int i = 1; i <= arrayLength; i++) infile >> a[i].key; infile.close(); buildHeap(h, a); } break; } } return 0; } It is being compiled using g++ on a Unix server. EDIT: To clarify: With a text file with the following contents (space = new line): 12 9 10 11 12 8 7 6 5 4 3 2 1 The output is: Capacity: 100 Size: 12 | 87 | 10 | 11 | 12 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | So it's working except for that first element.
Whatever you think ELEMENT H []; is doing, it probably isn't. C++ does not support dynamic arrays - you need to use the std::vector class. And BTW, C++ by convention uses UPPERCASE to name pre-processor macros and constants. You should use mixed case to name your classes.
797,594
797,632
When a compiler can infer a template parameter?
Sometimes it works sometimes not: template <class T> void f(T t) {} template <class T> class MyClass { public: MyClass(T t) {} }; void test () { f<int>(5); MyClass<int> mc(5); f(5); MyClass mc(5); // this doesn't work } Is there a way to hack around the example above? I.e. force the compiler to infer the template parameter from constructor parameter. Will this be fixed in the future, or is there a good reason not to? What is the general rule when compiler can infer template parameter?
Template parameters can be inferred for function templates when the parameter type can be deduced from the template parameters So it can be inferred here: template <typename T> void f(T t); template <typename T> void f(std::vector<T> v); but not here: template <typename T> T f() { return T(); } And not in class templates. So the usual solution to your problem is to create a wrapper function, similar to the standard library function std::make_pair: template <class T> class MyClass { public: MyClass(T t) {} void print(){ std::cout<<"try MyClass"<<std::endl; } }; template <typename T> MyClass<T> MakeMyClass(T t) { return MyClass<T>(t); } and then call auto a = MakeMyClass(5); to instantiate the class.
797,967
798,003
How to stop EnumWindows running infinitely win32
The code worked all along. Somehow I manage to get Visual C++ Express not hit the break point on the final return statement and it appeared to run for ever. In the example code bellow EnumWindows enumerates infinitely. How can one make it stop after all windows has been enumerated. #include <Windows.h> BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam) { TCHAR buff[255]; if (IsWindowVisible(hWnd)) { GetWindowText(hWnd, (LPWSTR) buff, 254); printf("%S\n", buff); } return TRUE; } int _tmain(int argc, _TCHAR* argv[]) { EnumWindows(EnumWindowsProc, 0); return 0; }
Your code works for me, once I removed the wide-character stuff and added #include <stdio.h> to get the printf() declaration. What output does it produce on your system? The code that works for me is: #include <windows.h> #include <stdio.h> BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) { char buff[255]; if (IsWindowVisible(hWnd)) { GetWindowText(hWnd, (LPSTR) buff, 254); printf("%s\n", buff); } return TRUE; } int main() { EnumWindows(EnumWindowsProc, 0); return 0; }
798,002
798,641
filling a boost vector or matrix
Is there a single-expression way to assign a scalar to all elements of a boost matrix or vector? I'm trying to find a more compact way of representing: boost::numeric::ublas::c_vector<float, N> v; for (size_t i=0; i<N; i++) { v[i] = myScalar; } The following do not work: boost::numeric::ublas::c_vector<float, N> v(myScalar, myScalar, ...and so on..., myScalar); boost::numeric::ublas::c_vector<float, N> v; v = myScalar;
Because the vector models a standard random access container you should be able to use the standard STL algorithms. Something like: c_vector<float,N> vec; std::fill_n(vec.begin(),N,0.0f); or std::fill(vec.begin(),vec.end(),0.0f); It probably also is compatible with Boost.Assign but you'd have to check.
798,013
798,091
Segmentation fault on string assignment in C++
Take a look at this example function: RuntimeConfiguration* conf_rt_conf() { RuntimeConfiguration *conf; conf = new RuntimeConfiguration(); conf->arch_path="./archive"; conf->err_log="./err_log"; conf->fail_log="./fail_log"; conf->msg_log="./msg_log"; conf->save="html, htm, php"; conf->ignore="jpg, gif"; conf->cookies=""; return conf; } Everything here works fine, but when I run something like this: DatabaseInput** conf_db_input() { DatabaseInput **db_input; db_input=(DatabaseInput **)malloc(NUMB_SITES*sizeof(DatabaseInput *)); for (int i=0;i<NUMB_SITES;i++) db_input[0]= new DatabaseInput(); db_input[0]->full_name="ABCNews"; db_input[0]->alias="abcn"; db_input[0]->prefix="/eng"; db_input[1]->full_name="Rzeczpospolita"; db_input[1]->alias="rp"; db_input[1]->prefix="/pol"; return db_input; } I get segmentation fault on first assignment. It probably has something to do with the fixed memory block allocated for this struct. How do I get it to work properly?
Maybe this: DatabaseInput *db_input[]; db_input = new DatabaseInput*[NUMB_SITES]; // Creates an array of pointers for (int i=0; i<NUMB_SITES; i++) db_input[i]= new DatabaseInput(); could work? (I didn't test it) Note, to free the memory used, you should do something like: for (int i=0; i<NUMB_SITES; i++) delete db_input[i]; delete[] db_input;
798,410
798,465
Multi-threading strategies? (Modifying a scene in a multi-threaded engine through an Editor)
I'm trying to write an editor overtop a multi-threaded game engine. In theory, through the editor, the contents of the scene can be totally changed but I haven't been able to come up with a good way for the engine to cope with the changes. (ie delete an entity while the renderer was drawing it). Additionally, I'm hesitant to write code to manage locks at every instance I use an entity or resource that can be potentially deleted. I imagine there has to be a relatively more elegant solution. Does anyone have any ideas or strategies I can start looking at? Thanks!
In addition to the two-stage process suggested by @lassevk you could use a Pipe structure to "push" commands to the renderer so that these changes gets the form of another work item for the render engine. For example, say your engine follows a workflow like: Calculate positions Process Physics Process Lights Process Cameras Render Scene You could just add a new item to the workflow in the position 0, called Process Changes which pulls out the information from the Pipe and incorporates it to the scene.
798,497
860,350
How do I check for an unmangled C++ symbol when building a PHP extension?
I have a PHP module written in C++, which relies on a C++ library (Boost Date_Time) being installed. Currently, in my config.m4 file I'm checking for the library as follows: LIBNAME=boost_date_time LIBSYMBOL=_ZN5boost9gregorian9bad_monthD0Ev PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,, [ AC_MSG_ERROR([lib $LIBNAME not found. Try: sudo apt-get install libboost-dev]) ],[ -lstdc++ -ldl ]) Now, this works in my current environment, but I'm painfully aware this will probably break on a different version of the library or compiler. How can I get automake to understand the non-mangled C++ symbol? Edit: I realise that checking on the mangled name is horrible, but is there not some way of checking for the symbol name as returned by "nm -C" (eg boost::gregorian::bad_month etc). I found some refence to the automake command AC_LANG_CPLUSPLUS(), but I'm not sure how to use it and whether it's applicable here.
You can check AC_TRY_COMPILE with something like that: LIBNAME=boost_date_time AC_MSG_CHECKING([for BOOST]) AC_TRY_COMPILE( [ #include "boost/date_time/gregorian/greg_month.hpp" ], [ boost::gregorian::bad_month* bm = new boost::gregorian::bad_month; ], [ AC_MSG_RESULT(yes) ], [ AC_MSG_ERROR([lib $LIBNAME not found. Try: sudo apt-get install libboost-dev]) ]) This avoid the use of unmangled symbol.
798,612
798,635
Syntax for dereferencing a pointer in C (or C++)
I had a colleague check in code like this in C (syntax #1): (*(*(*p_member).p_member).p_member).member When I asked him why he didn't use -> (syntax #2): p_member->p_member->p_member->member he got really defensive stating that syntax #2 is more complicated than #1...I ended up changing his code because I had to modify it and couldn't read it, then he got mad that I actually touched it... Which syntax does the SO community prefer? Both are valid, but I find syntax #2 more readable. I'm setting this to community wiki due to the question being subjective.
The technical term for syntax # 1 is "nuts." That said, I'd worry a little about code that has to go indirect 3 times too.
798,798
798,825
ifstream::open not working in Visual Studio debug mode
I've been all over the ifstream questions here on SO and I'm still having trouble reading a simple text file. I'm working with Visual Studio 2008. Here's my code: // CPPFileIO.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <fstream> #include <conio.h> #include <iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { ifstream infile; infile.open("input.txt", ifstream::in); if (infile.is_open()) { while (infile.good()) cout << (char) infile.get(); } else { cout << "Unable to open file."; } infile.close(); _getch(); return 0; } I have confirmed that the input.txt file is in the correct "working directory" by checking the value of argv[0]. The Open method just won't work. I'm also having trouble debugging- should I not be able to set a watch on infile.good() or infile.is_open()? I keep getting Error: member function not present. EDIT: Updated code listing with full code from .CPP file. UPDATE: The file was NOT in the Current Working Directory. This is the directory where the project file is located. Moved it there and it works when debugging in VS.NET.
Try using the bitwise OR operator when specifying the open mode. infile.open ("input.txt", ios::ate | ios::in); The openmode parameter is a bitmask. ios::ate is used to open the file for appending, and ios::in is used to open the file for reading input. If you just want to read the file, you can probably just use: infile.open ("input.txt", ios::in); The default open mode for an ifstream is ios::in, so you can get rid of that altogether now. The following code is working for me using g++. #include <iostream> #include <fstream> #include <cstdio> using namespace std; int main(int argc, char** argv) { ifstream infile; infile.open ("input.txt"); if (infile) { while (infile.good()) cout << (char) infile.get(); } else { cout << "Unable to open file."; } infile.close(); getchar(); return 0; }
798,876
803,982
How do I get an error message when failing to load a JVM via JNI?
I would like to retrieve an error message that explains why the jvm failed to load. From the examples provided here: http://java.sun.com/docs/books/jni/html/invoke.html I extracted this example: /* Create the Java VM */ res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if (res < 0) { // retrieve verbose error here? fprintf(stderr, "Can't create Java VM\n"); exit(1); } In my specific case I'm providing invalid arguments in the vm_args and would expect to see what I get on the command line: "Unrecognized option: -foo=bar" On further testing it looks like the jvm is putting the message I want to stdout or stderr. I believe I would need to capture stdout and stderr to get the error I'm looking for (unless of course there is a simpler way). I'm coding in C++ so if someone can show a way to capture the error into a stringstream that would be ideal. Thanks, Randy
I was able to get what I needed by using the "vfprintf" option described here: https://web.archive.org/web/20111229234347/http://java.sun.com/products/jdk/faq/jnifaq-old.html although I used the jdk1.2 options. This code snippet summarizes my solution: static string jniErrors; static jint JNICALL my_vfprintf(FILE *fp, const char *format, va_list args) { char buf[1024]; vsnprintf(buf, sizeof(buf), format, args); jniErrors += buf; return 0; } ... JavaVMOption options[1]; options[0].optionString = "vfprintf"; options[0].extraInfo = my_vfprintf; JavaVMInitArgs vm_args; memset(&vm_args, 0, sizeof(vm_args)); vm_args.nOptions = 1; vm_args.options = options; vm_args.version = JNI_VERSION_1_4; vm_args.ignoreUnrecognized = JNI_FALSE; JNIEnv env; JavaVM jvm; jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if (res != JNI_OK) setError(jniErrors); jniErrors.clear(); Also interesting was that I could not for the life of me capture stdout or stderr correctly with any of the freopen or dup2 tricks. I could load my own dll and redirect correctly but not the jvm. Anyway, it's better this way because I wanted the errors in memory rather than in a file.
799,068
799,078
What should i know about UDP programming?
I don't mean how to connect to a socket. What should I know about UDP programming? Do I need to worry about bad data in my socket? I should assume if I send 200bytes I may get 120 and 60 bytes separately? Should I worry about another connection sending me bad data on the same port? If data doesnt arrive typically how long may I (typically) not see data for (250ms? 1 second? 1.75sec?) What do I really need to know?
"i should assume if i send 200bytes i may get 120 and 60bytes separately?" When you're sending UDP datagrams your read size will equal your write size. This is because UDP is a datagram protocol, vs TCP's stream protocol. However, you can only write data up to the size of the MTU before the packet could be fragmented or dropped by a router. For general internet use, the safe MTU is 576 bytes including headers. "i should worry about another connection sending me bad data on the same port?" You don't have a connection, you have a port. You will receive any data sent to that port, regardless of where it's from. It's up to you to determine if it's from the right address. If data doesnt arrive typically how long may i (typically) not see data for (250ms? 1 second? 1.75sec?) Data can be lost forever, data can be delayed, and data can arrive out of order. If any of those things bother you, use TCP. Writing a reliable protocol on top of UDP is a very non trivial task and there is no reason to do so for almost all applications.
799,076
799,210
Returning a std::string from a C++ DLL to a c# program -> Invalid Address specified to RtlFreeHeap
In a function in my C++ DLL, I'm returning a std::string to my c# application. It pretty much looks like this: std::string g_DllName = "MyDLL"; extern "C" THUNDER_API const char* __stdcall GetDLLName() { return g_DllName.c_str(); } But when my C# code calls this function, I get this message in my output window: Invalid Address specified to RtlFreeHeap( 00150000, 0012D8D8 ) The function declaration in c# looks like this: [DllImport("MyDll", EntryPoint = "GetDLLName")] [return: MarshalAs(UnmanagedType.LPStr)] public static extern string GetDLLName(); From what I've been able to find online, sometimes this message appears when there's an inconsistency between which version of new(debug or release, etc) is being used with delete. But I'm not sure if that is what is going on in my case. So I'm not sure exactly what's causing it. Maybe the MashallAs might have something to do with it? Any ideas? Thanks!
I managed to find the issue. It was the way the C# definition was done. From what I can understand, using the MarshallAs(UnmanagedType.LPStr) in combination with the string return type makes it so that it'll attempt to free the string when its done. But because the string comes from the C++ DLL, and most likely a totally different memory manager, it fails. And even if it didn't fail, I don't want it to be freed anyway. The solution I found was to change the C# declaration to this (the C++ code is unchanged): [DllImport("MyDll", EntryPoint = "GetDLLName")] public static extern IntPtr GetDLLName(); So this makes it so that it just returns a pointer to the string data. And then to change it to a string, pass it to Marshal.PtrToStringAnsi() return Marshal.PtrToStringAnsi(GetDLLName()); And that gets wrapped into another function for cleanliness. I found the solution from this page: http://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=1108
799,090
799,196
Tracing MFC message handling
Trying to upgrade an MFC app to use the new MFC feature pack, we are loosing the messages from a context menu. The menu appears and can be clicked, but the message seems not to be handled anywhere. We overrode OnCmdMsg() in lots of places but to no avail, the context menu's command message are not caught. Is there a way, tool, or approach to trace messages? Any other ideas how to solve this problem?
Try SPY++ > ...can be found on the Programs or All Programs menu in Windows. Click Microsoft Visual Studio 9.0, and then click Visual Studio Tools. Provides a graphical view of the processes, threads, windows, and window messages of a system. For more information, click Help in the tool. I explain more in this answer about Spy++ for 2005.
799,314
799,342
Difference between erase and remove
I am bit confused about the difference between the usage of std::remove algorithm. Specifically I am not able to understand what is being removed when I use this algorithm. I wrote a small test code like this: std::vector<int> a; a.push_back(1); a.push_back(2); std::remove(a.begin(), a.end(), 1); int s = a.size(); std::vector<int>::iterator iter = a.begin(); std::vector<int>::iterator endIter = a.end(); std::cout<<"Using iter...\n"; for(; iter != endIter; ++iter) { std::cout<<*iter<<"\n"; } std::cout<<"Using size...\n"; for(int i = 0; i < a.size(); ++i) { std::cout<<a[i]<<"\n"; } The output was 2,2 in both the cases. However, if I use erase with the remove something like this: a.erase(std::remove(a.begin(), a.end(), 1), a.end()); I get the output as 2. So my questions are: (1). Is there any use of std::remove other than using it with erase function. (2). Even after doing std::remove, why a.size() returns 2 and not 1? I read the item in Scott Meyer's Effective STL book about the erase-remove idiom. But am still having this confusion.
remove() doesn't actually delete elements from the container -- it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that remove() is designed to work on not just a container but on any arbitrary forward iterator pair: that means it can't actually delete the elements, because an arbitrary iterator pair doesn't necessarily have the ability to delete elements. For example, pointers to the beginning and end of a regular C array are forward iterators and as such can be used with remove(): int foo[100]; ... remove(foo, foo + 100, 42); // Remove all elements equal to 42 Here it's obvious that remove() cannot resize the array!
799,558
799,581
Generating data structures by parsing plain text files
I wrote a file parser for a game I'm writing to make it easy for myself to change various aspects of the game (things like the character/stage/collision data). For example, I might have a character class like this: class Character { public: int x, y; // Character's location Character* teammate; } I set up my parser to read in from a file the data structure with syntax similar to C++ Character Sidekick { X = 12 Y = 0 } Character AwesomeDude { X = 10 Y = 50 Teammate = Sidekick } This will create two data structures and put them in a map<std::string, Character*>, where the key string is whatever name I gave it (in this case Sidekick and AwesomeDude). When my parser sees a pointer to a class, like the teammate pointer, it's smart enough to look up in the map to fetch the pointer to that data structure. The problem is that I can't declare Sidekick's teammate to be AwesomeDude because it hasn't been placed into the Character map yet. I'm trying to find the best way to solve this so that I can have my data structures reference objects that haven't yet been added to the map. The two easiest solutions that I can think of are (a) add the ability to forward declare data structures or (b) have the parser read through the file twice, once to populate the map with pointers to empty data structures and a second time to go through and fill them in. The problem with (a) is that I also can decide which constructor to call on a class, and if I forward declare something I'd have to have the constructor be apart from the rest of the data, which could be confusing. The problem with (b) is that I might want to declare Sidekick and AwesomeDude in their own files. I'd have to make my parser be able to take a list of files to read rather than just one at a time (this isn't so bad I guess, although sometimes I might want to get a list of files to read from a file). (b) also has the drawback of not being able to use data structures declared later in the constructor itself, but I don't think that's a huge deal. Which way sounds like a better approach? Is there a third option I haven't thought of? It seems like there ought to be some clever solution to this with pointer references or binding or something... :-/ I suppose this is somewhat subjective based on what features I want to give myself, but any input is welcome.
When you encounter the reference the first time, simply store it as a reference. Then, you can put the character, or the reference, or whatever on a list of "references that need to be resolved later". When the file is done, run through those that have references and resolve them.
799,599
799,877
C++ custom stream manipulator that changes next item on stream
In C++, to print a number in hexadecimal you do this: int num = 10; std::cout << std::hex << num; // => 'a' I know I can create a manipulator that just adds stuff to the stream like so: std::ostream& windows_feed(std::ostream& out) { out << "\r\n"; return out; } std::cout << "Hello" << windows_feed; // => "Hello\r\n" However, how can I create a manipulator that, like 'hex', modifies items to come on the stream? As a simple example, how would I create the plusone manipulator here?: int num2 = 1; std::cout << "1 + 1 = " << plusone << num2; // => "1 + 1 = 2" // note that the value stored in num2 does not change, just its display above. std::cout << num2; // => "1"
First, you have to store some state into each stream. You can do that with the function iword and an index you pass to it, given by xalloc: inline int geti() { static int i = ios_base::xalloc(); return i; } ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; } ostream& add_none(ostream& os) { os.iword(geti()) = 0; return os; } Having that in place, you can already retrieve some state in all streams. Now, you just have to hook into the respective output operation. Numeric output is done by a facet, because it potentially is locale dependent. So you can do struct my_num_put : num_put<char> { iter_type do_put(iter_type s, ios_base& f, char_type fill, long v) const { return num_put<char>::do_put(s, f, fill, v + f.iword(geti())); } iter_type do_put(iter_type s, ios_base& f, char_type fill, unsigned long v) const { return num_put<char>::do_put(s, f, fill, v + f.iword(geti())); } }; Now, you can test the stuff. int main() { // outputs: 11121011 cout.imbue(locale(locale(),new my_num_put)); cout << add_one << 10 << 11 << add_none << 10 << 11; } If you want that only the next number is incremented, just set the word to 0 again after each call to do_put.
799,780
799,850
Signal-slot architecture best practice
I am using libsigc++ to wire up an application, and is uncertain as to the easier way of going about it. There is a preexisting object hierarchy that manages the data layer, and the top level object exposes all functions. All good so far. To this I am adding a GUI object hierarchy, and in the application object I am hooking them together with signal connections. To make a connection, I need pointers to both sender and receiver. Now, do I hook in a child widget, far down in the tree, directly, thus requiring pointers to be passed up and down the tree? Or, do I go through the painstaking processes of hooking in signals and slots at every step in the chain? On the one hand, passing pointers break the separation that the sig-slot model buys you. On the other hand, creating connections at every step does not seem to rhyme with the supposed "event telepathy" that the sig-slots are supposed to provide. Which one would someone experienced with this model consider the default approach?
Personally, I don't see any problem by 'skipping' layers with the signal/slots mechanism. I prefer to see it this way: a component is sending signals into the wild, and whoever is interested in those signals may listen to them. A couple of tips: avoid to send signals that are too generic, and don't rely on the order of execution of the slots (if many slots are called for a given signal).
799,932
800,011
Fast Cross-Platform C/C++ Hashing Library
What's a high performance hashing library that's also cross platform for C/C++. For algorithms such as MD5, SHA1, CRC32 and Adler32. I initially had the impression that Boost had these, but apparently not (yet). The most promising one I have found so far is Crypto++, any other suggestions? http://www.cryptopp.com/ This seems to be quite comprehensive.
For usual crypto hashes (MD?, SHA? etc.), openssl is the most portable and probably fastest. None of the hashes you mentioned are good for high performance data structures like hash tables. The recommended hash functions for these data structures these days are: FNV, Jenkins and MurmurHash.
800,137
800,169
Beginner for loop problem
[EDIT]Whoops there was a mistake in the code, and now all the responses to the question seem bizzare, but basically the for loop used to be, for(i=0; i<15; i++). I also edited to make the question more clear.[/EDIT] I am trying to make a for loop, that checks a 16 element array, so it loops from 0 to 15. I then use the i variable later, however sometimes i == 16, which causes problems by being out of bounds. I have a solution but it doesnt seem elegant, which makes me think I am missing something. I've tried while loops, but I can never get any loop to go from 0 to 15, and never end at a value greater than 15. Is there any way to make a loop go and check all 16 elements of the array, while never being greater than 15 at the end of the loop? int i; for(i=0; i<16; i++) { someClass.someMethod(i); if(someClass.Test()) { break; } } if (i == 16) { i = 15; }
I suggest using some other variable other than i after your loop is finished. The criteria of using a for loop instead of a while loop is that you know beforehand exactly how many times a for loop will execute. If you already know this, just set some other variable to the ending value of your loop and use it instead of giving i a dual purpose. int j = 15; for(int i=0; i <= j; i++) { someClass.array[i]; } // continue on using j, which value hasn't changed
800,368
800,384
Declaring an object before initializing it in c++
Is it possible to declare a variable in c++ without instantiating it? I want to do something like this: Animal a; if( happyDay() ) a( "puppies" ); //constructor call else a( "toads" ); Basially, I just want to declare a outside of the conditional so it gets the right scope. Is there any way to do this without using pointers and allocating a on the heap? Maybe something clever with references?
You can't do this directly in C++ since the object is constructed when you define it with the default constructor. You could, however, run a parameterized constructor to begin with: Animal a(getAppropriateString()); Or you could actually use something like the ?: operator to determine the correct string. (Update: @Greg gave the syntax for this. See that answer)
800,576
800,588
Learn C# to transition to C/C++?
Alright, so I just took an introductory class into Computer Science and the school's language choice was Java (I have basic knowledge of concepts like polymorphism, encapsulation, etc..). I want to learn C++ then C (I hear that one should learn C++ first then go to C), and was wondering if C# is a nice transitional language because of the language similarities between Java and C#. So will learning C# first help me get a better understanding of C++ later? I appreciate any help. Thank you.
Doubtful. C# is not significantly more C++-like than Java. It does support pointers in unsafe code, but beyond that I can't think of any reason it would make an especially good bridge from Java to C++. Also that is a feature I suspect more likely to be used by developers coming from the other direction. If you have other reasons for learning C# I say go for it, but for the purposes of transitioning more easily to C++, I'd say skip it.
800,734
800,760
What's behind the CAsyncSocket assertion problems and "improper argument" errors in my MFC sockets code?
I was asked to look at some code for a friend. (I rightly hesitated due to the MFC and lots of bad code, but he won...) This is a dialog box based application that uses a CAsyncSocket. The problem manifests in some nonstop debugbreaks and other similar things - there are also problem with an MFC ENSURE() macro - checking the socket for nullness. All of the issues happen deep in MFC. Some googling showed up possible resource leaks if one uses themes in Vista/XP, but I don't think that is the problem here. The code is pretty poor based on my couple hours of debugging, but basically it is doing the following: (When connection is established there is no problem - it is only the case when no connection) Calls Connect(server, socket) (on the derived CAsyncSocket object) In the OnConnect() we are notified that connection did not work/not connected. Inside a window timer for the main dialog/app there is a timer. When the timer event/handler is called we check if connected. If we have detected that we are not connected (the OnConnect() was not good) then we call CAsyncSocket::Close(), then call CAsyncSocket::Create() (with no params) then call CAsyncSocket::Connect(server, port) Note that the initial call to Connect() had no preceding call to Create(). My first real question: What is the difference between the two and why is the Create() needed? (if I remove that then it no longer crashes, but I also don't connect when I re-establish connectivity) The general question: What exactly is wrong with the design of the code above? How should this work in general? EDIT: I fixed the code so that all the paths go through calling Create() then Connect(). I still have a problem with an assert in CAsyncSocket::DoCallBack() - the last line of the code below is asserting: void PASCAL CAsyncSocket::DoCallBack(WPARAM wParam, LPARAM lParam) { if (wParam == 0 && lParam == 0) return; // Has the socket be closed - lookup in dead handle list CAsyncSocket* pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, TRUE); // If yes ignore message if (pSocket != NULL) return; pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, FALSE); if (pSocket == NULL) { // Must be in the middle of an Accept call pSocket = CAsyncSocket::LookupHandle(INVALID_SOCKET, FALSE); ENSURE(pSocket != NULL); If I step through that then I get the message box: "Encountered an improper argument" I think (but am not sure) that MFC is trying to call back the socket AFTER I have closed it. It is in a callback method (DoCallback()) but I already called Close() on the socket. So it does look like an MFC problem, unless I am supposed to unsubscribe first.
Your choice really. If you think you'll have more luck with another sockets implementation, then do it. However, Microsoft has a lot of developers (and I believe some of them may even be good ones). You may, just may, want to consider the possibility that the fault doesn't all lay at their end. The amount of help you can get for their APIs and products is also good, in my opinion. Perhaps if you took the time to understand the MFC model, you would get that "AHA" moment and understand it better. I'm no fan of Winsock - I'm more used to the UNIX world where sync was the way to go, and you just ran separate processes/threads if you wanted async-type behavor. CAsyncSocket, I suspect, is still hamstrung by the fact that MFC is a single-threaded model (in terms of GUI) even though Windows has had real pre-emptive threads for quite a while. [I may be wrong about that hamstrung comment, it's been a while since I used Win32 directly]. Update: Based on your update where you stated what you were doing, I'm fairly certain you are not allowed to connect before creating. Quoting http://msdn.microsoft.com/en-us/library/3d46645f(VS.80).aspx, To use a CAsyncSocket object, call its constructor, then call the Create function to create the underlying socket handle ... and for a client socket call the Connect member function. As to why, I think this is an extra complexity added because Windows needs to do async sockets in an event-pumping environment since they cannot block the main GUI thread. In UNIXy environments, there is either no event thread (normal processes) or network ops are just farmed off to another thread manually (in GUI apps). This was most likely a design decision made in WinSock long ago (probably in Windows 3.11 which was a much more restrictive environment in which to do async operations) and carried through [although that's conjecture on my part, the UNIX sockets API has never had this sort of async behavior where messages are pumped, it always tended to use select() or threads/processes]. Further update: That assertion (not exception) usually occurs if you have closed and/or deleted the socket object while there is a pending operation on it. In your case, I'd suggest it's still trying to do the connect when you close it. Then when the connect succeeds or fails, the callback is called and it cannot find your socket in the tables. This isn't an MFC problem, it's your friend's code violating the contract. If you do a connect (or any async operation), you have to wait for success or failure before closing the socket (or working further on it) - in this case, that means wait for the call to your OnConnect() function. From memory, you call the create() when you create the async socket, then everything else happens in response to messages arriving in the message queue (i.e., calls to your OnXXX() functions). Like all Win32 GUI stuff, the messages are supposed to drive the program (the code runs in response to messages). This code is looking more and more like classic coding where the program drives everything - that way lies madness as you'll have your program and the async socket 'thread' fighting for control. I haven't looked at it for quite a while but you should be able to get your hands on a CHATSRVR sample program which will show you how to do it.
800,761
800,799
When to use the keyword "static" in C++class?
Code static void MyClass::ThreadEntryStatic() { //... } void MyClass::Begin() { CreateThread(..,ThreadEntryStatic,..); } In which condition we should use the static in class ?
There are three places that the keyword static can be used. One is in the declaration of a struct/class when that context means that the method is a class method instead of an instance method. This means that this method is called directly and you don't need an instance. From this static method, you can not access instance variables. In MyClass.h struct MyClass { static void ThreadEntryStatic(); void Begin(); }; In MyClass.cpp void MyClass::ThreadEntryStatic() { } void MyClass::Begin() { CreateThread(.., MyClass::ThreadEntryStatic, ...); } A second case where the static keyword is use is in the scope of a file where you don't want the visibility of the variable declared to be visible outside the file. You can also use an anonymous namespace for this as well. A third case where the static keyword is used is in the scope of a method and the value is retained between executions of the function (and initialized with the assignment the first time).
800,955
800,984
remove_if equivalent for std::map
I was trying to erase a range of elements from map based on particular condition. How do I do it using STL algorithms? Initially I thought of using remove_if but it is not possible as remove_if does not work for associative container. Is there any "remove_if" equivalent algorithm which works for map ? As a simple option, I thought of looping through the map and erase. But is looping through the map and erasing a safe option?(as iterators get invalid after erase) I used following example: bool predicate(const std::pair<int,std::string>& x) { return x.first > 2; } int main(void) { std::map<int, std::string> aMap; aMap[2] = "two"; aMap[3] = "three"; aMap[4] = "four"; aMap[5] = "five"; aMap[6] = "six"; // does not work, an error // std::remove_if(aMap.begin(), aMap.end(), predicate); std::map<int, std::string>::iterator iter = aMap.begin(); std::map<int, std::string>::iterator endIter = aMap.end(); for(; iter != endIter; ++iter) { if(Some Condition) { // is it safe ? aMap.erase(iter++); } } return 0; }
Almost. for(; iter != endIter; ) { if (Some Condition) { iter = aMap.erase(iter); } else { ++iter; } } What you had originally would increment the iterator twice if you did erase an element from it; you could potentially skip over elements that needed to be erased. This is a common algorithm I've seen used and documented in many places. [EDIT] You are correct that iterators are invalidated after an erase, but only iterators referencing the element that is erased, other iterators are still valid. Hence using iter++ in the erase() call.
801,054
818,390
OpenCV cvSaveImage Jpeg Compression Factor
I am using OpenCV and saving as a jpeg using the cvSaveImage function, but I am unable to find the Jpeg compression factor used by this. What's cvSaveImage(...)'s Jpeg Compression factor How can I pass the compression factor when using cvSaveImage(...)
Currently cvSaveImage() is declared to take only two parameters: int cvSaveImage( const char* filename, const CvArr* image ); However, the "latest tested snapshot" has: #define CV_IMWRITE_JPEG_QUALITY 1 #define CV_IMWRITE_PNG_COMPRESSION 16 #define CV_IMWRITE_PXM_BINARY 32 /* save image to file */ CVAPI(int) cvSaveImage( const char* filename, const CvArr* image, const int* params CV_DEFAULT(0) ); I've been unable to find any documentation, but my impression from poking through this code is that you would build an array of int values to pass in the third parameter: int p[3]; p[0] = CV_IMWRITE_JPEG_QUALITY; p[1] = desired_quality_value; p[2] = 0; I don't know how the quality value is encoded, and I've never tried this, so caveat emptor. Edit: Being a bit curious about this, I downloaded and built the latest trunk version of OpenCV, and was able to confirm the above via this bit of throwaway code: #include "cv.h" #include "highgui.h" int main(int argc, char **argv) { int p[3]; IplImage *img = cvLoadImage("test.jpg"); p[0] = CV_IMWRITE_JPEG_QUALITY; p[1] = 10; p[2] = 0; cvSaveImage("out1.jpg", img, p); p[0] = CV_IMWRITE_JPEG_QUALITY; p[1] = 100; p[2] = 0; cvSaveImage("out2.jpg", img, p); exit(0); } My "test.jpg" was 2,054 KB, the created "out1.jpg" was 182 KB and "out2.jpg" was 4,009 KB. Looks like you should be in good shape assuming you can use the latest code available from the Subversion repository. BTW, the range for the quality parameter is 0-100, default is 95.
801,199
832,474
OpenCV to use in memory buffers or file pointers
The two functions in openCV cvLoadImage and cvSaveImage accept file path's as arguments. For example, when saving a image it's cvSaveImage("/tmp/output.jpg", dstIpl) and it writes on the disk. Is there any way to feed this a buffer already in memory? So instead of a disk write, the output image will be in memory. I would also like to know this for both cvSaveImage and cvLoadImage (read and write to memory buffers). Thanks! My goal is to store the Encoded (jpeg) version of the file in Memory. Same goes to cvLoadImage, I want to load a jpeg that's in memory in to the IplImage format.
There are a couple of undocumented functions in the SVN version of the libary: CV_IMPL CvMat* cvEncodeImage( const char* ext, const CvArr* arr, const int* _params ) CV_IMPL IplImage* cvDecodeImage( const CvMat* _buf, int iscolor ) Latest check in message states that they are for native encoding/decoding for bmp, png, ppm and tiff (encoding only). Alternatively you could use a standard image encoding library (e.g. libjpeg) and manipulate the data in the IplImage to match the input structure of the encoding library.
801,209
801,240
char* vs std::string in c++
When should I use std::string and when should I use char* to manage arrays of chars in C++? It seems you should use char* if performance(speed) is crucial and you're willing to accept some of a risky business because of the memory management. Are there other scenarios to consider?
You can pass std::strings by reference if they are large to avoid copying, or a pointer to the instance, so I don't see any real advantage using char pointers. I use std::string/wstring for more or less everything that is actual text. char * is useful for other types of data though and you can be sure it gets deallocated like it should. Otherwise std::vector<char> is the way to go. There are probably exceptions to all of this.
801,279
807,398
Finding compiler vendor / version using qmake
Is there any way to get the version and vendor of the compiler used by the user through qmake? What I need is to disable building some targets of my project when g++ 3.x is used and enable them when g++ 4.x is used. Update: Most answers targeted the preprocessor. This is something that I want to avoid. I don't want a target to be build for a specific compiler version and I want this decision to be made by the build system.
In addition to ashcatch's answer, qmake allows you to query the command line and get the response back as a variable. So you could to something like this: linux-g++ { system( g++ --version | grep -e "\<4.[0-9]" ) { message( "g++ version 4.x found" ) CONFIG += g++4 } else system( g++ --version | grep -e "\<3.[0-9]" ) { message( "g++ version 3.x found" ) CONFIG += g++3 } else { error( "Unknown system/compiler configuration" ) } } Then later, when you want to use it to specify targets, you can use the config scoping rules: SOURCES += blah blah2 blah3 g++4: SOURCES += blah4 blah5
801,284
801,433
Is there a tool to monitor synchronisation objects (mutex, events, semaphores) in Windows?
In Windows, is there a tool to monitor the status of process synchronisation objects? ie. event/mutex : signaled or not signaled semaphore : count Better yet, to log which thread did what, eg. "thread #5421 Signal Event - testevt"
Memory Validator Process Explorer Handle usage: handle -s ==> Print count of each type of handle open. [EDIT]: How to monitor the status of process synchronization objects using Process Explorer. Open Process Explorer Click on your exe in the process section (for ex: MyApp.exe) Click Show Lower Pane (or press Ctrl+L). This will show all synchronization objects. (for ex: myEvent) Right click on synchronization object (for ex: myEvent) and click Properties... in context menu. This brings the details of the synchronization object. In the Details tab, you can see Event Info (if synch object is event): Gives information about the state (whether the synchronization object is signaled) Semaphore info (if synch object is semaphore): Provides the count of the semaphore.
801,385
801,658
Are there any practical limitations to only using std::string instead of char arrays and std::vector/list instead of arrays in c++?
I use vectors, lists, strings and wstrings obsessively in my code. Are there any catch 22s involved that should make me more interested in using arrays from time to time, chars and wchars instead? Basically, if working in an environment which supports the standard template library is there any case using the primitive types is actually better?
For 99% of the time and for 99% of Standard Library implementations, you will find that std::vectors will be fast enough, and the convenience and safety you get from using them will more than outweigh any small performance cost. For those very rare cases when you really need bare-metal code, you can treat a vector like a C-style array: vector <int> v( 100 ); int * p = &v[0]; p[3] = 42; The C++ standard guarantees that vectors are allocated contiguously, so this is guaranteed to work. Regarding strings, the convenience factor becomes almnost overwhelming, and the performance issues tend to go away. If you go beack to C-style strings, you are also going back to the use of functions like strlen(), which are inherently very inefficent themselves. As for lists, you should think twice, and probably thrice, before using them at all, whether your own implementation or the standard. The vast majority of computing problems are better solved using a vector/array. The reason lists appear so often in the literature is to a large part because they are a convenient data structure for textbook and training course writers to use to explain pointers and dynamic allocation in one go. I speak here as an ex training course writer.
801,657
801,671
Is Python faster and lighter than C++?
I've always thought that Python's advantages are code readibility and development speed, but time and memory usage were not as good as those of C++. These stats struck me really hard. What does your experience tell you about Python vs C++ time and memory usage?
I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out. My experiences with Python show the same definite trend that Python is on the order of between 10 and 100 times slower than C++ when doing any serious number crunching. There are many reasons for this, the major ones being: a) Python is interpreted, while C++ is compiled; b) Python has no primitives, everything including the builtin types (int, float, etc.) are objects; c) a Python list can hold objects of different type, so each entry has to store additional data about its type. These all severely hinder both runtime and memory consumption. This is no reason to ignore Python though. A lot of software doesn't require much time or memory even with the 100 time slowness factor. Development cost is where Python wins with the simple and concise style. This improvement on development cost often outweighs the cost of additional cpu and memory resources. When it doesn't, however, then C++ wins.
802,138
802,141
How should you return *this with a shared_ptr?
See also: Similar question The code below is obviously dangerous. The question is: how do you do keep track of the reference to *this? using namespace boost; // MyClass Definition class MyClass { public: shared_ptr< OtherClass > createOtherClass() { return shared_ptr< OtherClass > OtherClass( this ); // baaad } MyClass(); ~MyClass(); }; // OtherClass Definition class OtherClass { public: OtherClass( const *MyClass myClass ); ~OtherClass(); }; // Call; pMyClass refcount = 1 shared_ptr< MyClass > pMyClass( new MyClass() ); // Call; pMyClass refcount = 1 => dangerous pMyClass->createOtherClass(); I have the answer (posted below), I just want it to be on stackoverflow (where everyone can correct me if I'm wrong.)
The key is to extend enable_shared_from_this<T> and use the shared_from_this() method to get a shared_ptr to *this For detailed information using namespace boost; // MyClass Definition class MyClass : public enable_shared_from_this< MyClass > { public: shared_ptr< OtherClass> createOtherClass() { return shared_ptr< OtherClass > OtherClass( shared_from_this() ); } MyClass(); ~MyClass(); }; // OtherClass Definition class OtherClass { public: OtherClass( shared_ptr< const MyClass > myClass ); ~OtherClass(); }; // Call; pMyClass refcount = 1 shared_ptr< MyClass > pMyClass( new MyClass() ); // Call; pMyClass refcount = 2 pMyClass->createOtherClass();
802,170
802,202
How to use WMI to add an IP route?
I need to add a route into the IP4 routing table on windows xp. However, the Win32_IP4RouteTable class seems to only be able to query existing routes. Basically I need the same functionality as: route ADD 192.168.127.254 MASK 255.255.255.255 192.168.1.10 Is it possible to use WMI to add an entry into the IP4 routing table? Could I use CreateProcess instead?
Do you need solution on WMI only? I usually use IPHelper. Specifically, you need CreateIpForwardEntry function.
802,499
802,513
How can I enumerate/list all installed applications in Windows XP?
When I say "installed application", I basically mean any application visible in [Control Panel]->[Add/Remove Programs]. I would prefer to do it in Python, but C or C++ is also fine.
If you mean the list of installed applications that is shown in Add\Remove Programs in the control panel, you can find it in the registry key: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall more info about how the registry tree is structured can be found here. You need to use the winreg API in python to read the values from the registry.
802,656
802,955
Is runtime stack kept in data segment of memory?
I'm very curious of the stack memory organization after I experiment what's going on in the background and obviously saw it's matching with tiny knowledge I acquired from books. Just wanted to check if what I've understood is correct. I have a fundamental program -- has 2 functions, first one is foo and the other is main (the entry point). void foo(){ // do something here or dont } int main(){ int i = 0; printf("%p %p %p\n",foo, &i, main); system("PAUSE"); return EXIT_SUCCESS; }; The output of the program is shown below, main's local variable i is located totally in a unrelated position. integer is a value type but checked it again with a char * pointer local to main and obtain similar results. 00401390 0022FF44 00401396 Press any key to continue . . . I mainly understand that code and variables are allocated into different segments of memory (code segment/data segment). So basically is it right to say call stack collapses basic information about the execution of functions (their local variables, parameters, returning points) and keep them in the data segment?
A little caveat at the start: all of these answers are somewhat affected by the operating system and hardware architecture. Windows does things fairly radically differently from UNIX-like languages, real-time operating systems and old small-system UNIX. But the basic answer as @Richie and @Paul have said, is "yes." When your compiler and linker get through with the code, it's broken up into what are known as "text" and "data" segments in UNIX. A text segment contains instructions and some kinds of static data; a data segment contains, well, data. A big chunk of the data segment is then allocated for stack and heap space. Other chunks can be allocated to things like static or extern data structures. So yes, when the program runs, the program counter is busily fetching instructions from a different segment than the data. Now we get into some architecture dependencies, but in general if you have segmented memory your instructions are constructed in such a way that fetching a byte from the segments is as efficient as possible, In the old 360 architecture, they had base registers, in x86 have a bunch of hair that grew as the address space went to the old 8080's to modern processors, but all of the instructions are very carefully optimized because, as you can imagine, fetching instructions and their operands are very intensively used. Now we et to more modern architectures with virtual memory and memory management units. Now the machine has specific hardware that let's the program treat the address space as a big flat range of addresses; the various segments simply get placed in that bit virtual address space. The MMU's job is to take a virtual address and translate it to a physical address, including what to do if that virtual address doesn't happen to be in physical memory at all at the moment. Again, the MMU hardware is very heavily optimized, but that doesn't mean there is no performance cost associated. But as processors have gotten faster and programs have goten bigger, it's become less and less important.
802,706
803,229
libraries/approaches for implementing object models in C++
Apologies if this has been asked before, I'm not quite sure of the terminology or how to ask the question. I'm wondering if there are libraries or best practices for implementing object models in C++. If I have a set of classes where instances of these classes can have relations to each other and can be accessed from each other via various methods, I want to pick a good set of underlying data structures to manage these instances and their inter-relationships. This is easy in Java since it handles the memory allocation and garbage collection for me, but in C++ I have to do that myself. HTML's Document Object Model (DOM) is one example; as another (contrived) example, suppose I have these classes: Entity Person (subclass of Entity) Couple (subclass of Entity) Property House (subclass of Property) Pet (subclass of Property) Car (subclass of Property) and these relationships: Entity has 1 home of class House has 0 or more pets of class Pet has 0 or more cars of class Car has 0 or more children of class Person Person has 0 or 1 spouse of class Person has 0 or 1 marriage of class Couple has 0 or 1 parents of class Entity (in this model parents don't exist if they're not alive!) Couple has 2 members of class Person Property has 1 owner of class Entity Now that I've thought out these objects and their relationships, I want to start making data structures and methods and fields to handle them, and here's where I get lost, since I have to deal with memory allocation and lifetime management and all that stuff. You can run into problems like the following: I might want to put an object into a std::map or a std::vector, but if I do that, I can't store pointers to those objects since they can be relocated when the map or vector grows or shrinks. One approach I used when I was working with COM a lot, is to have a hidden collection that contained everything. Each object in the collection had a unique ID (either a number or name), by which it could be looked up from the collection, and each object had a pointer to the collection. That way, if you have an object which wants to point to another object, instead of literally holding a pointer to another object, I store the ID and can look it up via the hidden collection. I can use reference-counting to automatically deal with lifetime issues (except for the case of disjoint cycles, sometimes that's not a problem). Are there other approaches? Or are there libraries to make this kind of stuff easier in C++? edit: then you have other issues, such as the relationships between objects are likely to be mutable in many cases, and you have to think ahead about how references to objects should be stored, and what methods should be provided for accessing objects from each other. For example, if I have a handle to a Person X, and I want to represent the concept of "find X's child named George", then I have to store the name "George" rather than a child number: the children may be stored in a vector, and I may be able to call X.getChildCount() and X.getChild(0), but "George" may not always be child number 0, since other children may be inserted before "George" in the child vector. Or X may have two or three or four other children also named "George". Or "George" may change his name to "Anthony" or "Georgina". In all these cases it is probably better to use some kind of unique immutable ID. edit 2: (and I'll clean up my question a bit once I get this straightened out) I can deal with the choice of methods and property names, I can deal with whether to use a map or a list or a vector. That's fairly straightforward. The problems I'm trying to deal with specifically are: how to have one object store a reference to another object, when those objects may be part of data structures that are reallocated how to deal with object lifetime management, when there are reciprocal relationships between objects
You wrote about storing objects from your object model inside std::vector etc. and problems with using pointers to them. That reminds me that it's good to divide your C++ classes into two categories (I'm not sure about terminology here): Entity classes which represent objects that are part of your object model. They are usually polymorphic or potentially will be in the future. They are created on heap and are always referenced by pointers or smart pointers. You never create them directly on stack, as class/struct members nor put them directly in containers like std::vectors. They don't have copy constructor nor operator= (you can make a new copy with some Clone method). You can compare them (their states) if it's meaningful to you but they are not interchangable because they have identity. Each two objects are distinct. Value classes which implement primitive user defined types (like strings, complex numbers, big numbers, smart pointers, handle wrappers, etc). They are created directly on stack or as class/struct members. They are copyable with copy constructor and operator=. They are not polymorphic (polymorhism and operator= don't work well together). You often put their copies inside stl containers. You rarely store pointers to them in independent locations. They are interchangeable. When two instances have the same value, you can treat them as the same. (The variables that contain them are different things though.) There are many very good reasons to break above rules. But I observed that ignoring them from the start leads to programs that are unreadable, unreliable (especially when it comes to memory management) and hard to maintain. Now back to your question. If you want to store a data model with complex relationships and easy way to do queries like "find X's child named George", why not consider some in-memory relational database? Notice that when you are going to efficiently implement a) more complex bidirectional relationships and b) queries based on different object properties, then you will probably need to create indexed data structures that are very similar to what relational database does inside. Are your implementations (as there will be many, in single project) really going to be more effective and robust? Same goes for "collections of everything" and object ids. You'll need to track relationships between objects to avoid ids without objects anyway. How is it different from pointers? Other then getting meaningful errors instead of going crazy all over the memory, that is ;-) Some ideas for memory management: Strong ownership: when you can declare that some entity lives only as long as its owner and there is no possibility of independently existing pointers to it, you can just delete it in owner's destructor (or with scoped_ptr). Someone already proposed smart_ptr. They are great and can be used with stl containers. They are reference couter based though, so do not create cycles :-(. I am not aware of any widely used c++ automatic pointers that can handle cycles. Maybe there is some top-level object which owns all other objects. Eg. often you can say that all pieces belong to a document or an algorithm or a transaction. They can be created in context of top-level object and then deleted automatically when their top-level object is deleted (when you remove document from memory or finish execution of algorithm). Of course you cannot share pieces between top level objects.
802,717
802,748
Variables, Pointers, Objects and Memory Addresses: Why do I get this strange result?
After I thought that I've understood how they work, I tried this: NSString *str1 = [NSString stringWithCString:"one"]; NSString *str2 = [NSString stringWithCString:"two"]; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, one NSLog(@"str2: %x, %@", &str2, str2); //bfffd3c8, two str1 = str2; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, two The value of an pointer (like str1, str2) is a memory address. When you go to that address, you reach the "area" in memory where the object is stored. But: When I assign str2 to str1, str1 should have as an value the memory address of the same object that's referenced by str2, right? The strange thing here is, that the value of the pointer remains the same (bfffd3cc memory address), where the thing behind that address changes. that's actually completely unlogical to me ;) because I think that the memory address IS the object (or the home of the object in the memory brick, what ever). So I expected this: NSString *str1 = [NSString stringWithCString:"one"]; NSString *str2 = [NSString stringWithCString:"two"]; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, one NSLog(@"str2: %x, %@", &str2, str2); //bfffd3c8, two str1 = str2; NSLog(@"str1: %x, %@", &str1, str1); //bfffd3c8, two Otherwise, I still didn't get the point. The relation between the value of the "pointer variable" and the "real value", lets say the object that's sitting behind that memory address.
Remember that a pointer variable is a variable itself, so it has an address. So &str1 results in the address of the pointer variable, and str1 is an expression that results in whatever the pointer variable is holding - the address of the object it's pointing to. Assume that: the object holding the NSString "one" is at address 0x00000100 the object holding the NSString "two" is at address 0x00000200 Then your pointers might look something like this: At initialization: str1 0xbfffd3c8 +---------------+ | | | 0x00000100 | | ("one") | +---------------+ str2 0xbfffd3cc +---------------+ | | | 0x00000200 | | ("two") | +---------------+ ======================================= After the str1 = str2; assignment: str1 0xbfffd3c8 +---------------+ | | | 0x00000200 | | ("two") | +---------------+ str2 0xbfffd3cc +---------------+ | | | 0x00000200 | | ("two") | +---------------+
802,784
802,797
References and auto_ptr
If I have a auto_ptr I can pass it for a reference?Like: auto_ptr<MyClass>Class(new MyClass); void SetOponent(MyClass& oponent); //So I pass SetOponent(Class) And what is odd copy behavior of auto_ptrs?
No you can't, you would have to dereference it: SetOponent( * Class ) As for the copying behaviour, I recommend you read a good book on C++, such as Effective C++ by Scott Meyers. The copying behaviour of auto_ptr is extremely un-intuitive and possibly beyond the scope of an SO answer. However, nothing ventured... When an auto_ptr is copied, ownership is transferred from the original to the copy. For example: auto_ptr <Foo> p1( new Foo ); at this point p1 owns the pointer to the Foo object. auto_ptr <Foo> p2( p1 ); After the copy, p2 owns the pointer and p1 is changed so that it now holds a NULL pointer. This is important, because copying occurs in lots of places in C++. You should never, for example, pass auto_ptrs by value to functions, or attempt to store them in standard library containers.
802,970
803,005
How to build a Visual C++ Project for Linux?
What's the best and easiest way to build (for Linux) a C++ application which was written in Visual Studio? The code itself is ready - I used only cross-platform libs. Is it possible to prepare everything under Windows in Visual Studio and then build it with a CLI tool under Linux? Are there any docs describing this? EDIT: Some more information: Libs used: stl, wxwidgets, boost, asio, cryptlib. Very little Linux know-how. EDIT#2: I chose the following solution: Make new project with kdevelop and compile everything there.
We're using CMake for Linux projects. CMake can generate KDevelop and Visual Studio project files, so you can just create your CMake file as the origin of platform-specific IDE files. The KDevelop generator is fine, so you can edit and compile in KDevelop (which will in turn call Make). On the other hand, if you have nothing fancy, you can use CMake or just Make to build the thing on Linux, if you want to stay with your solution file (which is what I'm currently doing for a library with test applications). This approach gets complicated when your build process is more than just "throw these files at the compiler and let's see what it does", so the CMake solution is in my opinion a good thing for cross-platform development.
803,088
922,895
My qhttp get() call does not work on Windows but does on Linux
I have written a program that uses qhttp to get a webpage. This works fine on Linux, but does not work on my Windows box (Vista). It appears that the qhttp done signal is never received. The relevant code is: Window::Window() { http = new QHttp(this); connect(http, SIGNAL(done(bool)), this, SLOT(httpDone(bool))); url = new QUrl("http://something.com/status.xml"); http->setHost(url->host(), url->port() != -1 ? url->port() : 80); if (!url->userName().isEmpty()) http->setUser(url->userName(), url->password()); } void Window::retrievePage() { byteArray = new QByteArray; result = new QBuffer(byteArray); result->open(QIODevice::WriteOnly); httpRequestAborted = false; httpGetId = http->get(url->path(), result); } void Window::httpDone(bool error) { //Never gets here! } Any help would be appriecated. Matt
This should not happen at all, i.e. QHttp works reliably both on Windows and Unix. My advice is to check whether the serves gives proper response. This can be done e.g. by verifying that data transfer is fine. You can trace the status from QHttp's signal, e.g. dataReadProgress, requestStarted, requestFinished, and other related signals. On the other hand, instead of using old QHttp, why not using the recommended QNetworkAccessManager instead? To get your feet wet quickly, check an example I posted to Qt Labs some time ago: image viewer with remote URL drag-and-drop support. It uses the said QNetworkAccessManager to grab the image from the dropped URL. Check the source-code, it is only 150 lines.
803,161
806,142
Saving image to file with IImageEncoder
do you have a working code to share. I’m trying to figure out how to save to a file an IBitmapImage image. I need to resize existing .jpg file and it seems like the only API for Windows Mobile. I managed to load it convert it to IImage -> IBitmapImage -> IBasicBitmapOps and resize it finally, but I have no clue how to save it properly to a new file.
Use IBitmapImage::LockBits to get access to the image data via its BitmapData* lockedBitmapData parameter. Use the BitmapData to prepare a bitmap file info header, then write that one and the image data in BitmapData::Scan0 to a file using regular file writing with ::WriteFile or higher level ones if you use such.
803,391
803,436
What are some good approaches to learning the Half-Life 2 SDK?
I have been a Half-Life lover for years. I have a BS in CS and have been informally programming since High-School. When I was still in college I tried to become a mod programmer for fun..using the first Half-Life engine...didn't work so good. So i figured after all my great college learrning :-) I would have more insight on how to tackle this problem and could finally do it. So here I am..finally out in the business world programming java...so I downloaded the HL2 SDk and started looking through the class structure. I feel like I did that last time I tried this...dazed and confused. Sorry about all the back ground. So what is the best way to systematically learn the code structure? I know java and I know c++..i just dont know what any of the classes do...the comments are few and far between and the documentation seems meager. Any good approahces? I **don'**t wanna start my own mod... I just wanna maybe be a spare-time mod programmer on some cool MOD one day...to keep the fun in learning programming along with the business side.
the comments are few and far between and the documentation seems meager. Any good approahces? Welcome to the wonder that is the Source SDK. No, it's not documented. Experiment, hack, place breakpoints and see what happens if you change bits of code. There is a wiki you may find helpful in some cases, but it's filled in by the community, and not by Valve, which means that you won't find any actual documentation there, just explanations of how previous modders have hacked the engine. Honestly, it sucks. The only way around it is to dive in. Try to achieve various changes to the game and don't be afraid to rip the existing code apart. It won't be pretty, but if it works, who's going to complain? Their code is pretty horrible, and most likely, yours will be too.
803,506
806,574
How do I reference an external C++ namespace from within a nested one?
I have two namespaces defined in the default/"root" namespace, nsA and nsB. nsA has a sub-namespace, nsA::subA. When I try referencing a function that belongs to nsB, from inside of nsA::subA, I get an error: undefined reference to `nsA::subA::nsB::theFunctionInNsB(...)' Any ideas?
Need more information to explain that error. The following code is fine: #include <iostream> namespace nsB { void foo() { std::cout << "nsB\n";} } namespace nsA { void foo() { std::cout << "nsA\n";} namespace subA { void foo() { std::cout << "nsA::subA\n";} void bar() { nsB::foo(); } } } int main() { nsA::subA::bar(); } So, while specifying the global namespace solves your current problem, in general it is possible to refer to symbols in nsB without it. Otherwise, you'd have to write ::std::cout, ::std::string, etc, whenever you were in another namespace scope. And you don't. QED. Specifying the global namespace is for situations where there's another nsB visible in the current scope - for instance if nsA::subA contained its own namespace or class called nsB, and you want to call ::nsbB:foo rather than nsA::subA::nsB::foo. So you'd get the error you quote if for example you have declared (but not defined) nsA::subA::nsB::theFunctionInNsB(...). Did you maybe #include the header for nsB from inside namespace subA?
804,123
804,131
const unsigned char * to std::string
sqlite3_column_text returns a const unsigned char*, how do I convert this to a std::string? I've tried std::string(), but I get an error. Code: temp_doc.uuid = std::string(sqlite3_column_text(this->stmts.read_documents, 0)); Error: 1>.\storage_manager.cpp(109) : error C2440: '<function-style-cast>' : cannot convert from 'const unsigned char *' to 'std::string' 1> No constructor could take the source type, or constructor overload resolution was ambiguous
You could try: temp_doc.uuid = std::string(reinterpret_cast<const char*>( sqlite3_column_text(this->stmts.read_documents, 0) )); While std::string could have a constructor that takes const unsigned char*, apparently it does not. Why not, then? You could have a look at this somewhat related question: Why do C++ streams use char instead of unsigned char?
804,217
804,269
Function template declaration order affects visibility (sometimes)
I'm trying to create a function: template <typename T> void doIt( T*& p ) { if ( !p ) { return; } T& ref = *p; getClassName( ref ); } where the behavior varies according to the type of p passed in. In particular, the version of getClassName called should depend upon the type of p. In the following example, I can successfully call: doIt<myClass1>( myClass1*& ) doIt<myClass1<int> >( myClass1*& ) doIt<myClass2>( myClass2*& ) doIt<myClass2<int> >( myClass2*& ) but it fails when I call: doIt< std::vector<int, std::allocator<int> > >( std::vector<int, std::allocator<int>>*& ) with the error: a.cxx: In function ‘void doIt(T*&) [with T = std::vector<int, std::allocator<int> >]’: ba.cxx:87: instantiated from here a.cxx:33: error: invalid initialization of reference of type ‘MyClass1&’ from expression of type ‘std::vector<int, std::allocator<int> >’ a.cxx:16: error: in passing argument 1 of ‘const char* getClassName(MyClass1&)’ (gcc 4.2.4). If I move the declaration of: template<typename T, typename A> char const* getClassName( std::vector<T,A>& ) { printf("std::vector<T,A>\n"); return NULL; } before doIt -- then it compiles. So, Why is it required that getClassName( std::vector<T,A>& ) appears before doIt but not getClassName( MyClass2T<T>& ) What can I do to make doIt independent of std::vector? (I want to be able to place doIt in its own header and not have to know about std::vector, or any of the specializations, which will be user-defined). . #include <stdio.h> #include <assert.h> #include <vector> //template<typename T> //char const* getClassName( T& ); //template<typename T, typename A> ////char const* getClassName( std::vector<T,A>& ) { printf("std::vector<T,A>\n"); return NULL; } #if 1 // --------- MyClass2 struct MyClass1 {}; char const* getClassName( MyClass1& ) { printf("MyClass1\n"); return NULL; } // --------- MyClass1T template< typename T> struct MyClass1T {}; template<typename T> char const* getClassName( MyClass1T<T>& ) { printf("MyClass1T<T>\n"); return NULL; } #endif template <typename T> void doIt( T*& p ) { if ( !p ) { return; } T& ref = *p; getClassName( ref ); } // --------- MyClass2 struct MyClass2 {}; // declared after doIt, OK. char const* getClassName( MyClass2& ) { printf("MyClass2\n"); return NULL; } // --------- MyClass2T template< typename T> struct MyClass2T {}; // declared after doIt, OK. template<typename T> char const* getClassName( MyClass2T<T>& ) { printf("MyClass2T<T>\n"); return NULL; } template<typename T, typename A> char const* getClassName( std::vector<T,A>& ) { printf("std::vector<T,A>\n"); return NULL; } void test() { #if 1 MyClass1 mc1; MyClass1* mc1p = &mc1; doIt( mc1p ); MyClass2 mc2; MyClass2* mc2p = &mc2; doIt( mc2p ); MyClass1T<int> mc1t; MyClass1T<int>* mc1tp = &mc1t; doIt( mc1tp ); MyClass2T<int> mc2t; MyClass2T<int>* mc2tp = &mc2t; doIt( mc2tp ); // Nested templates are OK. MyClass2T<MyClass1> mc2t2; MyClass2T<MyClass1>* mc2tp2 = &mc2t2; doIt( mc2tp2 ); #endif #if 1 std::vector<int> v; std::vector<int>* vp = &v; doIt( vp ); // FAIL! #endif }
Why is it required that getClassName( std::vector& ) appear before doIt but not getClassName( MyClass2T& ) A declaration in scope is required for any function. When you instantiate your template function with a vector<int> it expects a function with the signature getClassName(vector<int>&) to be present (at least a prototype) for compilation to succeed. What can I do do make doIt independent of std::vector? (I want to be able to place doIt in its own header and not have to know about std::vector, or any of the specializations, which will be user-defined) Read the FAQ on Templates. Try putting the prototype of all of doIt's dependent template functions before first instantiation of doIt.
804,777
804,813
Counting down in for-loops
I believe (from some research reading) that counting down in for-loops is actually more efficient and faster in runtime. My full software code is C++ I currently have this: for (i=0; i<domain; ++i) { my 'i' is unsigned resgister int, also 'domain' is unsigned int in the for-loop i is used for going through an array, e.g. array[i] = do stuff converting this to count down messes up the expected/correct output of my routine. I can imagine the answer being quite trivial, but I can't get my head round it. UPDATE: 'do stuff' does not depend on previous or later iteration. The calculations within the for-loop are independant for that iteration of i. (I hope that makes sense). UPDATE: To achieve a runtime speedup with my for-loop, do I count down and if so remove the unsigned part when delcaring my int, or what other method? Please help.
I'm guessing your backward for loop looks like this: for (i = domain - 1; i >= 0; --i) { In that case, because i is unsigned, it will always be greater than or equal to zero. When you decrement an unsigned variable that is equal to zero, it will wrap around to a very large number. The solution is either to make i signed, or change the condition in the for loop like this: for (i = domain - 1; i >= 0 && i < domain; --i) { Or count from domain to 1 rather than from domain - 1 to 0: for (i = domain; i >= 1; --i) { array[i - 1] = ...; // notice you have to subtract 1 from i inside the loop now }
804,826
804,854
Why does std::ends cause string comparison to fail?
I spent about 4 hours yesterday trying to fix this issue in my code. I simplified the problem to the example below. The idea is to store a string in a stringstream ending with std::ends, then retrieve it later and compare it to the original string. #include <sstream> #include <iostream> #include <string> int main( int argc, char** argv ) { const std::string HELLO( "hello" ); std::stringstream testStream; testStream << HELLO << std::ends; std::string hi = testStream.str(); if( HELLO == hi ) { std::cout << HELLO << "==" << hi << std::endl; } return 0; } As you can probably guess, the above code when executed will not print anything out. Although, if printed out, or looked at in the debugger (VS2005), HELLO and hi look identical, their .length() in fact differs by 1. That's what I am guessing is causing the == operator to fail. My question is why. I do not understand why std::ends is an invisible character added to string hi, making hi and HELLO different lengths even though they have identical content. Moreover, this invisible character does not get trimmed with boost trim. However, if you use strcmp to compare .c_str() of the two strings, the comparison works correctly. The reason I used std::ends in the first place is because I've had issues in the past with stringstream retaining garbage data at the end of the stream. std::ends solved that for me.
std::ends inserts a null character into the stream. Getting the content as a std::string will retain that null character and create a string with that null character at the respective positions. So indeed a std::string can contain embedded null characters. The following std::string contents are different: ABC ABC\0 A binary zero is not whitespace. But it's also not printable, so you won't see it (unless your terminal displays it specially). Comparing using strcmp will interpret the content of a std::string as a C string when you pass .c_str(). It will say Hmm, characters before the first \0 (terminating null character) are ABC, so i take it the string is ABC And thus, it will not see any difference between the two above. You are probably having this issue: std::stringstream s; s << "hello"; s.seekp(0); s << "b"; assert(s.str() == "b"); // will fail! The assert will fail, because the sequence that the stringstream uses is still the old one that contains "hello". What you did is just overwriting the first character. You want to do this: std::stringstream s; s << "hello"; s.str(""); // reset the sequence s << "b"; assert(s.str() == "b"); // will succeed! Also read this answer: How to reuse an ostringstream
805,110
805,130
Inter-Thread Communication (and libraries?)
If have I have a game engine that has multiple threads that all work with one scene graph, what are techniques to ensure everything is synchronized whenever that scene graph changes? What kind of libraries are out there to help with that? Thanks!
See this question for a list of availiable synchronization primitives. What you need to use depends on what your threads do. How many threads read the graph? How many modify the graph? Do they operate on the same part of the graph or on distinct parts? If you provide some more details, I can give further suggestions.
805,356
805,435
Learning Graphical Layout Algorithms
During my day-to-day work, I tend to come across data that I want to visualize in a custom manner. For example, automatically creating a call graph similar to a UML sequence diagram, display digraphs, or visualizing data from a database (scatter plots, 3D contours, etc). For graphs, I tend to use GraphViz. For UML-like plots and 3D plots, I would like to write my own software to run under Linux. I typically program in C++ and prototype in Python. What books have people used to learn these basic graphical algorithms? I've seen some nice posts on force-directed layout and various block-style layout algorithms based upon the Cutting and Packing problems -- these are great starts, but I would like a more beginners guide and overview before I jump in. Directed Graph Layout Force directed layout
Here are some sources, Graphic Layout and Design (Paperback). Active Layout Engine: Algorithms and Applications in Variable Data Printing
805,403
805,490
What are the rules of the std::cin object in C++?
I am writing a small program for my personal use to practice learning C++ and for its functionality, an MLA citation generator (I'm writing a large paper with tens of citations). For lack of a better way to do it (I don't understand classes or using other .cpp files inside your main, so don't bother telling me, I'll work on that when I have more time), I am writing a function for each type of citation. I might break this down into a function for each reused code if I get more time. My question is: how does the std::cin object work? I am currently reading in with std::cin >> for the strings I expect to be single words, and getline(std::cin, string) for the strings with spaces. I am not getting the right output, though. I just want to know how std::cin works and why I keep unexpectedly skipping over some some inputs (for instance, it skips over webPage instead of giving me a chance to input into it). void webCit() { std::cout << "Leave any unknowns blank.\n"; std::cout << "Author last name: "; std::string lastName; std::cin >> lastName; if (lastName.size() != 0) { lastName = lastName + ", "; } std::cout << "Author first name: "; std::string firstName; std::cin >> firstName; if (firstName.size() != 0) { firstName = firstName + ". "; } std::cout << "Article title: "; std::string articleTitle; getline(std::cin, articleTitle); if (articleTitle.size() != 0) { articleTitle = "\"" + articleTitle + ".\" "; } std::cout << "Title of web page: "; std::string pageTitle; std::cin >> pageTitle; if (pageTitle.size() != 0) { pageTitle = pageTitle + ". "; } std::cout << "Publication date: "; std::string publicationDate; getline(std::cin, publicationDate); if (publicationDate.size() != 0) { publicationDate = publicationDate + ". "; } std::cout << "Web address: "; std::string webAddress; getline(std::cin, webAddress); webAddress = "<" + webAddress + ">. "; std::cout << "Date accessed: "; std::string dateAccessed; getline(std::cin, dateAccessed); if (dateAccessed.size() != 0) { dateAccessed = dateAccessed + ". "; } std::string citation = lastName + firstName + articleTitle + pageTitle + publicationDate + webAddress + dateAccessed; std::cout << citation; //TEST; remove after } EDIT: I/O Leave any unknowns blank. Author last name: Doe Author first name: John Article title: Title of web page: title Publication date: Web address: www.win.com Date accessed: 4/29/09 Doe, John. Title. <www.win.com>. 4/29/09. As you can see, something is going wrong, because my input is getting skipped over.
What is happening here is that std::cin >> firstName; only reads up to but not including the first whitespace character, which includes the newline (or '\n') when you press enter, so when it gets to getline(std::cin, articleTitle);, '\n' is still the next character in std::cin, and getline() returns immediately. // cin = "Bloggs\nJoe\nMan of Steel, Woman of Kleenex\n" std::cin >> lastName; std::cin >> firstName; // firstName = "Joe", lastName = "Bloggs", cin = "\nMan of Steel, Woman of Kleenex\n" getline(std::cin, articleTitle); // articleTitle = "", cin = "Man of Steel, Woman of Kleenex\n" Adding 'std::cin >> std::ws' (ws meaning whitespace) before your calls to getline() fixes the problem: std::cin >> firstName >> std::ws; getline(std::cin, articleTitle); But it is easier to see where you missed it if you do it in the argument: std::cin >> firstName; getline(std::cin >> std::ws, articleTitle);
805,413
805,578
Restrict inheritance to desired number of classes at compile-time
We have a restriction that a class cannot act as a base-class for more than 7 classes. Is there a way to enforce the above rule at compile-time? I am aware of Andrew Koenig's Usable_Lock technique to prevent a class from being inherited but it would fail only when we try to instantiate the class. Can this not be done when deriving itself? The base-class is allowed to know who are its children. So i guess we can declare a combination of friend classes and encapsulate them to enforce this rule. Suppose we try something like this class AA { friend class BB; private: AA() {} ~AA() {} }; class BB : public AA { }; class CC : public AA {}; The derivation of class CC would generate a compiler warning abt inaccessible dtor. We can then flag such warnings as errors using compiler tweaks (like flag all warnings as errors), but i would not like to rely on such techniques. Another way, but to me looks rather clumsy is:- class B; class InheritanceRule{ class A { public: A() {} ~A() {} }; friend class B; }; class B { public: class C : public InheritanceRule::A {}; }; class D : public InheritanceRule::A{}; The derivation of class D will be flagged as a compiler error, meaning all the classes to be derived should be derived inside class B. This will allow atleast an inspection of the number of classes derived from class A but would not prevent anyone from adding more. Anyone here who has a way of doing it ? Better still if the base-class need not know who are its children. NOTE: The class which acts as a base-class can itself be instantiated (it is not abstract). Thanks in advance, EDIT-1: As per Comment from jon.h, a slight modification // create a template class without a body, so all uses of it fail template < typename D> class AllowedInheritance; class Derived; // forward declaration // but allow Derived by explicit specialization template<> class AllowedInheritance< Derived> {}; template<class T> class Base : private AllowedInheritance<T> {}; // privately inherit Derived from that explicit specialization class Derived : public Base<Derived> {}; // Do the same with class Fail Error // it has no explicit specialization, so it causes a compiler error class Fail : public Base<Fail> {}; // this is error int main() { Derived d; return 0; }
I'm tired as crap, can barely keep my eyes open, so there's probably a more elegant way to do this, and I'm certainly not endorsing the bizarre idea that a Base should have at most seven subclasses. // create a template class without a body, so all uses of it fail template < typename D, typename B> class AllowedInheritance; class Base {}; class Derived; // forward declaration // but allow Derived, Base by explicit specialization template<> class AllowedInheritance< Derived, Base> {}; // privately inherit Derived from that explicit specialization class Derived : public Base, private AllowedInheritance<Derived, Base> {}; // Do the same with class Compiler Error // it has no explicit specialization, so it causes a compiler error class CompileError: public Base, private AllowedInheritance<CompileError, Base> { }; //error: invalid use of incomplete type //‘struct AllowedInheritance<CompileError, Base>’ int main() { Base b; Derived d; return 0; } Comment from jon.h: How does this stop for instance: class Fail : public Base { }; ? \ It doesn't. But then neither did the OP's original example. To the OP: your revision of my answer is pretty much a straight application of Coplien's "Curiously recurring template pattern"] I'd considered that as well, but the problem with that there's no inheritance relationship between a derived1 : pubic base<derived1> and a derived2 : pubic base<derived2>, because base<derived1> and base<derived2> are two completely unrelated classes. If your only concern is inheritance of implementation, this is no problem, but if you want inheritance of interface, your solution breaks that. I think there is a way to get both inheritance and a cleaner syntax; as I mentioned I was pretty tired when I wrote my solution. If nothing else, by making RealBase a base class of Base in your example is a quick fix. There are probably a number of ways to clean this up. But I want to emphasize that I agree with markh44: even though my solution is cleaner, we're still cluttering the code in support of a rule that makes little sense. Just because this can be done, doesn't mean it should be. If the base class in question is ten years old and too fragile to be inherited from, the real answer is to fix it.
805,487
805,799
Where to start with FastCGI and C++
Anyone have any links or resource regarding writing a proper C++ FastCGI application? (on top of Apache using mod_fastcgi or mod_fcgid).
The obvious one would be the FastCGI Development Kit (for C/C++).
805,691
832,973
C++ FastCGI parsing POST requests in to various form fields
I am writing a C++ app on FastCGI using libfcgi++. When I do a POST or GET request, is there a library out there that would parse the different fields? For example for a GET /fastcgi.fcgi?var1=data1&var2=data2 would return something that's easier to access var1 and var2? Same for a multipart POST request.
Looks like fastcgi++ might do the trick.
805,957
806,004
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
Several years ago, I more or less learned web app programming on the job. C was the main language I knew, so I wrote the (fairly large-scale) web app in C. Bad mistake. C's string handling and memory management is tedious, and together with my lack of experience in web apps, it quickly became a hard-to-maintain project. C++ would be significantly better, mainly because std::string is much nicer than char*. However, now I'd use Python every time (though PHP is not a terrible choice, and perhaps easier to get started with). Python's string handling is awesome, and it handles Unicode seamlessly. Python has much better web tools and frameworks than C++, and its regex handling and standard libraries (urllib, email, etc) work very well. And you don't have to worry about memory management. I'd probably only use C or C++ for a web app if I was severely RAM-constrained (like on an embedded micro) or if I worked at Google and was coding a search engine that was going to have to respond to thousands of queries per second.