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
763,608
763,628
How to make a .com file using C/C++?
How can we make a .com file using C/C++? Is it possible? Edit: I was able to successfully make a com file using darin's suggestions. But somehow the exe file of the following program cannot be converted to com file. I get the "File cannot be converted" message by exe2bin. I'm using Borland Turbo C++ 3.0. Any suggestions? #include <dos.h> void interrupt (*oldint65)( ); char st[80] = {"Hello World$"}; void interrupt newint65(void); void main() { oldint65 = getvect(0x65); setvect(0x65, newint65); geninterrupt (0x65); geninterrupt (0x65); geninterrupt (0x65); setvect(0x65, oldint65); } void interrupt newint65( ) { _AH = 0x09; _DX=(unsigned int)st; geninterrupt (0x21); }
In C, you must compile your program with the TINY memory model. Then you can use use EXE2BIN or a similar program to convert an EXE file to a COM file.
763,656
763,841
Should we still be optimizing "in the small"?
I was changing my for loop to increment using ++i instead of i++ and got to thinking, is this really necessary anymore? Surely today's compilers do this optimization on their own. In this article, http://leto.net/docs/C-optimization.php, from 1997 Michael Lee goes into other optimizations such as inlining, loop unrolling, loop jamming, loop inversion, strength reduction, and many others. Are these still relevant? What low level code optimizations should we be doing, and what optimizations can we safely ignore? Edit: This has nothing to do with premature optimization. The decision to optimize has already been made. Now the question is what is the most effective way to do it. anecdote: I once reviewed a requirements spec that stated: "The programmer shall left shift by one instead of multiplying by 2".
If there is no cost to the optimization, do it. When writing the code, ++i is just as easy to write as i++, so prefer the former. There is no cost to it. On the other hand, going back and making this change afterwards takes time, and it most likely won't make a noticeable difference, so you probably shouldn't bother with it. But yes, it can make a difference. On built-in types, probably not, but for complex classes, the compiler is unlikely to be able to optimize it away. The reason for this is that the increment operation no is no longer an intrinsic operation, built into the compiler, but a function defined in the class. The compiler may be able to optimize it like any other function, but it can not, in general, assume that pre-increment can be used instead of post-increment. The two functions may do entirely different things. So when determining which optimizations can be done by the compiler, consider whether it has enough information to perform it. In this case, the compiler doesn't know that post-increment and pre-increment perform the same modifications to the object, so it can not assume that one can be replaced with the other. But you have this knowledge, so you can safely perform the optimization. Many of the others you mention can usually be done very efficiently by the compiler: Inlining can be done by the compiler, and it's usually better at it than you. All it needs to know is how large a proportion of the function consists of function call over head, and how often is it called? A big function that is called often probably shouldn't be inlined, because you end up copying a lot of code, resulting in a larger executable, and more instruction cache misses. Inlining is always a tradeoff, and often, the compiler is better at weighing all the factors than you. Loop unrolling is a purely mechanic operation, and the compiler can do that easily. Same goes for strength reduction. Swapping inner and outer loops is trickier, because the compiler has to prove that the changed order of traversal won't affect the result, which is difficult to do automatically. So here is an optimization you should do yourself. But even in the simple ones that the compiler is able to do, you sometimes have information your compiler doesn't. If you know that a function is going to be called extremely often, even if it's only called from one place, it may be worth checking whether the compiler automatically inlines it, and do it manually if not. Sometimes you may know more about a loop than the compiler as well (for example, that the number of iterations will always be a multiple of 4, so you can safely unroll it 4 times). The compiler may not have this information, so if it were to inline the loop, it would have to insert an epilog to ensure that the last few iterations get performed correctly. So such "small-scale" optimizations can still be necessary, if 1) you actually need the performance, and 2) you have information that the compiler doesn't. You can't outperform the compiler on purely mechanical optimizations. But you may be able to make assumptions that the compiler can't, and that is when you're able to optimize better than the compiler.
763,837
774,914
Eclipse has two C/C++ indexers (fast & full): what's the difference?
Eclipse CDT provides two indexers for C/C++ code (Preferences > C/C++ > Indexer). Does anybody know what the exact difference is between these two? The help file isn't exactly enlightening: "CDT supports the contribution of additional indexers, with 2 indexers being provided with the default CDT release: Fast C/C++ Indexer : provides fastest indexing capabilities - both declarations and cross reference information. This is the recommended indexer. Full C/C++ Indexer : provides even more accurate indexing capabilities at the cost of performance - both declarations and cross reference information." What does it mean to be more accurate: does it index more things, and if so which ones?
Here is an excerpt from the CDT page describing their parsing and indexing(CDT/designs/Overview of Parsing). It gives a pretty good description of what the differences are and where the fast indexer can fail: Parsing and binding resolution is a slow process, this is a problem because the user expects code editing features such as content assist to be fast. For this reason CDT stores binding information in an on-disk cache called “the index” or “the PDOM” (Persisted Document Object Model) in order to be able to provide features that respond quickly to user requests. Building the index involves parsing all the code in a project, resolving all the bindings and writing those bindings to the index. The index is then incrementally updated every time the user edits a file. Older versions of CDT support three different indexing modes, fast indexing, full indexing and no indexing. The default setting being the fast indexer because indexing a large project can be a time consuming process. The difference between the fast and full indexers is that the fast indexer will skip header files that have already been parsed once, while the full indexer will always re-parse a header file every time it is included. However it is important to understand that the full indexer, despite its name, is still not fully accurate. When a header file is included in a source file it is subject to any macros that have been defined at that point. Some library headers use macros in conjunction with preprocessor conditionals (#ifdefs) to partially include a header file. Sometimes such a header file is included more than once in a project, if the macros that the header depends on are different each time the header is included then different parts of the header may be included in different source files. Neither indexer will be accurate in this scenario because it will only index the header the first time it is encountered. The Full indexer will re-parse headers it has already encountered, but it will not re-index them. Therefore source files that include a header may be parsed more accurately, but the header itself will only be indexed the one time. The full indexer is much slower than the fast indexer because of the extra parsing it does, but it is only marginally more accurate. For this reason the Full indexer is not recommended and has been removed from the current version of CDT. Each project has a single PDOM associated with it. The PDOM is stored on disk as a flat binary file. The indexer will only index headers that are included by source files, so if there is a .h file in the project that is not being included by any .c or .cpp file, then normally it won’t get indexed. However there is a preference setting for indexing all files in the project.
764,540
764,552
HTML Sanitization in C++
Is there any available C++ (or maybe C) function/class/library with only purpose to sanitize a string that might contain HTML? I find a lot of source code for sanitizing in C# or other languages more used in web application but nothing in C++. I'll try to implement my own function if I don't find any available but I think an heavily tested solution would be far better. edit> Some more precisions on my needs : I'm getting text input from keyboard in my C++ application. Then I need to sanitize it before using it as a parameter in a javascript function call. That javascript run in a loaded html page that is automatically rendered (via Chromium) in a texture that I display via a library (Navi). So, the javascript function I use will simply take the given text, put P tag around the text and inject it in a div like this : text_display.innerHTML += text_to_add; I need to sanitize the text before sending it to the web page, be it for this function or another. It just have to be sanitized before input in Chromium.
HTML Tidy is written in c, but there are bindings for practically every language/platform, including c++.
764,555
764,561
Determing exit point of application. C++/Linux
I'm working on a big app (ns2) and somewhere someone put an exit(1) in there without any debug or print statements and it is being executed. I don't want to have to manually check every file that calls exit to figure out why the program is exiting. Is is possible to determine where the program exited? This is running on Linux and coded in C++. Is it possible to do something like this in gdb?
Sure. Put a breakpoint at the start of exit(3). When it breaks, look at the stack. Second choice, run it under truss(1) (I'm pretty sure there's a Linux version of truss.) Or strace(1). Update In fact, I ran across another method in another question: here's a link.
764,824
764,872
Best way to organize entities in a game?
Let's say I'm creating an OpenGL game in C++ that will have many objects created (enemies, player characters, items, etc.). I'm wondering the best way to organize these since they will be created and destroyed real-time based on time, player position/actions etc. Here's what I've thought of so far: I can have a global array to store pointers to these objects. The textures/context for these objects are loaded in their constructors. These objects will have different types, so I can cast the pointers to get them in the array, but I want to later have a renderObjects() function that will use a loop to call an ObjectN.render() function for each existing object. I think I've tried this before but I didn't know what type to initialize the array with, so I picked an arbitrary object type, then cast anything that wasn't of that type. If I remember, this didn't work because the compiler didn't want me dereferencing the pointers if it no longer knew their type, even if a given member function had the same name: (*Object5).render() <-doesn't work? Is there a better way? How to commercial games like HL2 handle this? I imagine there must be some module etc. that keeps track of all the objects.
I'm not sure I fully understand the question but I think you are wanting to create a collection of polymorphic objects. When accessing a polymorphic object, you must always refer to it by a pointer or a reference. Here is an example. First you need to set up a base class to derive your objects from: class BaseObject { public: virtual void Render() = 0; }; Then create the array of pointers. I use an STL set because that makes it easy to add and remove members at random: #include <set> typedef std::set<BaseObject *> GAMEOBJECTS; GAMEOBJECTS g_gameObjects; To add an object, create a derived class and instantiate it: class Enemy : public BaseObject { public: Enemy() { } virtual void Render() { // Rendering code goes here... } }; g_gameObjects.insert(new Enemy()); Then to access objects, just iterate through them: for(GAMEOBJECTS::iterator it = g_gameObjects.begin(); it != g_gameObjects.end(); it++) { (*it)->Render(); } To create different types of object, just derive more classes from class BaseObject. Don't forget to delete the objects when you remove them from the collection.
764,833
764,840
Programming a Steganography application in C/C++
I have been reading up on on steno for a while. I have seen tools that help aid in embedding messages in .mp3's and png's etc. I am familiar that they do this by replacing the least important bit. In images, these LIB are colors that the human eye can't see; thus not needed. In audio files frequencies not audible to the human ear; also not needed. So my question is, how would one program something like this in a C or C++ language, preferably in a Windows environment.
Your application needs to be aware of the file formats. You can't just go changing the LSB of random words in a PNG, nor in an mp3. Once you can read and write back those format, analyze the data, figure out where the LIBs (where importance is the perception of the user, not the least significant bit of the architecture) of the given data are, and embed your information in there. There is no magic recipe, really.
765,148
10,669,041
How to remove constness of const_iterator?
As an extension to this question Are const_iterators faster?, I have another question on const_iterators. How to remove constness of a const_iterator? Though iterators are generalised form of pointers but still const_iterator and iterators are two different things. Hence, I believe, I also cannot use const_cast<> to covert from const_iterator to iterators. One approach could be that you define an iterator which moves 'til the element to which const_iterator points. But this looks to be a linear time algorithm. Any idea on what is the best way to achieve this?
There is a solution with constant time complexity in C++11: for any sequence, associative, or unordered associative container (including all of the Standard Library containers), you can call the range-erase member function with an empty range: template <typename Container, typename ConstIterator> typename Container::iterator remove_constness(Container& c, ConstIterator it) { return c.erase(it, it); } The range-erase member functions have a pair of const_iterator parameters, but they return an iterator. Because an empty range is provided, the call to erase does not change the contents of the container. Hat tip to Howard Hinnant and Jon Kalb for this trick.
765,228
765,230
32bit int * 32bit int = 64 bit int?
In other words does this work as expected? int32 i = INT_MAX-1; int64 j = i * i; or do I need to cast the i to 64 bit first?
You need to cast at least one of the operands to the multiply. At the point the multiply is being done, the system doesn't know you're planning to assign to an int64. (Unless int64 is actually the native int type for your particular system, which seems unlikely)
765,257
765,266
Should I prefer iterators over const_iterators?
Someone here recently brought up the article from Scott Meyers that says: Prefer iterators over const_iterators (pdf link). Someone else was commenting that the article is probably outdated. I'm wondering what your opinions are? Here is mine: One of the main points of the article is that you cannot erase or insert on a const_iterator, but I think it's funny to use that as an argument against const_iterators. I thought the whole point of const_iterators it that you do not modify the range at all, neither the elements themselves by substituting their values nor the range by inserting or erasing. Or am I missing something?
I totally agree with you. I think the answer is simple: Use const_iterators where const values are the right thing to use, and vice versa. Seems to me that those who are against const_iterators must be against const in general...
765,301
765,395
Should I reject C++ because it's becoming a juggernaut?
I have tried to keep up with C++ since they introduced 1998 ANSI/ISO C++. I absorbed the new concepts and tried to understand them. I learned about exception handling, templates, and namespaces. I've read about the new cast mechanisms and worked with the STL library. All of these concepts required a lot of energy. But now I am somewhat worried about the future of C++ when having a look at the new C++0x standard. Things are getting more and more complicated. This language is becoming a monster. I'm not sure that I want to keep up with the language anymore, since I don't do my day-to-day hacking in C++ anyway. I mostly use interpreted or bytecode languages. So why should I bother to learn this difficult, yet exceptionally powerful, language? I can do 95% of my business with Python et al. With the remaining 5%, I can deal with plain old C++ or C without hassle. What do you think?
Hear what Bruce Eckel { author of the two of the so-called best C++ books } commented on C++ a few weeks ago: That said, I hardly ever use C++ anymore. When I do, it's either examining legacy code, or to write performance-critical sections, typically as small as possible to be called from other code (my preferred approach is to quickly write an app in Python, then profile it and if necessary improve performance by calling small portions of C++ using Python's ctypes library). Because I was on the C++ Standards Committee, I saw these decisions being made. They were all extremely carefully considered, far more so than many of the decisions made in Java. However, as people have rightly pointed out, the resulting language was complicated and painful to use and full of weird rules that I forget as soon as I'm away from it for a little while -- and I figured out those rules from first principles while I wrote books, not just by memorizing them. Additionally, you should read this thread and Danny Kalev's predictions on C++. However, the growing complexity of C++ will create pressure towards splitting the language into quasi-official dialects. We can already see this trend today; it will probably intensify in the future. EDIT: You should take a look at this discussion, too: C++ - Anyone else feel like C++ is getting too complicated?
765,408
765,474
Free easy way to draw graphs and charts in C++?
I am doing a little exploring simulation and I want to show the graphs to compare the performance among the algorithms during run-time. What library comes to your mind? I highly prefer those that come small as I'd love if it's easy for my instructor to compile my code. I've checked gdchart but it seems to be too heavy. I just want a simple x-y sort of timeline graph. Google chart is of course out of the question, in case you've read this similar question. Related post Scatter Plots in C++.
My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.
765,459
765,494
How can you do C++ when your embedded compiler doesn't have operator new or STL support?
I am working on a group senior project for my university and I have run into a major hurdle in trying to get my code to work. The compiler that we have for our 8 bit Atmel microcontroller does not support the new or delete operators, and it does not support the C++ STL. I could program it in C, but I have to implement an A* algorithm which I have never done before. While I have tried C initially I soon realized that I never did pure C before. Trying to model objects with structs and functions is slowing me down since I am so used to the much cleaner C++ syntax. Regardless, the exact wording for my compilers shortcomings can be found here: http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus To overcome them and still use C++ I have considered the following possibilities. 1) Don't allocate anything, just use templates to generate fixed arrays on the stack. 2) Allocate and find some hack to call the constructor for objects once I have allocated the space for them. Placement new isn't an option since new isn't an operator. 3) Just use C and suck it up, its a microcontroller why am I getting fancy? 4) Find a better compiler which will probably cost $$$. The second option is the hardest but it would have the biggest pay off in terms of how I can write this code. However, I imagine that debugging it could be a huge pain if I get it wrong. I'm thinking of creating objects on the stack, copying their bits into the allocated space, and then zeroing the bits in the object so it doesn't call its destructor. To do that I would access the bits directly with an unsigned char pointer and the sizeof operator to get the byte count. That sounds terrible and I don't know if it could work reliably, but I am considering it. I know vtables can be a problem but I don't intend on having any vtables since it is just an 8 bit microcontroller.
Just for the record, zeroing the bits in an object won't affect whether the destructor gets called (unless the compiler has a special quirk that enables this behaviour). Just write some logging statements in your destructor to test this out. Structuring your program not to allocate anything is probably the way the system was designed. I've not worked with embedded systems before, however I have read some experienced embedded shops that discourage use of dynamic memory because the runtime environment has scarce amounts of it. However, if you must, you can still use placement new. If you don't have the <new> header, here are the relevant lines directly from it on my version of GCC: // Default placement versions of operator new. inline void* operator new(std::size_t, void* __p) throw() { return __p; } inline void* operator new[](std::size_t, void* __p) throw() { return __p; } // Default placement versions of operator delete. inline void operator delete (void*, void*) throw() { } inline void operator delete[](void*, void*) throw() { } Stick that somewhere in a header file included by every source file that uses placement new/delete. Sample file that tests this: #include <cstdio> #include <new> int main(int argc, char** argv) { typedef char const* cstr; char foobar[16]; cstr* str = new (&foobar) cstr(argc > 1 ? argv[1] : "Hello, world!"); std::puts(*str); str->~cstr(); } On my version of GCC, this does not use libstdc++ at all (if -fno-exceptions is used). Now, if you want to combine that with malloc (if your platform provides this), then you can do this: #include <cstdio> #include <cstdlib> inline void* operator new (std::size_t n) {return std::malloc(n);} inline void* operator new[](std::size_t n) {return std::malloc(n);} inline void operator delete (void* p) {std::free(p);} inline void operator delete[](void* p) {std::free(p);} int main(int argc, char** argv) { typedef char const* cstr; cstr* str = new cstr(argc > 1 ? argv[1] : "Hello, world!"); std::puts(*str); delete str; } This allows you to use the standard new/delete that you're familiar with, without requiring use of libstdc++. Good luck!
765,629
765,644
Learning OpenGL through Java
I'm interested in learning OpenGL and my favorite language at the time is Java. Can I reap its full (or most) benefits using things like JOGL or should I instead focus on getting stronger C++ skills? Btw, which is your Java OpenGL wrapper library of choice and why?
JOGL is a wrapper library that allows OpenGL to be used in the Java programming language. It is currently the reference implementation for JSR-231 (Java Bindings for OpenGL) so it should be your first choice
765,709
765,722
Why compiler is not giving error when signed value is assigned to unsigned integer? - C++
I know unsigned int can't hold negative values. But the following code compiles without any errors/warnings. unsigned int a = -10; When I print the variable a, I get a wrong value printed. If unsigned variables can't hold signed values, why do compilers allow them to compile without giving any error/warning? Any thoughts? Edit Compiler : VC++ compiler Solution Need to use the warning level 4.
Microsoft Visual C++: warning C4245: 'initializing' : conversion from 'int' to 'unsigned int', signed/unsigned mismatch On warning level 4. G++ Gives me the warning: warning: converting of negative value -0x00000000a' to unsigned int' Without any -W directives. GCC You must use: gcc main.c -Wconversion Which will give the warning: warning: negative integer implicitly converted to unsigned type Note that -Wall will not enable this warning. Maybe you just need to turn your warning levels up.
765,778
765,780
Why does tm_sec range from 0-60 instead of 0-59 in time.h?
My time.h has the following definition of tm: struct tm { int tm_sec; /* seconds after the minute [0-60] */ int tm_min; /* minutes after the hour [0-59] */ int tm_hour; /* hours since midnight [0-23] */ ... } I just noticed that they document tm_sec as ranging between 0-60 inclusive. I've always assumed it ranged from 0-59 just like tm_min. I've certainly never seen a clock read 10:37:60... Do you think this is just a documentation bug left over from this 90's era Berkley-originated file? Or is there something more subtle going on that I'm unaware of?
Leap seconds are the reason for this: A leap second is a plus or minus one-second adjustment to the Coordinated Universal Time (UTC) time scale that keeps it close to mean solar time. When a positive leap second is added at 23:59:60 UTC, it delays the start of the following UTC day (at 00:00:00 UTC) by one second, effectively slowing the UTC clock.
765,913
765,918
Should I worry about "Conditional jump or move depends on uninitialised value(s)"?
If you've used Memcheck (from Valgrind) you'll probably be familiar with this message... Conditional jump or move depends on uninitialized value(s) I've read about this and it simply occurs when you use an uninitialized value. MyClass s; s.DoStuff(); This will work because s is automatically initialized... So if this is the case, and it works, why does Memcheck tell me that it's uninitialized? Should the message be ignored? Perhaps I misunderstood where the error was directing me. From the Valgrind manual, the actual erroneous snippet is... int main() { int x; printf ("x = %d\n", x); } However, in my code, I can't see anything like that. I have noticed however that the function at the top of the stack trace Memcheck shows me is a virtual function; could this be something to do with it? ==14446== Conditional jump or move depends on uninitialised value(s) ==14446== at 0x414164: vimrid::glut::GlutApplication::FinishRender() (GlutApplication.cpp:120) ==14446== by 0x422434: vimrid::demos::filterdemos::FilterDemo3::Render() (FilterDemo3.cpp:260) ==14446== by 0x412D3D: vimrid::VimridApplication::UpdateAndRender() (VimridApplication.cpp:93) ==14446== by 0x4144BA: vimrid::glut::GlutApplication::glutHandleDisplay() (GlutApplication.cpp:201) ==14446== by 0x41486A: vimrid::glut::GlutApplication::glutCallbackDisplay() (GlutApplication.cpp:277) ==14446== by 0x54D9FAA: (within /usr/lib64/libglut.so.3.8.0) ==14446== by 0x54DDA4A: fgEnumWindows (in /usr/lib64/libglut.so.3.8.0) ==14446== by 0x54DA4A3: glutMainLoopEvent (in /usr/lib64/libglut.so.3.8.0) ==14446== by 0x54DAEB5: glutMainLoop (in /usr/lib64/libglut.so.3.8.0) ==14446== by 0x413FF8: vimrid::glut::GlutApplication::Run() (GlutApplication.cpp:112) ==14446== by 0x41249D: vimrid::Launcher::runDemo(vimrid::VimridSettings&) (Launcher.cpp:150) ==14446== by 0x412767: vimrid::Launcher::Launch(int, char**) (Launcher.cpp:62) Update 1: I took a look at GlutApplication.cpp:120, and it looks like the uninitialized variable was being passed in to a function on that line. Simple!
Can you post a more complete sample? It's hard to see how there would be that particular error with out some form of goto or flow changing statement. I most commonly see this error in code like the following MyClass s1; ... if ( someCondition ) { goto Foo: } MyClass s2; Foo: cout << s2.GetName(); This code is fundamentally incorrect. The reason why is that even though s2 has a constructor, it's not executed if someCondition is true. The goto statement will jump over the initialization and at the last line of the program s2 will be uninitialized and essentially point to garbage. EDIT You may also want to check out this page which gives hints on how to decipher this particular valgrind error https://computing.llnl.gov/code/memcheck/#deciphering4 Addendum Another common cause for this I've just found is when you pass over some integer constants to a variadic function, which are put on the stack as ints, but when the callee gets it as longs, you've got a problem on 64-bit machines. I was almost about to give up and just consider valgrind being stupid, then I've realised that simply casting it to long fixes it. So my upshot is: take this messages seriously.
765,971
766,002
Is memory allocated with new ever automatically freed?
I'm 99% certain the answer to this is a blinding no. Please validate my proposition that the following code will produce a memory leak. Data &getData() { Data *i = new Data(); return *i; } void exampleFunc() { Data d1 = getData(); Data d2; /* d1 is not deallocated because it is on the heap, and d2 is * because it is on the stack. */ } Please note that this is an oversimplified example, so clearly you wouldn't actually use the above code... So no need to point this out thanks. Update 1: To add to this, what if I assign the pointer to a reference? In this case, I assume that the data is not copied... Data &getData() { Data *i = new Data(); return *i; } void exampleFunc() { // Does copying occur here? Data &d1 = getData(); // Does this deallocate the memory assigned to the pointer? delete &d; } Update 2: I guess to answer my own question (in update 1) the following code proves that assigning a reference to a reference does not cause a copy... #include <iostream> #include <string> using namespace std; class Data { public: string mName; Data(const string &name) : mName(name) { cout << mName << " default ctor" << endl; } Data(const Data& other) { mName = other.mName + " (copy)"; cout << mName << " copy ctor" << endl; } ~Data() { cout << mName << " dtor" << endl; } static Data &getData(const string &name) { Data *d = new Data(name); return *d; } }; int main() { cout << "d1..." << endl; Data d1 = Data::getData("d1"); cout << "d2..." << endl; Data d2("d2"); cout << "d3..." << endl; Data &d3 = Data::getData("d3"); cout << "return..." << endl; return 0; } Yields the following result... d1... d1 default ctor d1 (copy) copy ctor d2... d2 default ctor d3... d3 default ctor return... d2 dtor d1 (copy) dtor Thanks to Eric Melski for a great answer (my code in update 2 is a modified copy of his exmaple code).
Actually both d1 and d2 will be deallocated, because they are both on the stack. What is not deallocated is the Data object you allocated in your getData() function. You can see this a little more clearly if you flesh out your Data class with instrumentation in the constructors and destructor. For example: class Data { public: Data() { cout << "Data default ctor" << endl; } Data(const Data& other) { cout << "Data copy ctor" << endl; } ~Data() { cout << "Data dtor" << endl; } static Data& getData() { Data *i = new Data(); return *i; } }; Note that I have explicitly declared the copy constructor for Data. In your example you are implicitly calling that constructor when you do Data d1 = getData();, and I suspect this is where your confusion is coming from. Now if I run this simple program: #include <iostream> using namespace std; int main(int argc, char *argv[]) { Data d1 = Data::getData(); Data d2; return 0; } The output is as follows: Data default ctor Data copy ctor Data default ctor Data dtor Data dtor Line-by-line, here's what you're seeing: The default constructor is invoked when you allocate a new Data in getData(). The copy constructor is invoked to create d1 from the dynamically allocated Data you just made. The default constructor is invoked to create d2. The destructor is invoked for d2 when it goes out of scope at the end of main(). The destructor is invoked for d1 when it goes out of scope at the end of main(). Note that there are three constructor calls, but only two destructor calls -- indicating that you have leaked exactly one Data object. Hope that helps, Eric Melski
766,080
766,100
Why is Valgrind stating that my implementation of std::map<T, T> produces a memory leak?
Valgrind is outputting the following: ==14446== 2,976 (176 direct, 2,800 indirect) bytes in 2 blocks are definitely lost in loss record 23 of 33 ==14446== at 0x4C2506C: operator new(unsigned long) (in /usr/lib64/valgrind/amd64-linux/vgpreload_memcheck.so) ==14446== by 0x41C487: __gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::allocate(unsigned long, void const*) (new_allocator.h:92) ==14446== by 0x41C4AB: std::_Rb_tree<unsigned, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn>, std::_Select1st<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::_M_get_node() (stl_tree.h:357) ==14446== by 0x41C915: std::_Rb_tree<unsigned, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn>, std::_Select1st<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::_M_create_node(std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> const&) (stl_tree.h:366) ==14446== by 0x5036E9A: std::_Rb_tree<unsigned, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn>, std::_Select1st<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::_M_insert_(std::_Rb_tree_node_base const*, std::_Rb_tree_node_base const*, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> const&) (stl_tree.h:852) ==14446== by 0x5037027: std::_Rb_tree<unsigned, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn>, std::_Select1st<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::_M_insert_unique(std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> const&) (stl_tree.h:1148) ==14446== by 0x5037227: std::_Rb_tree<unsigned, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn>, std::_Select1st<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::_M_insert_unique_(std::_Rb_tree_const_iterator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> const&) (stl_tree.h:1188) ==14446== by 0x50375CD: std::map<unsigned, vimrid::imaging::ImageMatrixColumn, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::insert(std::_Rb_tree_iterator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> >, std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> const&) (stl_map.h:496) ==14446== by 0x50376DE: std::map<unsigned, vimrid::imaging::ImageMatrixColumn, std::less<unsigned>, std::allocator<std::pair<unsigned const, vimrid::imaging::ImageMatrixColumn> > >::operator[](unsigned const&) (stl_map.h:419) ==14446== by 0x5036A43: vimrid::imaging::ImageMatrixRow::operator[](unsigned) (ImageMatrixRow.cpp:10) ==14446== by 0x5034BBB: vimrid::imaging::ImageMatrix::_getRotatedCopy(double, vimrid::imaging::ImageMatrix&) (ImageMatrix.cpp:151) ==14446== by 0x503350A: vimrid::imaging::processing::ImageFilter& vimrid::imaging::ImageMatrix::GetRotatedCopy<vimrid::imaging::processing::ImageFilter>(double) (ImageMatrix.h:48) What could this possibly mean? //ImageMatrixRow.cpp:8-11 ImageMatrixColumn &ImageMatrixRow::operator[](VUInt32 columnIndex) { return columns[columnIndex]; } //ImageMatrix.cpp:151 target[x][y][0] = source[roundX][roundY][0]; //ImageMatrix.h:48 return *(T*)&_getRotatedCopy(degrees, CopyDimensions());
It's probably because of a pool allocator. From Valgrind FAQ: My program uses the C++ STL and string classes. Valgrind reports 'still reachable' memory leaks involving these classes at the exit of the program, but there should be none. First of all: relax, it's probably not a bug, but a feature. Many implementations of the C++ standard libraries use their own memory pool allocators. Memory for quite a number of destructed objects is not immediately freed and given back to the OS, but kept in the pool(s) for later re-use. The fact that the pools are not freed at the exit() of the program cause Valgrind to report this memory as still reachable. The behaviour not to free pools at the exit() could be called a bug of the library though. Read more at: Valgrind Faq I may be wrong, as I'm in a hurry and I can't analyse your code.
766,126
766,131
Representation of wchar_t and char in WinDbg
Note: /* * Trivial code */ wchar_t *greeting = L"Hello World!"; char *greeting_ = "Hello World!"; WinDbg: 0:000> ?? greeting wchar_t * 0x00415810 "Hello World!" 0:000> ?? greeting_ char * 0x00415800 "Hello World!" 0:000> db 0x00415800 00415800 48 65 6c 6c 6f 20 57 6f-72 6c 64 21 00 00 00 00 Hello World!.... 00415810 48 00 65 00 6c 00 6c 00-6f 00 20 00 57 00 6f 00 H.e.l.l.o. .W.o. 00415820 72 00 6c 00 64 00 21 00-00 00 00 00 00 00 00 00 r.l.d.!......... Question: What is the purpose of the NULL character: 00 between ASCII characters in wchar_t - Win32?
wchar_t is a wide-character string, so each character takes 2 bytes of storage. 'H' as a wchar_t is 0x0048. Since x86 is little-endian, you see the bytes in memory in order 48 00. db in windbg will dump the bytes and provide how its viewed as an ASCII string, hence the H.E.L. ... output you see. You can use 'du' to dump the memory as a unicode string.
766,127
766,139
Obtaining current ModelView matrix
In OpenGL, how do I read the current x/y translation in the modelview matrix? I know that you have to load the current matrix into an array and read the floats from there, but I don't know precisely how to do it.
In order to retrieve the current modelview matrix you have to call the glGetFloatv function with GL_MODELVIEW_MATRIX parameter. GLfloat matrix[16]; glGetFloatv (GL_MODELVIEW_MATRIX, matrix); From the documentation: GL_MODELVIEW_MATRIX params returns sixteen values: the modelview matrix on the top of the modelview matrix stack. Initially this matrix is the identity matrix.
766,167
766,176
What happens to pixels after passing them into glTexImage2D()?
If for example I create an array of pixels, like so: int *getPixels() { int *pixels = new int[10]; pixels[0] = 1; pixels[1] = 0; pixels[1] = 1; // etc... } glTexImage2D(..., getPixels()); Does glTexImage2D use that reference or copy the pixels into it's own memory? If the answer is the former, then should I do the following? int *p = getPixels(); glTexImage2D(..., p); /* Just changed to delete[], because delete * would only delete the first element! */ delete[] p;
From this quote in the man page, it sounds like glTexImage2D allocates its own memory. This would make sense, ideally the OpenGL API would send data to be stored on the graphics card itself (if drivers/implementation/etc permitted). In GL version 1.1 or greater, pixels may be a null pointer. In this case texture memory is allocated to accommodate a texture of width width and height height. You can then download subtextures to initialize this texture memory. The image is undefined if the user tries to apply an uninitialized portion of the texture image to a primitive. So yea, I'd imagine there is no harm in freeing the memory once you've generated your texture.
766,172
766,608
How to make this Matrix class easier to use in the debugger
I've written a C++ matrix template class. It's parameterized by its dimensions and by its datatype: template<int NRows, int NCols, typename T> struct Mat { typedef Mat<NRows, NCols, T> MyType; typedef T value_type; typedef const T *const_iterator; typedef T *iterator; enum { NumRows = NRows }; enum { NumCols = NCols }; T m_data[NRows * NCols]; // ... Lot's of operations and functions ... // Some overloads typedef Mat<2, 1, int> Vec2i; typedef Mat<2, 1, float> Vec2f; typedef Mat<3, 1, float> Vec3f; typedef Mat<4, 1, unsigned char> Vec4ub; typedef Mat<4, 4, float> Mat44f; typedef Vec3f Vector; typedef Vec4ub Color; typedef Vec2f LonLat; It's a fantastic little class that handles lots of vector arithmetic and linear algebra. Also, it is able to interface easily with both low level code (OpenGL) and high level code (PID and Kalman filters). Its design seems sound to me, but that's not what this question is about. This class has one dreadful flaw: it is a dread to use in the debugger. Because it is a struct that contains an array, there is always that one annoying level of indirection when examining variables in Xcode (and I assume in VisualStudio). This is further aggravated by the fact that Xcode sometimes fails to follow chains of pointers correctly and I can't examine the values at all. This happens if I have, say, a vector of these objects. I realize that I could perhaps customize the debugger to somehow work with my type. But I was wondering if there is perhaps a different way to store the data of my Matrix so that it has better "debugability"? This is more of a "use your imagination" type question than one looking for a best-practices design. I'm just curious what alternative class layouts could be used while still maintaining the generic nature of the code.
XCode allows you to create custom data formatters to format the data in the debugger in any way you'd want.
766,303
766,717
Why does Valgrind not like my usage of glutCreateWindow?
I'm using the following code... 169: const char *title = Title.c_str(); 170: glutCreateWindow(title); ... Valgrind gives me the following ... ==28841== Conditional jump or move depends on uninitialised value(s) ==28841== at 0x6FF7A4C: (within /usr/lib64/libGLcore.so.180.44) ==28841== by 0x6FF81F7: (within /usr/lib64/libGLcore.so.180.44) ==28841== by 0x7289B36: (within /usr/lib64/libGLcore.so.180.44) ==28841== by 0x728A757: _nv000133gl (in /usr/lib64/libGLcore.so.180.44) ==28841== by 0x4EAB9E9: (within /usr/lib64/libGL.so.180.44) ==28841== by 0x4EAEA81: (within /usr/lib64/libGL.so.180.44) ==28841== by 0x4EB1D81: (within /usr/lib64/libGL.so.180.44) ==28841== by 0x4EA782B: glXCreateNewContext (in /usr/lib64/libGL.so.180.44) ==28841== by 0x54DF9AA: fgOpenWindow (in /usr/lib64/libglut.so.3.8.0) ==28841== by 0x54DE062: fgCreateWindow (in /usr/lib64/libglut.so.3.8.0) ==28841== by 0x54DF300: glutCreateWindow (in /usr/lib64/libglut.so.3.8.0) ==28841== by 0x4146CE: vimrid::glut::GlutApplication::Init() (GlutApplication.cpp:170) But what is uninitialized? The title variable is initialized with the value of Title.c_str() and Title is a class member which is initialized in the constructor member initialization list... class VimridApplication { // ... public: std::string Title; // ... } VimridApplication::VimridApplication() : Title("Untitled VimridApplication") { // ... } class GlutApplication : public VimridApplication { // ... }
Valgrind comes with some default error suppression, but that probably does not cover libCLcore. The error-checking tools detect numerous problems in the base libraries, such as the GNU C library, and the X11 client libraries, which come pre-installed on your GNU/Linux system. You can't easily fix these, but you don't want to see these errors (and yes, there are many!) So Valgrind reads a list of errors to suppress at startup. A default suppression file is created by the ./configure script when the system is built. You can create your own error suppressions that you know are irrelevant to your code.
766,477
766,526
Are there equivalents to pread on different platforms?
I am writing a concurrent, persistent message queue in C++, which requires concurrent read access to a file without using memory mapped io. Short story is that several threads will need to read from different offsets of the file. Originally I had a file object that had typical read/write methods, and threads would acquire a mutex to call those methods. However, it so happened that I did not acquire the mutex properly somewhere, causing one thread to move the file offset during a read/write, and another thread would start reading/writing to an incorrect part of the file. So, the paranoid solution is to have one open file handle per thread. Now I've got a lot of file handles to the same file, which I'm assuming can't be great. I'd like to use something like pread, which allows passing in of the current offset to read/write functions. However, the function is only available on linux, and I need equivalent implementations on windows, aix, solaris and hpux, any suggestions?
On Windows, the ReadFile() function can do it, see the lpOverlapped parameter and this info on async IO.
766,605
766,633
Can you embed for loops (in each other) in C++
I am working on a merge sort function. I got the sort down - I am trying to get my merge part finished. Assume that I am learning C++, have cursory knowledge of pointers, and don't understand all the rules of std::vector::iterator's (or std::vector's, for that matter). Assume that num is the size of the original std::vector that have copied (std::copy) values from an array of size "int ar[num]." Assume that farray has the values of (0 to (num / 2)) and sarray has the values of ((num / 2) to num). int num = original.size(); std::vector<int> final(num); for (std::vector<int>::iterator it = farray.begin(); it != farray.end(); ++it) { for (std::vector<int>::iterator iter = sarray.begin(); iter != sarray.end(); ++iter) { if (*it > *iter) final.push_back(*it); else final.push_back(*iter); } } This code compiles and my latest stable build of Bloodshed Dev-C++ does not throw any warnings or errors. I don't know if this is valid, I still need to try and cout all the values of final. I just want to know if this is common, prone to errors, or just bad style. And, if so, how you would
It's valid... but a for loop probably isn't what you want. When you use two for loops, your inner loop keeps going back to the start every time the outer loop loops. So if your vectors contain: farray: 10 9 8 4 3 sarray: 7 6 4 3 1 Then your final array will contain something like: 10 10 10 10 10 9 9 9 9 9 8 8 8 8 8 7 6 4 4 4 7 6 4 3 3 because you are testing every single combination, and adding the larger one to the final list. A better solution might be to remember an iterator for each list, and just use one loop. Rather than looping over a list, just go through both of them together - if sarray has the larger number, then increment your sarray iterator, and compare that with the old farray iterator. Stop your loop when both sarray and farray are empty. vector<int> fiter = farray.begin(); vector<int> siter = sarray.begin(); vector<int> final; // Let's traverse both farray and sarray. // We'll want to stop this loop once we've traversed both lists. while (fiter != farray.end() && siter != sarray.end()) { if (fiter == farray.end()) { // we must have gone right through farray - // so use the value from sarray, and go to the next one final.push_back(*siter); siter++; } else if (siter == sarray.end()) { // we must have gone right through sarray - // so use the value from farray, and go to the next one final.push_back(*fiter); fiter++; } else if (*siter > *fiter) { // siter is the bigger of the two - add it to the final list, and // go to the next sarray entry final.push_back(*siter); siter++; } else // *fiter >= *siter { // fiter is the bigger of the two - add it to the final list, and // go to the next farray entry final.push_back(*fiter); fiter++; } } I haven't tested it - and if this is for homework, then please try to understand what I've done, go away and write it yourself, rather than copy+paste.
766,816
766,819
Why does this compile in C but not C++ (sigaction)?
I get the following errors when trying to compile the below code using g++. When I compile it using gcc it works fine (other than a few warnings). Any help appreciated. g++ ush7.cpp ush7.cpp: In function ‘int signalsetup(sigaction*, sigset_t*, void (*)(int))’: ush7.cpp:93: error: expected unqualified-id before ‘catch’ ush7.cpp:95: error: expected primary-expression before ‘catch’ ush7.cpp:95: error: expected `;' before ‘catch’ ush7.cpp:97: error: expected primary-expression before ‘catch’ ush7.cpp:97: error: expected `;' before ‘catch’ ush7.cpp:100: error: expected primary-expression before ‘catch’ ush7.cpp:100: error: expected `)' before ‘catch’ ush7.cpp:108: error: expected `)' before ‘;’ token ush7.cpp:108: error: expected `)' before ‘;’ token ush7.cpp: In function ‘int makeargv(const char*, const char*, char***)’: ush7.cpp:137: error: invalid conversion from ‘void*’ to ‘char*’ ush7.cpp:145: error: invalid conversion from ‘void*’ to ‘char**’ int signalsetup(struct sigaction *def, sigset_t *mask, void (*handler)(int)) { struct sigaction catch; catch.sa_handler = handler; /* Set up signal structures */ def->sa_handler = SIG_DFL; catch.sa_flags = 0; def->sa_flags = 0; if ((sigemptyset(&(def->sa_mask)) == -1) || (sigemptyset(&(catch.sa_mask)) == -1) || (sigaddset(&(catch.sa_mask), SIGINT) == -1) || (sigaddset(&(catch.sa_mask), SIGQUIT) == -1) || (sigaction(SIGINT, &catch, NULL) == -1) || (sigaction(SIGQUIT, &catch, NULL) == -1) || (sigemptyset(mask) == -1) || (sigaddset(mask, SIGINT) == -1) || (sigaddset(mask, SIGQUIT) == -1)) return -1; return 0; }
catch is a keyword in C++ but not in C. Please see my related answer C is not a proper subset of C++ here, or even better here.
767,009
767,060
Wrapping up a C++ API in Java or .NET
Has anyone successfully "wrapped up" a C++ API in Java or .NET? I have an application that provides a C++ API for writing plug-ins. What I'd like to do is access that API from .NET or Java. Would I need to use COM, or are there simpler/better alternatives?
If you have a very straight forward method signatures (i.e. methods that takes and returns primitive types such as int, char[], void* ... etc), it is reasonably easy to do so in .NET and still possible but a bit harder in Java with JNI. However, if your class methods uses modern C++ programming techniques such as boost shared pointers and STL containers then it is a very different story. You will need to be really careful with memory management in this case. EDIT: It is gonna be even more interesting if the method has C++ template arguments because C++ template system is very different from C# or Java generics in that it is only a compile time mechanism. Basically this means the signature of the method or class is different every time you pass a different data type to the template argument. This made the method impossible to wrap in C# or Java.
767,099
767,174
Is it good form to compare against changing values in a loop in C++?
No doubt some of you have seen my recent posting, all regarding the same program. I keep running into problems with it. To reiterate: still learning, not very advanced, don't understand pointers very well, not taking a class, don't understand OOP concepts at all, etc. This code just merges two sorted vectors, farray and sarray, into a single sorted vector. At least, I hope that's what it does. Tell me: //int num is to find the size of the original vector and //build up farray and sarray; not used in the merge process int num = original.size() std::vector<int> final; std::vector<int>::iterator it = farray.begin(); std::vector<int>::iterator iter = sarray.begin(); //farray.size() == (0 thru (num / 2)) //sarray.size() == ((num / 2) thru num) for (;it != farray.end() && iter != sarray.end();) { if (*it > *iter) { final.push_back(*it); it++; } else { final.push_back(*iter); iter++; } if (it == farray.end()) { for (int i = 0; iter < sarray.end(); i++) { final.push_back(*iter); } } if (iter == sarray.end()) { for (int i = 0; it < farray.end(); i++) { final.push_back(*iter); } } } I rewrote the merge part of my merge sort function so as to...well, make it work. I actually have several questions about this code: Is it good form to compare against std::vector::iterators it && iter for my last two if statements if the for loop might change them on its next pass? Will the values of iter and it change on this loop's last pass and screw up my code? Will putting my last if statements before the *it and *iter comparison? Does the end() member function refer to the last value of whatever is calling it? It seems like it might extend past it somehow. EDIT: I will respond to all replies tomorrow, so check back then if you want to hear more. It's past midnight. G'night.
1 . It's fine to compare iterators which are from the same container as a for loop condition, but this only makes sense if you are moving one or other iterators in either the increment part if the for loop statement or in the body of the for loop itself. In this for loop you compare iter against sarray.end() but the for loop never changes iter. This means that either there will be no iterations or the for loop will never terminate. Also, you probably want to use != and not < for the comparison. == and != work for all iterators, < doesn't. for (int i = 0; iter != sarray.end(); i++) { final.push_back(*iter); } As iter starts where you want the loop to begin, you may want something like this: for (; iter != sarray.end(); ++iter) { final.push_back(*iter); } As you're still learning (although aren't we all!), it's probably instructive to work through an algorithm like this, but you should be aware of std::merge which probably does what you want. std::merge( farray.begin(), farray.end(), sarray.begin(), sarray.end(), std::back_inserter( final ) ); (You need to #include <iterator> and <algorithm>.) 2 . I don't see incrementing iter or it in the outer for loop invalidating the logic in the later for loops, the point in 1. aside. 3 . end() points to one past the end of a container, so you can use it for loop termination checks, but you shouldn't try to dereference an iterator which is "==" to ".end()".
767,477
767,630
template specialization for static member functions; howto?
I am trying to implement a template function with handles void differently using template specialization. The following code gives me an "Explicit specialization in non-namespace scope" in gcc: template <typename T> static T safeGuiCall(boost::function<T ()> _f) { if (_f.empty()) throw GuiException("Function pointer empty"); { ThreadGuard g; T ret = _f(); return ret; } } // template specialization for functions wit no return value template <> static void safeGuiCall<void>(boost::function<void ()> _f) { if (_f.empty()) throw GuiException("Function pointer empty"); { ThreadGuard g; _f(); } } I have tried moving it out of the class (the class is not templated) and into the namespace but then I get the error "Explicit specialization cannot have a storage class". I have read many discussions about this, but people don't seem to agree how to specialize function templates. Any ideas?
When you specialize a templated method, you must do so outside of the class brackets: template <typename X> struct Test {}; // to simulate type dependency struct X // class declaration: only generic { template <typename T> static void f( Test<T> ); }; // template definition: template <typename T> void X::f( Test<T> ) { std::cout << "generic" << std::endl; } template <> inline void X::f<void>( Test<void> ) { std::cout << "specific" << std::endl; } int main() { Test<int> ti; Test<void> tv; X::f( ti ); // prints 'generic' X::f( tv ); // prints 'specific' } When you take it outside of the class, you must remove the 'static' keyword. Static keyword outside of the class has a specific meaning different from what you probably want. template <typename X> struct Test {}; // to simulate type dependency template <typename T> void f( Test<T> ) { std::cout << "generic" << std::endl; } template <> void f<void>( Test<void> ) { std::cout << "specific" << std::endl; } int main() { Test<int> ti; Test<void> tv; f( ti ); // prints 'generic' f( tv ); // prints 'specific' }
767,579
767,709
Exporting classes containing `std::` objects (vector, map etc.) from a DLL
I'm trying to export classes from a DLL that contain objects such as std::vectors and std::strings - the whole class is declared as DLL export through: class DLL_EXPORT FontManager { The problem is that for members of the complex types I get this warning: warning C4251: 'FontManager::m__fonts' : class 'std::map<_Kty,_Ty>' needs to have dll-interface to be used by clients of class 'FontManager' with [ _Kty=std::string, _Ty=tFontInfoRef ] I'm able to remove some of the warnings by putting the following forward class declaration before them even though I'm not changing the type of the member variables themselves: template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>; template class DLL_EXPORT std::vector<tCharGlyphProviderRef,std::allocator<tCharGlyphProviderRef> >; std::vector<tCharGlyphProviderRef> m_glyphProviders; Looks like the forward declaration "injects" the DLL_EXPORT for when the member is compiled but is it safe? Does it really change anything when the client compiles this header and uses the std:: container on his side? Will it make all future uses of such a container DLL_EXPORT (and possibly not inline)? And does it really solve the problem that the warning tries to warn about? Is this warning anything I should be worried about or would it be best to disable it in the scope of these constructs? The clients and the DLL will always be built using the same set of libraries and compilers and those are header only classes... I'm using Visual Studio 2003 with the standard STD library. Update I'd like to target you more though as I see the answers are general and here we're talking about std containers and types (such as std::string) - maybe the question really is: Can we disable the warning for standard containers and types available to both the client and the DLL through the same library headers and treat them just as we'd treat an int or any other built-in type? (It does seem to work correctly on my side) If so would should be the conditions under which we can do this? Or should maybe using such containers be prohibited or at least ultra care taken to make sure no assignment operators, copy constructors etc will get inlined into the DLL client? In general I'd like to know if you feel designing a DLL interface having such objects (and for example using them to return stuff to the client as return value types) is a good idea or not and why, I'd like to have a "high level" interface to this functionality... Maybe the best solution is what Neil Butterworth suggested - creating a static library?
When you touch a member in your class from the client, you need to provide a DLL-interface. A DLL-interface means, that the compiler creates the function in the DLL itself and makes it importable. Because the compiler doesn't know which methods are used by the clients of a DLL_EXPORTED class it must enforce that all methods are dll-exported. It must enforce that all members which can be accessed by clients must dll-export their functions too. This happens when the compiler is warning you of methods not exported and the linker of the client sending errors. Not every member must be marked with with dll-export, e.g. private members not touchable by clients. Here you can ignore/disable the warnings (beware of compiler generated dtor/ctors). Otherwise the members must export their methods. Forward declaring them with DLL_EXPORT does not export the methods of these classes. You have to mark the according classes in their compilation-unit as DLL_EXPORT. What it boils down to ... (for not dll-exportable members) If you have members which aren't/can't be used by clients, switch off the warning. If you have members which must be used by clients, create a dll-export wrapper or create indirection methods. To cut down the count of externally visible members, use approaches such as the PIMPL idiom. template class DLL_EXPORT std::allocator<tCharGlyphProviderRef>; This does create an instantiation of the template specialization in the current compilation unit. So this creates the methods of std::allocator in the dll and exports the corresponding methods. This does not work for concrete classes as this is only an instantiation of template classes.
767,644
767,688
How would I write a Photoshop plugin for an image format?
I have an image format and Photoshop doesn't support it. I've been tasked with writing a plugin to import or open the format, but there seems to be little information out there and what information I can find is all about writing filters. However, I want to import/export/open, not filter it.
My experience with photoshop import filters is roughly six years old, so take this comment with a grain of (old) salt. I just took the import filter example code from the official SDK as a boilerplate and added my own decoding function. It was a straight forward job and took a week from start to finish. If I remember right the worst thing was: Getting the compiler settings right and compile the example code (two days) Learning how the Photoshop GUI works. It was not standard win32 back then but something half mac resource based. I think they've changed that though.
767,770
768,199
Explorer thumbnails (winXP)
I have a file format I need to be able to show in explorer thumbnails. Since the target system is windows XP, the Vista PreviewHandler API will not be suitable. Ill be using c++. How would I do it?
You'll need to register a shell extension for your file type. The extension contains code that extracts/generates the thumbnail by implementing the IExtractImage interface. See: IExtractImage Interface on MSDN
767,995
768,012
using std::find_if with std::string
I'm being stupid here but I can't get the function signature for the predicate going to find_if when iterating over a string: bool func( char ); std::string str; std::find_if( str.begin(), str.end(), func ) ) In this instance google has not been my friend :( Is anyone here?
#include <iostream> #include <string> #include <algorithm> bool func( char c ) { return c == 'x'; } int main() { std::string str ="abcxyz";; std::string::iterator it = std::find_if( str.begin(), str.end(), func ); if ( it != str.end() ) { std::cout << "found\n"; } else { std::cout << "not found\n"; } }
768,182
768,195
C/C++: How to convert 6bit ASCII to 7bit ASCII
I have a set of 6 bits that represent a 7bit ASCII character. How can I get the correct 7bit ASCII code out of the 6 bits I have? Just append a zero and do an bitwise OR? Thanks for your help. Lennart
ASCII is inherently a 7-bit character set, so what you have is not "6-bit ASCII". What characters make up your character set? The simplest decoding approach is probably something like: char From6Bit( char c6 ) { // array of all 64 characters that appear in your 6-bit set static SixBitSet[] = { 'A', 'B', ... }; return SixBitSet[ c6 ]; } A footnote: 6-bit character sets were quite popular on old DEC hardware, some of which, like the DEC-10, had a 36-bit architecture where 6-bit characters made some sense.
768,351
770,662
Complete example using Boost::Signals for C++ Eventing
I’m aware of the tutorial at boost.org addressing this: Boost.org Signals Tutorial, but the examples are not complete and somewhat over simplified. The examples there don’t show the include files and some sections of the code are a little vague. Here is what I need: ClassA raises multiple events/signals ClassB subscribes to those events (Multiple classes may subscribe) In my project I have a lower-level message handler class that raises events to a business class that does some processing of those messages and notifies the UI (wxFrames). I need to know how these all might get wired up (what order, who calls who, etc).
The code below is a minimal working example of what you requested. ClassA emits two signals; SigA sends (and accepts) no parameters, SigB sends an int. ClassB has two functions which will output to cout when each function is called. In the example there is one instance of ClassA (a) and two of ClassB (b and b2). main is used to connect and fire the signals. It's worth noting that ClassA and ClassB know nothing of each other (ie they're not compile-time bound). #include <boost/signal.hpp> #include <boost/bind.hpp> #include <iostream> using namespace boost; using namespace std; struct ClassA { signal<void ()> SigA; signal<void (int)> SigB; }; struct ClassB { void PrintFoo() { cout << "Foo" << endl; } void PrintInt(int i) { cout << "Bar: " << i << endl; } }; int main() { ClassA a; ClassB b, b2; a.SigA.connect(bind(&ClassB::PrintFoo, &b)); a.SigB.connect(bind(&ClassB::PrintInt, &b, _1)); a.SigB.connect(bind(&ClassB::PrintInt, &b2, _1)); a.SigA(); a.SigB(4); } The output: Foo Bar: 4 Bar: 4 For brevity I've taken some shortcuts that you wouldn't normally use in production code (in particular access control is lax and you'd normally 'hide' your signal registration behind a function like in KeithB's example). It seems that most of the difficulty in boost::signal is in getting used to using boost::bind. It is a bit mind-bending at first! For a trickier example you could also use bind to hook up ClassA::SigA with ClassB::PrintInt even though SigA does not emit an int: a.SigA.connect(bind(&ClassB::PrintInt, &b, 10)); Hope that helps!
768,585
768,605
Why does my Visual Studio Win32 project require .NET 3.5 SP1 to install?
Using Visual Studio 2008, I created a C++ Win32 project. To release the program, I made a Visual Studio setup project within the same solution. The setup.exe prompts my users to install .NET 3.5 SP1, which is often a 15+ minute install and only allowed to administrator level accounts. If they do not there is an error along the lines of "wrong framework". I am confused over what in my project requires .NET 3.5 SP1. I suspect just because that is the framework my PC is on... Is there a way to broaden which frameworks it will run on? The code is mostly Win32 API calls. Just in case, here are my dependencies and #includes: gdiplus.lib comctl32.lib Winmm.lib d3d9.lib (The setup project automatically added comdlg32.dll, then tells me to exclude it.) #include <windows.h> #include <tchar.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <string.h> #include <commctrl.h> #include <process.h> #include <sstream> #include <math.h> #include <d3d9.h> #include <time.h> #include <gdiplus.h> My guess is that somewhere through windows.h there is a WIN_VER or similar version setting that is set to .NET 3.5 SP1, and this is where the dependency comes from. If that is the case, and I need to define a different version, I would love to hear everyone's advice on does / don'ts / and how-to and how far back can I go for maximum inclusion.
In VS 2008 the default target framework is .NET 3.5. For C++ on the Common Properties page there's a "Targeted Framework" drop down, but on the test project I created it's greyed out, so it looks like this can't be changed after the project has been created. I created a second C++ project and selected the 2.0 Template from the New Project dialog and that had 2.0 in the "Targeted Framework". So if you want to target a lower version of the framework it looks like you've got to create your project correctly in the first place. EDIT: As to which version of the framework you should target - it all depends(!) Do you need to use any of the 3.0 or 3.5 features? If not then go for 2.0. If you do then select that one and take the hit of the download. I can't say how likely it is that any class of user will have a particular version installed. As time goes on it will be increasingly likely that they will have 3.5 installed as other apps will require it.
768,588
768,620
Is the const value parameter in definition but not declaration really C++?
This is similar to (but different from) this question. Here is some simple test code to illustrate some weirdness I have discovered with Sun CC: //---------------main.cpp #include "wtc.hpp" int main(int, char**) { testy t; t.lame(99); return 0; } //--------------wtc.hpp #ifndef WTC_HPP_INCLUDED #define WTC_HPP_INCLUDED class testy { public: void lame(int ); }; #endif //---------------wtc.cpp #include <iostream> #include "wtc.hpp" void testy::lame(const int a) { std::cout << "I was passed " << a << "\n"; } //---------------makefile #CXX=CC CXX =g++ #CXXFLAGS= -g CXXFLAGS= -g3 -Wall -Werror OBJECTS=$(patsubst %.cpp,%.o,$(wildcard *.cpp)) all : $(OBJECTS) $(CXX) $(CXXFLAGS) -o $@ $^ .PHONY: clean clean : rm *.o When this was compiled using g++ it compiles, links and does what you would expect when run. You can also add a ++a; in testy::lame() and the compiler will complain about changing a read-only variable (as it should). However when I compile using CC, I get the following linker error: CC -g -c -o main.o main.cpp CC -g -c -o wtc.o wtc.cpp CC -g -o all main.o wtc.o Undefined first referenced symbol in file void testy::lame(int) main.o ld: fatal: Symbol referencing errors. No output written to all make: *** [all] Error 1 checking the object code with nm and C++filt, I find that the g++ version creates a testy::lame(int) symbol, whereas CC creates testy::lame(const int) , hence the linker error. I looked it up in Stroustrup's book, but can't find this technique mentioned (doesn't mean it's not there!); so is this really a compiler bug, or just a hack that works everywhere else but Solaris?
This looks like a compiler problem in CC. The C++ standard says (in 13.1 Overloadable declarations): Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called. But there are const/volatile modifiers that can participate in overloading, as the standard mentions shortly afterwards: Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.
768,844
899,624
non-unicode WM_CHAR in unicode windows
I have written a DLL which exports a function that creates a window using RegisterClassExW and CreateWindowExW. Every message is retrieved via GetMessageW(&msg, wnd_handle, 0, 0); TranslateMessage(&msg); DispatchMessageW(&msg); Also there is a program which loads the DLL and calls the function. Despite the Unicode window creation method, the wParam in the WM_CHAR message always contains ASCII characters, even if I type some non-ASCII symbols or use Alt+(code). Instead of UTF-16, the wParam contains some ASCII character between 'A' and 'z'. The WndProc is a static function inside the DLL. The problem doesn't occur when all the window-related code is inside one program. Is there a way to always have Unicode WM_CHAR messages inside the DLL's window?
the problem was in the message retrieval process. I used GetMessage() with the handle of my window instead of just 0, GetMessageW(&msg, wnd_handle, 0, 0) instead of GetMessageW(&msg, 0, 0, 0). In this way, the WM_INPUTLANGCHANGEREQUEST messages were swallowed and the locale remained English.
768,853
768,869
TinyXML: how to parse a file pointer
I'm trying to connect the output of popen, a file pointer, to the input of TinyXML. According to the main page, the best way to do it is using the parse method: C style input: * based on FILE* * the Parse() and LoadFile() methods I believe I need to use the TIXML_USE_STL to get to this. How do I go about finding examples and import it? A reply since deleted pointed me in the right direction on the docs http://www.grinninglizard.com/tinyxmldocs/index.html Thanks. Now, i just need to figure out how to link and import it.
I'm not hugely familiar with TinyXML, but does LoadFile() not work in its overloaded version which takes a FILE *? http://www.grinninglizard.com/tinyxmldocs/classTiXmlDocument.html#a12 EDIT: Ah, the problem is that TinyXML doesn't support reading from a stream (see the link above). Your only choice then is to read the stream manually into a buffer and pass it to TinyXML's Parse().
768,982
769,087
How to properly use structs inside a class?
Using: VS2008, Win32, C/C++ I'm trying to encapsulate my entire dialog window into a class for reusability. Sort of like a custom control. In doing this, I am moving my seperate functions into a class. The following struct design though is giving me problems, with Visual Studio outputting: error C2334 '{'. It's a simple message map layout. But I can't seem to escape this C2334 error. :( Here is my class code snippet. class CScrollingListDlg { private: LRESULT DoCommandMain (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT DoPaintMain (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT DoAnimationTimer (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT DoHandleTouch (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT DoDestroyMain (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam); // // message maps // // Generic defines and data types. struct decodeUINT { UINT Code; LRESULT (*Fxn)(HWND, UINT, WPARAM, LPARAM); }; struct decodeCMD { UINT Code; LRESULT (*Fxn)(HWND, WORD, HWND, WORD); }; // WM_Message dispatch table for MainWndProc. // // *** error C2334 '{' *** // const struct decodeUINT MainMessages[] = { WM_PAINT, DoPaintMain, WM_DESTROY, DoDestroyMain, WM_QUIT, DoDestroyMain, WM_COMMAND, DoCommandMain, }; }; What am I missing here? Thanks.
You cannot specify initialisers for non-static members that way -- you would normally need to declare the array and then populate it inside the constructor... Except that, in fact there is no way to initialise const member arrays in C++ (see this thread). If you are prepared to share MainMessages amongst all instances of CScrollingListDlg (which I suspect was your intention all along), you should make it static, in which case you can declare: static const decodeUINT MainMessages[]; // "struct" keyword unnecessary inside the class definition of CScrollingListDlg, and then define it outside the class: const CScrollingListDlg::decodeUINT CScrollingListDlg::MainMessages[] = { WM_PAINT, DoPaintMain, WM_DESTROY, DoDestroyMain, WM_QUIT, DoDestroyMain, WM_COMMAND, DoCommandMain, // The comma *is* allowed -- thanks Josh! }; In order for this to actually compile, you'll need to make DoPaintMain(), DoDestroyMain(), etc. static as well -- as it stands, they are all per-object methods that implicitly take a this pointer, so they can't actually be contained in a function pointer of type LRESULT (*Fxn)(HWND, UINT, WPARAM, LPARAM). (You could leave them as non-static methods and change the pointer type in decodeUINT to a pointer-to-member-function type, but that's probably not what you want.) [EDIT: Thanks to Josh for some helpful comments!]
769,026
769,056
stl algorithm in class
Is there a way to use stl algorithms like find() and find_if() in a container of objects? Ex.:With find() find the element whit name "abc" in a vector of class Alfhabetic.
You can define a comparing predicate (functor). Here is a generic implementation: struct AlphabeticNameComp { AlphabeticNameComp( const std::string& toCompare) : toCompare_( toCompare) { } bool operator()( const Alphabetic& obj) const { return toCompare_ == obj.name(); } private: const std::string toCompare_; }; In a vector of Alphabetic elements std::vector< Alphabetic> vect; you can run a search like: std::find_if( vect.begin(), vect.end(), AlphabeticNameComp( "abc"));
769,097
769,161
Choosing a STL container with uniqueness and which keeps insertion ordering
I am unable to decide which STL container to use in the following case: I want to preserve the order of insertion of the elements The elements in the container have to be unique. Is there any readymade container available for this? I don't want to use a vector and then perform a std::find before doing a push_back every time.
Boost MultiIndex should be able to do exactly what you want - you can just use one sequenced index to get the "ordered by insertion order" requirement, and either a hashed_unique or ordered_unique index to get the uniqueness requirement.
769,537
770,837
Hook LoadLibrary call from managed code
We would like to hook calls to LoadLibrary in order to download assemblies that are not found. We have a handler for ResolveAssembly that handles the managed assemblies, but we also need to handle unmanaged assemblies. We have attempted to hook LoadLibrary calls by re-writing the imports table via techniques specified in "Programming Applications for Microsoft Windows", but when we call WriteProcessMemory() we get a permission denied error (998). (Yes, we're running with elevated privs) Has anyone succeeded in re-writing the imports table while the CLR is loaded? Can anyone point me in the right direction? Update: We resolved the permission denied issue, but now when we iterate the Imports Table of a mixed assembly (managed + unmanaged), the only entry we find is mscoree.dll. Does anyone know how to find the native imports? (we're working in C++/CLI).
I have successfully hooked from Managed code. However, I did it by injecting an unmanaged DLL into the remote process and have it rewrite the import table in DllMain. You may want to consider this method. Here is my hooking function: //structure of a function to hook struct HookedFunction { public: LPTSTR moduleName; LPTSTR functionName; LPVOID newfunc; LPVOID* oldfunc; }; BOOL Hook(HMODULE Module, struct HookedFunction Function) { //parse dos header IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) return 0; //not a dos program //parse nt header IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)(dos_header->e_lfanew + (SIZE_T)Module); if (nt_header->Signature != IMAGE_NT_SIGNATURE) return 0; //not a windows program //optional header (pretty much not optional) IMAGE_OPTIONAL_HEADER optional_header = nt_header->OptionalHeader; if (optional_header.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0; //no optional header IMAGE_IMPORT_DESCRIPTOR* idt_address = (IMAGE_IMPORT_DESCRIPTOR*)(optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + (SIZE_T)Module); if (!optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size) return 0; //no import table //enumerate the import dlls BOOL hooked = false; for(IMAGE_IMPORT_DESCRIPTOR* i = idt_address; i->Name != NULL; i++) //check the import filename if (!_stricmp(Function.moduleName, (char*)(i->Name + (SIZE_T)Module))) //enumerate imported functions for this dll for (int j = 0; *(j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module)) != NULL; j++) //check if the function matches the function we are looking for if (!_stricmp(Function.functionName, (char*)(*(j + (SIZE_T*)(i->OriginalFirstThunk + (SIZE_T)Module)) + (SIZE_T)Module + 2) )) { //replace the function LPVOID* memloc = j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module); if (*memloc != Function.newfunc) { //not already hooked DWORD oldrights; DWORD newrights = PAGE_READWRITE; VirtualProtect(memloc, sizeof(LPVOID), newrights, &oldrights); if (Function.oldfunc && !*Function.oldfunc) *Function.oldfunc = *memloc; *memloc = Function.newfunc; VirtualProtect(memloc, sizeof(LPVOID), oldrights, &newrights); } hooked = true; } return hooked; }
769,867
769,921
How to use BOOST_FOREACH with two std::maps?
I have code that looks essentially like this: std::map<int, int> map1, map2; BOOST_FOREACH(int i, map1) { // do steps 1-5 here... } BOOST_FOREACH(int i, map2) { // do steps 1-5 (identical to above) here... } Is there any way to concatenate the maps to eliminate the duplicate code in the second loop? Or a way to extend BOOST_FOREACH to iterate over two different maps in one go? Obviously I don't want to increase the time complexity of the program (otherwise I could just create a new map and insert into it map1 and map2). I have a feeling I am missing something rudimentary here.
You could define a function: typedef std::map<int, int> IntMap; void doStuffWithInt(IntMap::value_type &i) { // steps 1 to 5 } BOOST_FOREACH(IntMap::value_type &i, map1) doStuffWithInt(i); BOOST_FOREACH(IntMap::value_type &i, map2) doStuffWithInt(i); Although in that case it might be even simpler to use std::for_each: for_each(map1.begin(), map1.end(), doStuffWithInt); for_each(map2.begin(), map2.end(), doStuffWithInt);
770,344
770,374
Visual C++ - Linking plugin DLL against EXE?
I'm in the process of porting a large C++ application from Linux (gcc) to Windows (Visual C++ 2008) and am having linker issues with plugins. On Linux this wasn't an issue, as .so supports runtime symbol lookup, but dll does not seem to support this. Some background information: The application (the host), which hosts a scripting environment, provides interfaces to plugins (shared libraries that are loaded at runtime by script API calls), allowing the host and the scripting API to be extended without recompiling the host application. On Linux this is just a matter of including the host application's headers in the plugin source, but on Windows I'm receiving linker errors. I'm not sure exactly what I need to link with for Visual C++ to resolve these symbols. One of our dependencies (open source, LGPL) has preprocessor declarations that it uses to insert __declspec(dllexport) and __declspec(dllimport) into it's headers. Some prior research indicates that I may have to do this as well, but I'd like to be sure before I go modifying a whole bunch of core headers. (I was previously able to get this working on MinGW, but we've decided that supporting Visual Studio is a requirement for this sort of commercial project.) My question, in a nutshell: How do I link runtime-loaded dlls against a host exe in Visual C++? Edit: To clarify the problem with an example, I have a class in my host application, Object, which represents the base type of an object that may be accessed by a script. In my plugins I have a number of classes which extend Object to perform other functions, such as integrating networking support or new visual elements. This means that my dll must link with symbols in the host exe, and I am not sure how to do that.
What do you mean by "runtime symbol lookup"? Do you mean dynamically loading libraries using dlopen and dlsym and so on? The equivalents in Windows are called LoadLibrary and GetProcAddress. In windows, you don't export symbols from a executable. You should only export them from a dll. The right way to solve your problem is to rearchitect so that the exported symbols are in a dll that the executable and other plugin dlls can link against.
770,577
771,391
Is the ANTLR parser generator best for a C++ app with constrained memory?
I'm looking for a good parser generator that I can use to read a custom text-file format in our large commercial app. Currently this particular file format is read with a handmade recursive parser but the format has grown and complexified to the point where that approach has become unmanageable. It seems like the ultimate solution would be to build a proper grammar for this format and then use a real parser generator like yacc to read it, but I'm having trouble deciding which such generator to use or even if they're worth the trouble at all. I've looked at ANTLR and Spirit, but our project has specific constraints beyond earlier answers that make me wonder if they're as appropriate for us. In particular, I need: A parser that generates C or C++ code with MSVC. ANTLR 3 doesn't support C++; it claims to generate straight C but the docs on getting it to actually work are sort of confusing. Severely constrained memory usage. Memory is at a huge premium in our app and even tiny leaks are fatal. I need to be able to override the parser's memory allocator to use our custom malloc(), or at the very least I need to give it a contiguous pool from which it draws all its memory (and which I can deallocate en bloc afterwards). I can spare about 200kb for the parser executable itself, but whatever dynamic heap it allocates in parsing has to get freed afterwards. Good performance. This is less critical but we ought to be able to parse 100kb of text in no more than a second on a 3ghz processor. Must be GPL-free. We can't use GNU code. I like ANTLRworks' IDE and debugging tools, but it looks like getting its C target to actually work with our app will be a huge undertaking. Before I embark on that palaver, is ANTLR the right tool for this job? The text format in question looks something like: attribute "FluxCapacitance" real constant asset DeLorean { //comment foo bar baz model "delorean.mdl" animation "gullwing.anm" references "Marty" loadonce } template TimeMachine { attribute FluxCapacitance 10 asset DeLorean }
ANTLR 3 doesn't support C++; it claims to generate straight C but the docs on getting it to actually work are sort of confusing. It does generate C, and furthermore, it works with Visual Studio and C++. I know this because I've done it before and submitted a patch to get it to work with stdcall. Memory is at a huge premium in our app and even tiny leaks are fatal. I need to be able to override the parser's memory allocator to use our custom malloc(), or at the very least I need to give it a contiguous pool from which it draws all its memory (and which I can deallocate en bloc afterwards). I can spare about 200kb for the parser executable itself, but whatever dynamic heap it allocates in parsing has to get freed afterwards. The antlr3c runtime, last time I checked does not have a memory leak, and uses the Memory pool paradigm which you describe. However, it does have one shortcoming in the API which the author refuses to change, which is that if you request the string of a node, it will create a new copy each time until you free the entire parser. I have no comment on the ease of using a custom malloc, but it does have a macro to define what malloc function to use in the entire project. As for the executable size, my compilation was about 100 kb in size including a small interpreter. My suggestion to you is to keep learning ANTLR, because it still fits your requirements and you probably need to sacrifice a little more time before it will start working for you.
770,728
770,855
mouse over transparency in Qt
I am trying to create an app in Qt/C++ with Qt4.5 and want the any active windows to change opacity on a mouseover event... As i understand it, there is no explicit mouseover event in Qt. However, I got rudimentary functioning by reimplementing QWidget's mousemoveevent() in the class that declares my mainwindow. But the mainwindow's mousemoveevent is not called whenever the mouse travels over any of the group boxes i have created in there (understandbly since QGroupbox has its own reimplementation of mousemoveevent). So as a cheap work around, I am still using the mousemoveevent of my mainwindow but a query the global mouse position and based on the (x,y) position of the mainwindow (obtained through ->pos()) and the window size (-> size -> rHeight and rWidth), I check if the mouse is within the bounds of the area of the mainwindow and change the opacity thus. This has had very limited success. The right border works fine, the the left changes opacity 4 pixels early. The top does not work (presumably because the mouse goes through the menubar and title bar) and the bottom changes way too early. I thought of creating an empty container QWidget class and then place all the rest in there, but i felt that it would still not solve the big issue of the base widget not receiving the mousemoveevent if it has already been implemented in a child widget. Please suggest any corrections/errors I have made in my method or any alternate methods to achieve this. p.s. I doubt this matters, but I am working Qt Creator IDE, not Qt integration into VS2008 (it's the same classes anyways - different compiler though, mingw)
Installing event filters for each of your child widgets might do the trick. This will allow your main window to receive child events such as the ones from you group boxes. You can find example code here.
770,994
771,544
Is there a way to call the STL Libraries of C++ from Java using JNI?
Is there a way to call STL libraries from JNI, I believe JNI provides a C like interface for native calls, how do we achieve this for the C++ template libraries?
I agree that if you're looking for just the plain STL, you could probably use a Java library instead. However, if you insist on wrapping STL, SWIG provides some STL wrapping in JNI out of the box (see this for the basic mechanism), which should produce relatively stable, tested code.
771,008
771,018
'for' loop vs Qt's 'foreach' in C++
Which is better (or faster), a C++ for loop or the foreach operator provided by Qt? For example, the following condition QList<QString> listofstrings; Which is better? foreach(QString str, listofstrings) { //code } or int count = listofstrings.count(); QString str = QString(); for(int i=0;i<count;i++) { str = listofstrings.at(i); //Code }
It really doesn't matter in most cases. The large number of questions on StackOverflow regarding whether this method or that method is faster, belie the fact that, in the vast majority of cases, code spends most of its time sitting around waiting for users to do something. If you are really concerned, profile it for yourself and act on what you find. But I think you'll most likely find that only in the most intense data-processing-heavy work does this question matter. The difference may well be only a couple of seconds and even then, only when processing huge numbers of elements. Get your code working first. Then get it working fast (and only if you find an actual performance issue). Time spent optimising before you've finished the functionality and can properly profile, is mostly wasted time.
771,012
771,065
Baffling Inline Behaviour from Random Number Generator Wrapper (C++)
I have a simple wrapper for an Mersenne twister random number generator. The purpose is to scale the number returned by the generator (between 0 and 1) to between argument defined limits (begin and end). So my function is inline float xlRandomFloat(float begin, float end) {return (begin+((end-begin)*genrand_real2()));} I don't believe the implementation of genrand_real2() function is important, but if I am wrong it can be found here The problem is the function does not return the translated result. The scaling (multiplying by (begin-end) seems to work correctly, but the addition of begin does not seem to be returned. So if I call xlRandomFloat(5,10) - I get values between 0 and 5. If I debug with GDB, and use the print function then it shows the correct result. So then I tried separating things into lines to see what happens inline float xlRandomFloat(float begin, float end) { float ret; ret=(((end-begin)*genrand_real2())); ret+=begin; return ret;}; When debugging, it jumped straight from the first line into the genrand_real2() function and skipped out every thing else entirely. That was really confusing so I thought it may have something to do with the inlining. I moved the file from this .hpp file to the .cpp and removed the inline keyword and everything works correctly. But why does this behavior occur, and how can I inline this function? Also, I am not sure if this is relevant, but often when I made changes to the sources, my Make compilation would say there is nothing to be done. Which is unusual since normally I expect make to pick up on changes in the sources and rebuild accordingly. Any ideas. Thanks Zenna
Okay, several things at work here. First, on the debugging, you describe what I'd think of as the more or less expected behavior, because when you inline a function, there's no generated code to go with the fromt matter of the function. So, the first statement there is ret=(((end-begin)*genrand_real2())); and the first step on that is to call genrand_real2(). If genrand_real2() is also inline, then you end up at the first statement in that, with no pause to catch your breath. Second, make sure you're really running the code you think you are. Try making from a clean directory --some C++ compilers make precompiled pieces that they preserve to speed compilation. Make sure your inline definition has been completely removes or commented out from the header files. m Thrd, make a very simple program with an inline and make sure it's behaving as you expect.
771,453
771,463
Copy map values to vector in STL
Working my way through Effective STL at the moment. Item 5 suggests that it's usually preferable to use range member functions to their single element counterparts. I currently wish to copy all the values in a map (i.e. - I don't need the keys) to a vector. What is the cleanest way to do this?
You can't easily use a range here because the iterator you get from a map refers to a std::pair, where the iterators you would use to insert into a vector refers to an object of the type stored in the vector, which is (if you are discarding the key) not a pair. I really don't think it gets much cleaner than the obvious: #include <map> #include <vector> #include <string> using namespace std; int main() { typedef map <string, int> MapType; MapType m; vector <int> v; // populate map somehow for( MapType::iterator it = m.begin(); it != m.end(); ++it ) { v.push_back( it->second ); } } which I would probably re-write as a template function if I was going to use it more than once. Something like: template <typename M, typename V> void MapToVec( const M & m, V & v ) { for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) { v.push_back( it->second ); } }
771,458
771,554
Improvements for this C++ stack allocator?
Any suggestions for my stack based allocator? (Except for suggestions to use a class with private/public members) struct Heap { void* heap_start; void* heap_end; size_t max_end; Heap(size_t size) { heap_start = malloc(size); heap_end = heap_start; max_end = size + (size_t) heap_start; } ~Heap() { ::free(heap_start); } void* allocate(size_t bytes) { size_t new_end = ((size_t) heap_end) + bytes; if( new_end > max_end ) throw std::bad_alloc(); void* output = heap_end; heap_end = (void*) new_end; return output; } }
You've implemented a stack based allocator. You can't free up without leaving gaps. Usually a pool refers to a block of contiguous memory with fixed sized slots, which are doubly linked to allow constant time add and delete. Here's one you can use as a guide. It's along the same lines as yours but includes basic iterators over allocated nodes, and uses templates to be type aware.
771,492
771,508
C++ Style Convention: Parameter Names within Class Declaration
I'm a fairly new C++ programmer and I would like to hear the arguments for and against naming parameters within the class declaration. Here's an example: Student.h #ifndef STUDENT_H_ #define STUDENT_H_ #include <string> using namespace std; class Student { private: string name; unsigned int age; float height, GPA; public: Student(string, unsigned int, float, float); void setAge(unsigned int); }; #endif /*STUDENT_H_*/ vs. #ifndef STUDENT_H_ #define STUDENT_H_ #include <string> class Student { private: string name; unsigned int age; float height, GPA; public: Student(string name, unsigned int age, float height, float GPA); void setAge(unsigned int age); }; #endif /*STUDENT_H_*/ Student.cpp #include "Student.h" Student::Student( string name, unsigned int age, float height, float GPA) : name(name), age(age), height(height), GPA(GPA) {} void Student::setAge(unsigned int age) { this -> age = age; } I cannot decide. On the one hand, I feel that it is redundant to name the variables in both the declaration (.h) and the definition (.cpp). Especially since you have to worry about updating the names in both places so that they match. On the other hand, without names, it can often be confusing to determine what variables the parameters correspond to just by looking at the declaration. So, what are your thoughts?
It is much better to use the parameter names in the declaration, and use good parameter names. This way, they serve as function documentation. Otherwise, you will have to write additional comments in your header, and it is always better to use good parameter/variable names than to use comments. Exception: when a function must have a certain signature for external reasons, but the parameters are not actually used. In this case, you should not name them in the implementation either.
771,867
772,005
How to make a cross-platform c++ inline assembly language?
I hacked a following code: unsigned long long get_cc_time () volatile { uint64 ret; __asm__ __volatile__("rdtsc" : "=A" (ret) : :); return ret; } It works on g++ but not on Visual Studio. How can I port it ? What are the right macros to detect VS / g++ ?
#if defined(_MSC_VER) // visual c #elif defined(__GCCE__) // gcce #else // unknown #endif My inline assembler skills are rusty, but it works like: __asm { // some assembler code } But to just use rdtsc you can just use intrinsics: unsigned __int64 counter; counter = __rdtsc(); http://msdn.microsoft.com/en-us/library/twchhe95.aspx
771,868
771,888
Problem compiling Platform SDK program
I'm trying to compile the example from here; http://msdn.microsoft.com/en-us/library/ms682619(VS.85).aspx I've installed the Platform SDK, but I'm getting these errors; Error 1 error LNK2019: unresolved external symbol _GetDeviceDriverBaseNameW@12 referenced in function _main DriverChecker.obj DriverChecker Error 2 error LNK2019: unresolved external symbol _EnumDeviceDrivers@12 referenced in function _main DriverChecker.obj DriverChecker Error 3 fatal error LNK1120: 2 unresolved externals C:\Files\Projects\VS2008\DriverChecker\Debug\DriverChecker.exe DriverChecker Anyone any idea how to get this compiling correctly?
You just need to add psapi.lib as an additional library in your linker options. Edit properties for your project, navigate to Linker->Input, and type "psapi.lib" where it says Additional Dependencies.
771,944
771,955
How to measure user time used by process on windows?
On linux we can use "time" command. Or from C++: #include <sys/time.h> #include <sys/resource.h> int getrusage(int who, struct rusage *usage); How to do a closest thing to that on windows ?
GetProcessTimes This gives lpUserTime [out] : A pointer to a FILETIME structure that receives the amount of time that the process has executed in user mode. The time that each of the threads of the process has executed in user mode is determined, and then all of those times are summed together to obtain this value.
772,089
1,083,465
One executable that starts as a GUI application or console application based on command line in Visual Studio 2005
I have a Qt application in Visual Studio 2005 which is linked using \subsystem:windows such that when I run the compiled executable it does not create a command line terminal, as well. I would like to create a command-line mode: when I start it with the --nogui command line argument, then the GUI is not presented, but a simple command-line program is run. Since the linking uses /subsystem:windows, the command line mode doesn't show any of the std::cout outputs unless I link my executable with \subsystem:console. Is there a way to set the compilation/linking such that the same executable can either present the GUI windows or behave as a console application based on command-line parameters? PS. I use Qt 4.2.0 and Visual Studio 2005 and the project is in C++.
I think the preferred technique for the situation here is the ".com" and ".exe" method. In Windows from the command line, if you run a program and don't specify an extension, the order of precedence in locating the executable will .com preferred over a .exe file. Then you can use tricks to have that ".com" be a proxy for the stdin/stdout/stderr and launch the same-named .exe file. This give the behavior of allowing the program to preform in a command-line mode when called form a console (potentially only when certain command-line arguments are detected) while still being able to launch as a GUI application free of a console. There are various articles describing this, like "How to make an application as both GUI and Console application?" (see references in link below). I hosted a project called dualsubsystem on google code that updates an old codeguru solution of this technique and provides the source code and working example binaries. I hope that is helpful!
772,146
772,224
c++ delete object referenced by two pointers
I am just curious if there is an elegant way to solve following problem in c++: I have a simulator app which contains several components connected by channels. The channels may be either network channels (two instances of the app are needed) or dummy local channel. There are two interfaces: IChannelIn and IChannelOut and two corresponding variables: IChannelIn* in; IChannelOut* out; The DummyChannel is both IChannelIn and IChannelOut. It just copies input to output. There is also TCPChannelIn: public IChannelIn and separate TCPChannelOut: public IChannelOut. Now, according to user's choice , I either create one DummyChannel DummyChannel* d = new DummyChannel; in = d; out = d; or two separate objects: in = new TCPChannelIn; out = new TcpChannelOut The question is: what should the destructor do? ~App::App() { delete in; delete out; } ends in an error because delete in; deleted also the dummy channel d so that delete out deletes already deleted thing. Is there an elegant way out of this?
How does your class know that this is a freestore pointer? E.g. what speaks against the following code? DummyChannel d; in = &d; out = &d; This is an entirely sensible piece of code but your destructor will crash when trying to delete either of the pointers. Long story short: reclaiming resources is the job of whoever has allocated the resources in the first place. If your class gets passed a pointer, the class cannot know and does not care about deallocation. This is strictly the responsability of the caller. Elegant ways to solve this dilemma without making the client to a lot of work are smart pointers, as mentioned before.
772,192
3,670,232
tr1::hash for boost::thread::id?
I started to use the unordered_set class from the tr1 namespace to speed-up access against the plain (tree-based) STL map. However, I wanted to store references to threads ID in boost (boost::thread::id), and realized that the API of those identifiers is so opaque that you cannot clearly obtain a hash of it. Surprisingly, boost implements parts of the tr1 (including hash and unordered_set), but it does not define a hash class that is able to hash a thread ID. Looking at the documentation of boost::thread::id I found that thread IDs can be output to a stream, so my solution for doing hashing was kind of: struct boost_thread_id_hash { size_t operator()(boost::thread::id const& id) const { std::stringstream ostr; ostr << id; std::tr1::hash<std::string> h; return h(ostr.str()); } }; That is, serialize it, apply the hash to the resulting string. However, this seems to be less efficient than actually using the STL map<boost::thread::id>. So, my questions: Do you find a better way of doing this? Is it a clear inconsistency in both boost and tr1 not to force the existence of a hash<boost::thread::id> class? Thanks.
The overhead of stringifying thread::id (only to compute the string hash afterward) is, as you almost said yourself, astronomical compared to any performance benefits a tr1::unordered_map might confer vis-a-vis std::map. So the short answer would be: stick with std::map< thread::id, ... > If you absolutely must use unordered containers, try to usenative_handle_type instead of thread::id if possible, i.e. prefer tr1::unordered_map< thread::native_handle_type, ... >, invoking thread::native_handle() instead of thread::get_id() when inserting and finding. DO NOT attempt anything like the following: struct boost_thread_id_hash { // one and only member of boost::thread::id is boost::thread::id::thread_data // of type boost::detail::thread_data_ptr; // boost::thread::id::operator==(const id&) compares boost::thread::id::thread_data's size_t operator()(boost::thread::id const& id) const { const boost::detail::thread_data_ptr* pptdp = \ reinterpret_cast< boost::detail::thread_data_ptr* >(&id); return h(pptdp->get()); } }; It could work, but is extremely brittle and an almost guaranteed timebomb. It assumes intimate knowledge of the inner workings of the thread::id implementation. It will get you cursed at by other developers. Don't do it if maintainability is of any concern! Even patching boost/thread/detail/thread.hpp to add size_t hash_value(const id& tid) as a friend of thread::id is "better". :)
772,655
772,697
Counting instances of individual derived classes
I'd like to be able to count instances of classes that belong in the same class hierarchy. For example, let's say I have this: class A; class B: public A; class C: public B; and then I have this code A* tempA = new A; B* tempB = new B; C* tempC = new C; C* tempC2 = new C; printf(tempA->GetInstancesCount()); printf(tempB->GetInstancesCount()); printf(tempC->GetInstancesCount()); the result of that should print 1 1 2 The counting, ideally, should be done internally. Each class, and not some kind of manager, should know how many instances it has. Any ideas? Thanks!
There is a problem with proposed solutions: when you create B you A constructor will be called automatically and thus increment count of A. class A { public: A(bool doCount = true) { if (doCount) ++instanceCount_; } static std::size_t GetInstanceCount() { return instanceCount_; } virtual ~A(){} private: static std::size_t instanceCount_; }; class B: public A { public: B(bool doCount = true):A(false) { if (doCount) ++instanceCount_; } static std::size_t GetInstanceCount() { return instanceCount_; } private: static std::size_t instanceCount_; }; std::size_t A::instanceCount_ = 0; std::size_t B::instanceCount_ = 0;
772,709
772,719
What's the proper "C++ way" to do global variables?
I have a main application class, which contains a logger, plus some general app configurations, etc. Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor. I have seen some variants, like declaring the main class extern everywhere, but that doesn't feel very object oriented. What is the "standard" C++ way to make elements in the main class accessible to all (or most) other classes?
Use the singleton design pattern. Basically you return a static instance of an object and use that for all of your work. Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it Warning: The singleton pattern involves promoting global state. Global state is bad for many reasons. For example: unit testing.
773,414
773,424
Structure to hold value by ranged key
I need a structure to hold a value based on a key that has a range. My implementation is C++, so any STL or Boost would be excellent. I have as range-key, which are doubles, and value [0,2) -> value1 [2,5) -> value2 [5,10) -> value3 etc Such that a search of 1.23 should return value1, and so on. Right now I am using a vector containing all three parts, key1/key2/value, with custom searching, but it feels like there should be a cleaner structure. Edit: Thanks all. Given the ranges in this case are supposed to be contiguous and non-overlapping, the use of upper_bound will work just fine. Thanks for the class Range solutions as well, they are filed away for future reference.
If your ranges are contiguous and non-overlapping, you should use std::map and the upper_bound member function. Or, you could use a sorted vector with the upper_bound algorithm. Either way, you only need to record the lowest value of the range, with the upper part of the range being defined by the next higher value. Edit: I phrased that confusingly, so I decided to provide an example. In coding the example, I realized you need upper_bound instead of lower_bound. I always get those two confused. typedef std::map<double, double> MyMap; MyMap lookup; lookup.insert(std::make_pair(0.0, dummy_value)); lookup.insert(std::make_pair(2.0, value1)); lookup.insert(std::make_pair(5.0, value2)); lookup.insert(std::make_pair(10.0, value3)); MyMap::iterator p = lookup.upper_bound(1.23); if (p == lookup.begin() || p == lookup.end()) ...; // out of bounds assert(p->second == value1);
773,486
773,550
C hard coding an array of typedef struct
This is such a dumb question it's frustrating even asking it. Please, bear with me, I'm feeling particularly dumb over this one today.... I've got a library with a certain typedef struct. basically: typedef struct {int x; int y;} coords; What I really wanted to do was declare in my header a variable array of this: coords MyCoords[]; (I recently switched it to just coords *MyCoords; and then ran a MyCoords = new coords[4];) and then in my init I wanted to hardcode some values in it. MyCoords[] = {{0, 0}, {2, 2} etc. I must just be brainfarting today because it's not letting me do any manner of simply putting in even something simple like MyCoords[0] = {0, 0} sorry about some of the syntax above. Thanks for any help. I don't even care about hard-coding all the values at once. I'm now fine with just geting MyCoords[0] = {0, 0} working. I could do MyCoords[0].x = 0; MyCoords[0].y = 0 but then I'd never figure out what I'm doing wrong. Thanks a lot anyone..
Well, what you created is not a variable array. It's an array whose size is not known. That array has an incomplete type, and can thus not be defined in C++. What you can do is to make it just a declaration by putting extern before it. extern coords MyCoords[]; Then, in the .cpp file that initializes it, you can then create (define) that array - beware you should do it at namespace scope, outside any function, of course: coords MyCoords[] = {{1, 2}, {3, 4}, ... }; If what you want is an array whose size is not known at compile time yet, but rather at runtime, you should use a std::vector: std::vector< coords > MyCoords; Then later if you fill it, do MyCoords.push_back( coords(1, 2) ); MyCoords.push_back( coords(3, 4) ); .... Or create a local array and then initialize the vector using a copy of the elements of that array: coords c[] = ....; MyCoords.insert(MyCoords.end(), c, c + sizeof c / sizeof *c); Well, in C, it is slightly different than in C++. You can define an array whose dimension isn't known. What happens is that it's taken to be a "tentative" definition. If at the end of the file (more precisely, of its translation unit, which is that file, and all the files it includes - meaning everything the compiler translates together) there is not a subsequent definition of it that includes the size, then the size is taken to be 1. However, in C++ there are no tentative definitions, and a definition that does not include the size and does not contain an initializer that can tell the size is an invalid C++ program. For the reason why your code goes grazy, you are doing MyCoords[0] = {0, 0} Which the compiler will read as: -> Set LHS to RHS -> -> LHS is a variable of type `coords`. Fine -> -> RHS is... hmm, `{0, 0}`. What the heck is it?? You see, the compiler has no clue what the right hand side is supposed to mean. C99, for that reason (1999 version of C) introduced so-called compound literals. It allows you to write MyCoords[0] = (coords){0, 0}; And it will actually do what you want it to do - creating a right hand side value of type coord and assigns it to the left hand side. But you should just, already from a compatibility reason (many C compilers are not reasonable C99 compliant - and neither C++ nor C89 supports compound literals), use one of the previous ways i showed you.
773,525
773,549
std::map iterator not iterating in MFC app
I have a std::map declared thusly in a legacy MFC application: typedef std::map<long, CNutrientInfo> NUTRIENT_INFO_MAP; typedef NUTRIENT_INFO_MAP::const_iterator NUTRIENT_INFO_ITER; typedef NUTRIENT_INFO_MAP::value_type NUTRIENT_INFO_PAIR; static NUTRIENT_INFO_MAP m_NutrientInfoMap; m_NutrientInfoMap is populated when the app loads by looping through a table and creating an instance of CNutrientInfo and then inserting it into the std:map like: m_NutrientMapInfo.insert(NUTRIENT_INFO_PAIR(nutrient.GetId(), nutrient)); The std::map now contains a list of the nutrients that have been defined by the database. At some point a user can add a new nutrient to this list and it checks to see if what the user is adding already exists in the list. It does that check like: NUTRIENT_INFO_ITER iter = m_NutrientInfoMap.begin(); while (iter != m_NutrientInfoMap.end()) { m = (*iter).second; if (_stricmp(m.GetFullName().c_str(), name.c_str()) == 0) { return m; } iter++; } Or at least it's supposed to. When the function actually gets called it never advances past the initial line of the while loop. Placing a breakpoint there simply shows that the line in question is called over and over and never advances beyond it, which hangs the app. If you step into the actual comparison it compares correctly and then returns to the while loop line. Stepping in again to advance into the body of the loop simply returns to the while loop line. This same logic is used elsewhere in the app with no trouble so I'm stumped as to what's going on in this case. I've re-written the logic above using a for-loop and it works just fine, so it's not like I can't work around it, but C++ isn't my strongest language and as this is a legacy app that I'm trying to help support, I'd really like to learn and understand WHY this is doing what's it's doing for future reference. Plus, since the logic works elsewhere and not here perhaps there's an underlying cause that is what actually needs to be addressed. Any suggestions or thoughts on this would be greatly appreciated. Thanks in advance.
Is your example actually pasted from the source? Maybe it looks more like: while (iter != m_NutrientInfoMap.end()); // <== note the semi-colon { m = (*iter).second; if (_stricmp(m.GetFullName().c_str(), name.c_str()) == 0) { return m; } iter++; }
773,599
773,604
Return class pointer from a function
I am not sure what is wrong with this (keep in mind I'm kinda sorta new to C++) I have this class: Foo { string name; public: SetName(string); } string Foo::SetName(string name) { this->name = name; return this->name; }; ////////////////////////////////////////////// //This is where I am trying to return a Foo pointer from this global function: Foo * ReturnFooPointer() { Foo foo; Foo * foo_ptr; foo_ptr = &foo; return foo_ptr; } At compile time, this compiles just fine. However at run time it throws a runtime exception(Some sort of access violation) What am I doing wrong?
You need to use the new keyword instead to create new Foo on the heap. The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory. Here is the correct code. Foo * ReturnFooPointer() { Foo * foo_ptr = new Foo(); return foo_ptr; } Remember later to delete the pointer you are returning. So later in code: Foo *pFoo = ReturnFooPointer(); //Use pFoo //... delete pFoo;
773,667
871,802
element-wise operations with boost c++ ublas matrix and vector types
i'd like to perform element-wise functions on boost matrix and vector types, e.g. take the logarithm of each element, exponentiate each element, apply special functions, such as gamma and digamma, etc. (similar to matlab's treatment of these functions applied to matrices and vectors.) i suppose writing a helper function that brute-forced this for each desired function would suffice, but this seems wasteful. likewise, the boost wiki offers some code to vectorize standard functions, but this seems quite complex. valarray has been suggested, but i'd like to avoid converting between data types, as i need the ublas data types for other operations (matrix products, sparse matrices, etc.) any help is greatly appreciated.
WARNING The following answer is incorrect. See Edit at the bottom. I've left the original answer as is to give context and credit to those who pointed out the error. I'm not particularly familiar with the boost libraries, so there may be a more standard way to do this, but I think you can do what you want with iterators and the STL transform function template. The introduction to the uBLAS library documentation says its classes are designed to be compatible with the same iterator behavior that is used in the STL. The boost matrix and vector templates all have iterators which can be used to access the individual elements. The vector has begin() and end(), and the matrix has begin1(), end1(), begin2(), and end2(). The 1 varieties are column-wise iterators and the 2 varieties are row-wise iterators. See the boost documentation on VectorExpression and MatrixExpression for a little more info. Using the STL transform algorithm, you can apply a function to each element of an iterable sequence and assign the result to a different iterable sequence of the same length, or the same sequence. So to use this on a boost uBLAS vector you could do this: using namespace boost::numeric::ublas; // Create a 30 element vector of doubles vector<double> vec(30); // Assign 8.0 to each element. std::fill(vec.begin(), vec.end(), 8.0); // Perform the "Gamma" function on each element and assign the result back // to the original element in the vector. std::transform(vec.begin(), vec.end(), vec.begin(), boost::math::tgamma); For a matrix it would be basically the same thing, you would use either the 1 or 2 family of iterators. Which one you choose to use depends on whether the memory layout of your matrix is row major or column major. A cursory scan of the uBLAS documentation leads me to believe that it could be either one, so you will need to examine the code and determine which one is being used so you choose the most efficient iteration order. matrix<double> mat(30, 30); . . . std::transform(mat.begin1(), mat.end1(), mat.begin1(), boost::math::tgamma); The function you pass as the last argument can be a function taking a single double argument and returning a double value. It can also be a functor. This is not exactly the same as the vectorization example you cited, but it seems like it should be pretty close to what you want. EDIT Looks like I should have tested my recommendation before making it. As has been pointed out by others, the '1' and '2' iterators only iterate along a single row / column of the matrix. The overview documentation in Boost is seriously misleading on this. It claims that begin1() "Returns a iterator1 pointing to the beginning of the matrix" and that end1() "Returns a iterator1 pointing to the end of the matrix". Would it have killed them to say "a column of the matrix" instead of "matrix"? I assumed that an iterator1 was a column-wise iterator that would iterate over the whole matrix. For the correct way to do this, see Lantern Rouge's answer.
773,935
774,010
Handle Tab key in GLUT
I use OpenGL+GLUT for simple application, but I can't handle a "Tab" key press. Does anybody knows how to handle pressing of Tab key ? thanx P.S.:Mac OS 10.5.6, GCC 4.0 Solution void processNormalKeys(unsigned char key, int x, int y){ if ((int)key == 9) { //tab pressed .... } .... } .... int main(int argc, char ** argv) { .... glutKeyboardFunc(processNormalKeys); .... }
I believe hitting tab triggers the normal keyboard callback with a key value of 9 (ASCII for tab).
774,047
774,256
How can I change Windows shell (cmd.exe) environment variables from C++?
I would like to write a program that sets an environment variable in an instance of the shell (cmd.exe) it was called from. The idea is that I could store some state in this variable and then use it again on a subsequent call. I know there are commands like SetEnvironmentVariable, but my understanding is that those only change the variable for the current process and won't modify the calling shell's variables. Specifically what I would like to be able to do is create a command that can bounce between two directories. Pushd/Popd can go to a directory and back, but don't have a way of returning a 2nd time to the originally pushed directory.
A common techniques is the write an env file, that is then "call"ed from the script. del env.var foo.exe ## writes to env.var call env.var
774,233
774,320
MS Extensions To STL
If this is a "Google Is Your Friend" question, I apologize in advance. I've searched but perhaps I've been using the wrong terms for searching. Can anyone point me to any sort of introductory document on the STL extensions which MS provided with Visual Studio 2003? I believe the libraries were licensed from Dinkumware and I've seen their docs but they're not helping with this issue. I'm trying to insure that we've not made some dumb and obvious mistake with our use of these extension containers. I've not worked on this issue myself--I'm helping another developer--but I believe the issue is something to do with the algorithm to create buckets getting into some sort of infinite loop within the hash_set container. As I say I just want to make sure we've eliminated obvious and dumb mistakes.
One thing Microsoft has done starting with VS 2003 it to put non-standard C++ extensions in the stdext namespace: http://msdn.microsoft.com/en-us/library/ek139e86(VS.71).aspx So doing a search on stdext (either on the headers or on MSDN) will help you. Note that while the above link talks only about <hash_set> and <hash_map> (even in the VS 2008 version of the page), the stdext namespace is used for other things such as the checked iterators and checked algorithms.
774,293
774,317
How to create an iterator over elements that match a derived type in C++?
I'd like an iterator in C++ that can only iterate over elements of a specific type. In the following example, I want to iterate only on elements that are SubType instances. vector<Type*> the_vector; the_vector.push_back(new Type(1)); the_vector.push_back(new SubType(2)); //SubType derives from Type the_vector.push_back(new Type(3)); the_vector.push_back(new SubType(4)); vector<Type*>::iterator the_iterator; //***This line needs to change*** the_iterator = the_vector.begin(); while( the_iterator != the_vector.end() ) { SubType* item = (SubType*)*the_iterator; //only SubType(2) and SubType(4) should be in this loop. ++the_iterator; } How would I create this iterator in C++?
You must use a dynamic cast. the_iterator = the_vector.begin(); while( the_iterator != the_vector.end() ) { SubType* item = dynamic_cast<SubType*>(*the_iterator); if( item != 0 ) ... //only SubType(2) and SubType(4) should be in this loop. ++the_iterator; }
774,464
774,484
Undefined reference? Is there something I'm not seeing? (c++, singleton class)
I can't seem to make this undefined reference go away. I have this code under the private section of Scene.h: static Scene * scene_; There is a #include "Scene.h" at the very first part of the header of Scene.cpp This is the only error I'm receiving at the moment, any ideas? I'll supply any other info you want.
When you declare a static member you must also define it in one compilation unit (and only one): // a.h class A { static int x; }; // a.cpp int A::x = 0; The declaration of the variable in the class will not reserve memory, just tell the compiler (from other compilation units) that there will be a variable accessible by that name defined somewhere.
774,474
774,530
How to hide MFC splash screen in auto start?
I have a MFC app without main window. When users start it, it displays the splash screen for 1~2 seconds, then splash screen fades out to system tray. Users start to access the menu by clicking the icon in the tray. The app can also auto start when users login to Windows (adding entry in Start Up folder). The same process described above repeats. I think the splash screen is kind of bothering during auto starts. I like to hide the splash screen when it auto starts, but keep splash screen shown if users manually run the app. I wonder what is the best way to do this? Thanks a lot!
A simple way would be to set a shortcut to the application in the Startup folder that specifies a parameter on the command line, e.g. if your application is called myapp.exe in the shortcut properties you could type <path to myapp>\myapp.exe -nosplash. Then modify your application code to check the command line parameters possibly with GetCommandLine to see if -nosplash had been passed and then not display the splash screen. Obviously, if the user had just launched it by doubling clicking the application itself, -nosplash would not be present and it would display the splash screen as normal.
774,717
774,755
C++ Object Graph to C#
Is there a tool that will take a series of C++ headers and generate a XSD and a class that will serialize the C++ to XML? Or really what we are looking for is the simplest way to migrate data from C++ to C#? We have a library in C++ that we would like to write a GUI for in C#. Using Managed wrapper classes it seems like we will have to make wrappers for each class. Automation is the goal.
This would be a good starting point for serializing the C++ stuff. http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/index.html
774,802
794,763
Is there a gcc 4.2 warning similar to Visual Studio's regarding possible loss of data?
Is there a flag for gcc such that conversions from a long to a short will generate a warning about a possible loss of data? I'm working on a C++ application that is compiled for both Visual Studio (2005) and GCC 4.2 (for Mac OS X). The warnings that Visual Studio prints out follow this pattern: : warning C4244: 'argument' : conversion from 'long' to 'short', possible loss of data I've tried -Wconversion, but that isn't quite what I'm looking for. The only thing I've been able to find so far is an experimental flag, -Wcoercion, which is associated with GCC 4.3 (which I'm not sure if we want to invest in quite yet). April 22, 2009 @ 11:00 EST Edit:To clarify, I want to see that warning. We have code where we want to know when a data loss would occur. If I have the code: unsigned long value1 = LONG_MAX; std::cout << "value1: " << value1 << std::endl; unsigned short value2 = value1; std::cout << "value2: " << value2 << std::endl; I get this expected result:   value1: 2147483647   value2: 65535 In our code, we have special asserts put in place that perform the coercion and warn us if the executed-code would result in a loss of data. We found the places in our large code base using Visual Studio's warnings. Is there any way we can generate these warnings in gcc 4.2?
This feature is not supported in GCC 4.2, but it has been added in GCC 4.3. Wiki page explaining it. Thanks to schnaader and Evan Teran for providing the links that led me there.
775,082
775,098
Best commercial C++ IDE?
I have tried C++ Builder 2009 and Visual Studio 2008. VCL seems much more friendlier than MFC. Are there alternates which are superior than these two? PS: Please do not suggest freebies or open source IDEs. I really am interested in commercial IDE's only.
I suppose mentioning VCL and MFC means you are referring to Windows IDEs only. With that said, I think VS2008 pretty much has the crown no contest. Its debugger is one of the best you can get and it's perfectly integrated into the IDE. Don't get me wrong, C++ builder is still a great piece of software, but I feel Borland's line of coding tools was in it's prime in the days before they sold it to Embarcadero. Visual Studio 2010 also looks pretty promising!
775,144
775,179
C++ Segregated Free Lists
I need to use segregated free lists for a homework assignment and I was wondering if the STL or some other library had these already written so I don't have to reinvent the wheel?
I don't think STL has anything, but it looks like the Boost library might have it, http://www.boost.org/doc/libs/1_38_0/libs/pool/doc/interfaces/simple_segregated_storage.html
775,217
775,227
What is a good way to load textures dynamically in OpenGL?
Currently I am loading an image in to memory on a 2nd thread, and then during the display loop (if there is a texture load required), load the texture. I discovered that I could not load the texture on the 2nd thread because OpenGL didn't like that; perhaps this is possible but I did something wrong - so please correct me if this is actually possible. On the other hand, if my failure was valid - how do I load a texture without disrupting the rendering loop? Currently the textures take around 1 second to load from memory, and although this isn't a major issue, it can be slightly irritating for the user.
You can load a texture from disk to memory on any thread you like, using any tool you wish for reading the files. However, when you bind it to OpenGL, it's going to need to be handled on the same thread as the rendering for that OpenGL context. That being said, this discussion suggests that using a PBO in a second thread is an option, and can speed up the process.
775,325
775,343
Function for manipulating container of Base/Derived objects
consider the following algorithm with arrays: class MyType; { // some stuff } class MySubType:MyType { // some stuff } void foo(MyType** arr, int len) { for (int i = 0;i<len;i++) // do something on arr[i]-> } void bar() { MySubType* arr[10]; // initialize all MySubType*'s in arr foo(&arr, 10); } Nothing too fancy here. My question is - how do I do this with templates? void foo(std::vector<MyType>& s) { std::vector<MyType>::iterator i; for (i = s.begin(); i != s.end(); i++) // do stuff on *i } so, in bar, I can't do this: void bar() { std::vector<MySubType> s; foo(s); // compiler error } error: invalid initialization of reference of type std::vector<MyType, std::allocator<MyType> >& from expression of type std::vector<MySubType, std::allocator<MySubType> > Is there some way to do something like this? Basically, if there's a way to do this: std::vector<MySubType> s; std::vector<MyType>& t = s; I'd be happy...
This might fix your problem template <typename T> void foo(std::vector<T>& s) { typename std::vector<T>::iterator i; for (i = s.begin(); i != s.end(); i++) // do stuff on *i }
775,349
787,671
Webcam driver settings?
I'm working on a C++ application that uses OpenCV/ffmpeg to capture video frames from my built-in webcam (Studio XPS 13). This application is really sensitive to those auto light adjustments that the webcam driver does.... is there any way I can change this behavior? Either via some webcam driver settings app, or in code (you may suggest a different library).
Well, I'm not sure what the most general way to do this is, but I know that the module for my webcam (ov511) has options to tweak all these settings... try running modinfo for the kernel module.
775,357
775,379
MPI Genetic Monte Carlo Algorithm Resources?
I have been working with some friends to convert a Matlab Genetic Algorithm to C++ and it works in a sequential order currently. Matlab is no longer a portion of our current code. We are looking to use it on a cluster, but have been a little dry on resources. We have a cluster available at the University and it is equipped with Rocks and OpenMPI, but I'm not really sure where to begin working with it. We currently have 2D and 3D Arrays setup with the data in them and when the system is doing crossover or exchanging between the models it just tries swapping parts of the 2D and 3D array. What are some good ways to separate these structures across multiple nodes?
If you're doing matrix computations, then whether there's even a good way to partition the calculations is highly dependent upon the calculation itself. I'd highly recommend the Golub and van Loan book, "Matrix Computations, 3rd Ed.". In it there is an entire chapter devoted to parallel computations (Ch. 6). OpenMPI is a fine middleware to use for this problem. Since you're doing this in C++, you might also take a look at zeromq. The two have different semantics, and one might favor your problem space or your skillset more than the other. Also, you should know that parallel matrix computations (typically signal processing, but there are lots of other applications) is a very, very active area of research.
775,367
775,371
Will this be out of scope and not function properly?
I'm declaring a struct inside my code and then trying to insert it into a data structure that I have written. However, I'm concerned that since I declare the struct inside the function, once the function ends, the data structure will be pointing to garbage. Can anyone help with this? Here's the code: void Class::function() { // do some stuff node newNode; newNode.memAddr = tempNode.memAddr+totalSize; newNode.size = tempNode.size-totalSize; lists[newNode.size>=512?64:(newNode.size>>3)].insert(&newNode); } Edit: I'm actually trying to re-write malloc, so calling malloc() or new will not work here. Is there some way that I could move this code into the insert method and then make it work in a way that it would not fall out of scope in insert?
It will be out of scope after function returns, yes. That is not valid. You want to allocate it on the heap. Edit: Unless you copy the memory you point to in insert, of course.
775,481
775,500
Keeping address in C++ hacking game code?
I have this code that edits addresses in a game to get unlimited ammo and what not, and I found out that the addresses are different for every computer, sometimes every time you restart the game, so how would I manage making this work still even though they change.
If you get the address you're looking for, and then search for that address in memory to find the address of the pointer to that data, and then search for that address in memory so you can find the address of the pointer to it, and so on, you may eventually find an address that does not change. Then, at runtime, you can use that as a starting point and dereference it to find the location you're looking for. Of course, that all depends on how the data is laid out internally. It can get very complicated.
775,700
779,424
Why aren't Shell_NotifyIcon balloon tips working?
According to everything I've seen, the following C++ program should be displaying a balloon tool tip from the tray icon when I left-click in the application window, yet it's not working. Can anyone tell me what I'm missing? This is on XP with version 6.0 of Shell32.dll (verified with DllGetVersion). Thanks! #include "stdafx.h" #include "shellapi.h" LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { MSG msg; WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszClassName = "sysTrayTest"; RegisterClass(&wc); HWND hWnd = CreateWindow("sysTrayTest", "", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 500, 500, NULL, NULL, hInstance, NULL); if (hWnd) { ShowWindow(hWnd, nCmdShow); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(NOTIFYICONDATA)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 1; Shell_NotifyIcon(NIM_DELETE, &nid); PostQuitMessage(0); } break; case WM_CREATE: { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(NOTIFYICONDATA)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 1; nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; nid.uCallbackMessage = WM_USER + 200; nid.hIcon = LoadIcon(NULL, IDI_INFORMATION); lstrcpy (nid.szTip, "Test Tip"); Shell_NotifyIcon(NIM_ADD, &nid); } break; case WM_LBUTTONDOWN: { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(NOTIFYICONDATA)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hWnd; nid.uID = 1; nid.uFlags = NIF_INFO; lstrcpy(nid.szInfo, "Test balloon tip"); lstrcpy(nid.szInfoTitle, "Test Title"); nid.dwInfoFlags = NIIF_INFO; nid.uTimeout = 15000; Shell_NotifyIcon(NIM_MODIFY, &nid); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
Bah, I figured it out. For some reason with the headers I have... sizeof(NOTIFYICONDATA) == 508 whereas... NOTIFYICONDATA_V3_SIZE == 504 NOTIFYICONDATA_V2_SIZE == 488 NOTIFYICONDATA_V1_SIZE == 88 If I specify either V2 or V3 instead of sizeof(NOTIFYICONDATA) the balloon tips show up just fine.
775,774
776,008
Conditionally disable warnings with qmake/gcc?
I am involved with a software project written in Qt and built with qmake and gcc on Linux. We have to link to a third-party library that is of fairly low quality and spews tons of warnings. I would like to use -W -Wall on our source code, but pass -w to the nasty third-party library to keep the console free of noise and clutter so we can focus on our code quality. In qmake, is there a way to conditionally add CFLAGS/CXXFLAGS to certain files and libraries?
Jonathan, I think the problem is where your source files are including header files from 3rd party libraries, and you want to switch off the warnings for the latter. Kevin, i think you can use pragmas to control warnings : gcc diagnostic pragmas You could add these before and after any #includes for 3rd party libs.
775,790
775,804
From Visual Studio C++ 6.0 to VS 2008?
I work in a company doing C++ development on VC6, and we're considering a move to VS 2008. What are the benefits of upgrading? What are the cons? Any guides/steps on migrating project files, or gotchas I should be aware of? Are people ok with moving to the different development interface?
For me, the biggest reason to upgrade to 2008 is the level of standards compliance in the C++ compiler. It is vastly improved from VC6 and is capable of using most libraries that you are familiar with or want to use. Including STL, BOOST and TR1. The downsides are the normal issues with upgrading. For example, improved standards compliance means that it may break some of your code which depended on non-standard behavior. No specific examples come to mind but I'm sure they're out there.
775,902
776,148
Zeroing out a struct in the constructor
A wide range of structures is used in Win32 programming. Many times only some of their fields are used and all the other fields are set to zero. For example: STARTUPINFO startupInfo; // has more than 10 member variables ZeroMemory( &startupInfo, sizeof( startupInfo ) ); //zero out startupInfo.cb = sizeof( startupInfo ); //setting size is required according to MSDN startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK; //Now call CreateProcess() passing the startupInfo into it I want to stop copy-pasting such code and instead use an abstraction that would care about zeroing and setting parameters. Let's presume I only need the struct initialized as in example, and no other tuning is ever needed. Is the following a good solution? What are possible problems? class CStartupInfo : public STARTUPINFO { public: CStartupInfo() { ZeroMemory( this, sizeof( STARTUPINFO ) ); cb = sizeof( STARTUPINFO ); dwFlags = STARTF_FORCEOFFFEEDBACK; } }; I'm in particular concerned about the ZeroMemory() call - looks like I fully control the code and the class has no vtable and calling ZeroMemory() this way is safe and there's no big difference between the two code snippets except that the latter provides an abstraction. Are there any caveats?
I think this is a fine way to make such structures more bulletproof. I'm not sure why others seem to not like the technique. I use it occasionally, but not as often as I otherwise might because it doesn't seem to be very well liked by coworkers for some reason. I don't see it used in published material very often - the only one I could find in a quick Google right now is an article by Paul DiLascia in MSJ August 1997 (http://www.microsoft.com/MSJ/0897/C0897.aspx): CRebarInfo and CRebarBandInfo are programmer-friendly C++ versions of the C structs REBARINFO and REBARBANDINFO, with constructors that initialize the objects to all zeroes before setting the cbSize member appropriately. I can't think of much in the way of drawbacks (except the lack of acceptance). If anyone else can point to something more concrete, I'd appreciate it.
776,004
776,086
Manipulating with pointers to derived class objects through pointers to base class objects
I have this code to represent bank: class Bank { friend class InvestmentMethod; std::vector<BaseBankAccount*> accounts; public: //... BaseBankAccount is an abstract class for all accounts in a bank: class BaseBankAccount { public: BaseBankAccount() {} virtual int getInterest() const = 0; virtual int getInvestedSum() const = 0; virtual void increaseDepositSum(int additionalSum) = 0; virtual void close(std::string& reason) = 0; virtual ~BaseBankAccount() {} }; The problem is, when I manipulate with pointers to derived class objects through pointers to base class objects, the set of methods I can call is restricted by BaseBankAccount public interface - no matter what type the REAL object is. For example, not every account has an option to increase sum invested already - so, I didn`t include this method in a base class: class BankAccount: public BaseBankAccount { protected: BaseDeposit* deposit; double sumInvested; public: BankAccount(int sum, int term, int inter): sumInvested(sum), depositTerm(term), interest(inter) {} int getInterest() const { return interest; } int getInvestedSum() const { return sumInvested; } void prolong(int increaseTerm) { depositTerm += increaseTerm; } void increaseInvestment(double addition) { sumInvested += addition; } virtual ~BankAccount() {} }; then, I want to call it: Bank bank1(...); bank1.accounts[i]->increaseInvestment(1000.0); So, what can I do to get access to the interface of derived class objects in this case? As far as I know, downcasting to concrete type each time I need to call specific functionality is not good.Create one more abstract class derived from this to expand the interface?Create parallel hierarchy for each specific type I need to implement (looks a bit heavy thing to do)?
A solution to accessing more derived class features from a base class is the visitor pattern. class BaseBankAccount { public: ... virtual void AcceptVisitor(IVisitor& v) = 0; }; class AccountTypeA : public BaseBankAccount { public: void TypeAFeature() {...} void AcceptVisitor(IVisitor& v) { v.VisitAccountTypeA(*this); } }; class AccountTypeB : public BaseBankAccount { public: void TypeBFeature() {...} void AcceptVisitor(IVisitor& v) { v.VisitAccountTypeB(*this); } }; class IVisitor { public: virtual void VisitAccountTypeA(AccountTypeA& account) = 0; virtual void VisitAccountTypeB(AccountTypeB& account) = 0; }; class ConcreteVisitor : public IVisitor{ public: void VisitAccountTypeA(AccountTypeA& account) { account.TypeAFeature(); //Can call TypeA features } void VisitAccountTypeB(AccountTypeB& account) { account.TypeBFeature(); //Can call TypeB Features } }; The interaction is not immediately obvious. You define a pure virtual method AcceptVisitor in your base class, which takes an Object of type IVisitor as a parameter. IVisitor has one Method per derived class in the hierarchy. Each derived class implements AcceptVisitor differently and calls the method corresponding to its concrete type (AccountTypeA & AccountTypeB), and passes a concrete reference to itself to the method. You implement the functionality that uses the more derived types of your hierachy in objects deriving from IVisitor. Wikipedia: Visitor Pattern
776,042
776,092
How to detect cycles when using shared_ptr
shared_ptr is a reference counting smart pointer in the Boost library. The problem with reference counting is that it cannot dispose of cycles. I am wondering how one would go about solving this in C++. Please no suggestions like: "don't make cycles", or "use weak_ptr". Edit I don't like suggestions that say to just use a weak_ptr because obviously if you know you will create a cycle, then you wouldn't have a problem. You also cannot know you will have a cycle at compile time if you generate shared_ptrs at runtime. So please, self delete answers that use weak_ptr in them because I specifically asked not to have those kind of answers...
I haven't found a much better method than drawing large UML graphs and looking out for cycles. To debug, I use an instance counter going to the registry, like this: template <DWORD id> class CDbgInstCount { public: #ifdef _DEBUG CDbgInstCount() { reghelper.Add(id, 1); } CDbgInstCount(CDbgInstCount const &) { reghelper.Add(id, 1); } ~CDbgInstCount() { reghelper.Add(id, -1); } #else #endif }; I just ned to add that to the classes in question, and have a look at the registry. (The ID, if given as e.g. 'XYZ!' will be converted to a string. Unfortunately, you can't specify a string constant as template parameter)
776,182
776,226
C++ : variable template parameters (for genetic algorithm)
I'm writing a parallel evolutionary algorithm library using C++, MPI and CUDA. I need to extract the raw data from my object oriented design and stick it into a flat array (or std::vector using stl-mpi) for it to be sent across to nodes or the cuda device. The complete design is quite complex with a lot of inheritance to keep the library flexible. But the classes of interest are: Genome class - contains vector of data. e.g. floats or bools. Population class - contains vector of Genome objects and is initailised with a genome object. First a genome object is created, then a reference to it is passed to population class constructor which creates its own vector of genomes based on passed one. (Hope that makes sense!) So I thought I would add another member vector, say rawData to the population class. But the type of rawData would need to depend on the type of data stored in the genomes (or the original genome object). Here lies the problem, as far as I am aware there is no way to dynamically set the type passed to template. my pseudo-code would be class genome { std::vector<bool> data; } template <class T> class population { std::vector<genome> population; std::vector<T> rawData; void PackDataIntoRawData(); }; then when i create the population (which is actually a member object of another class), I would call: genome myBitGenome(); population<type of myBitGenome.data> pop(myBitGenome); Is there anyway to do this, or can anyone suggest another way to implement this. Thanks in advance
As far as dynamic typing is concerned, boost::variant is a pretty powerful tool. But your problem seems to be fairly simple, so i'd recommend doing something like this : template<typename DataPiece> class Genome { typedef std::vector<DataPiece> Data; Data data; } template <class T_Genome> class Population { std::vector<T_Genome> population; typedef typename T_Genome::Data Data; Data rawData; void PackDataIntoRawData(); }; And then use it : typedef Genome<bool> MyGenome; MyGenome myBItGenome; Population<MyGenome> pop( myBitGenome );
776,303
776,320
In C++ how can I use a template function as the 3rd parameter in std::for_each?
I am trying to use std::for_each to output the contents of vectors, which may contain different types. So I wrote a generic output function like so: template<typename T> void output(const T& val) { cout << val << endl; } which I would like to use with: std::for_each(vec_out.begin(), vec_out.end(), output); but the compiler complains with "could not deduce template argument" in the for_each statement. Also complains with "A function template cannot be an argument to another function template". Is this not possible? I would have thought the compiler would know the type of vec_out (it's vector) and so should instantiate the function "output(const double& val)"? If this doesn't work how can I get similar STL functionality without writing manual loops? I am quite new to C++ and still learning the ropes :-)
Try: std::for_each(vec_out.begin(), vec_out.end(), output<T>); where vec_out is a container (vector) of type T. Note: The for_each algorithm expects an unary functor for its last argument. See the link for an example using functors.
776,304
1,133,119
TAB control background in ATL App, XP styles
I have an ATL application with a dialog containing a TAB control. The App uses a common controls manifest. Under XP with visual styles, the tab control background is a different color than the dialog and the controls (mostly checkboxes), so it looks quite ugly. Screenshot How can I fix that?
Here you could find answer to your question.
776,354
776,369
Test if a font is installed (Win32)
How can I test if a font is installed? Ultimately, I want to implement a HTML-like font selection, i.e. when specifying e.g. "Verdana,Arial", it should pick the first font that is installed. This Question provides an answer for .NET - it seems the recommended way is to create the font, and then cmpare the font face actually used. Is that the most efficient way?
You can use EnumFontFamiliesEx to enumerate the list of Fonts on the system, or if you pass a font name you can enumerate the fonts for that family.
776,510
776,890
Soundex Algorithm implementation using C++
Put simply a Soundex Algorithm changes a series of characters into a code. Characters that produce the same Soundex code are said to sound the same. The code is 4 characters wide The first character of the code is always the first character of the word Each character in the alphabet belongs in a particular group (at least in this example, and code thereafter this is the rule I'll be sticking with): b, p, v, f = 1 c, g, j, k, q, s, x, z = 2 d, t = 3 l = 4 m, n = 5 r = 6 Every other letter in the alphabet belongs to group 0. Other notable rules include: All letters that belong to group 0 are ignored UNLESS you have run out of letters in the provided word, in which case the rest of the code is filled with 0's. The same number cannot be used twice or more consecutively, thus the character is ignored. The only exception is the rule above with multiple 0's. For example, the word "Ray" will produce the following Soundex code: R000 (R is the first character of the provided word, a is apart of group 0 so it's ignored, y is apart of group 0 so it's ignored, there are no more characters so the 3 remaining characters in the code are 0). I've created a function that has passed to it 1) a 128 character array which is used in create the Soundex code and 2) an empty 5 character array which will be used to store the Soundex code at the completion of the function (and pass back by reference as most arrays do for use in my program). My problem is however, with the conversion process. The logic I've provided above isn't exactly working in my code. And I do not know why. // CREATE A SOUNDEX CODE // * Parameter list includes the string of characters that are to be converted to code and a variable to save the code respectively. void SoundsAlike(const char input[], char scode[]) { scode[0] = toupper(input[0]); // First character of the string is added to the code int matchCount = 1; int codeCount = 1; while((matchCount < strlen(input)) && (codeCount < 4)) { if(((input[matchCount] == 'b') || (input[matchCount] == 'p') || (input[matchCount] == 'v') || (input[matchCount] == 'f')) && (scode[codeCount-1] != 1)) { scode[codeCount] = 1; codeCount++; } else if(((input[matchCount] == 'c') || (input[matchCount] == 'g') || (input[matchCount] == 'j') || (input[matchCount] == 'k') || (input[matchCount] == 'q') || (input[matchCount] == 's') || (input[matchCount] == 'x') || (input[matchCount] == 'z')) && (scode[codeCount-1] != 2)) { scode[codeCount] = 2; codeCount++; } else if(((input[matchCount] == 'd') || (input[matchCount] == 't')) && (scode[codeCount-1] != 3)) { scode[codeCount] = 3; codeCount++; } else if((input[matchCount] == 'l') && (scode[codeCount-1] != 4)) { scode[codeCount] = 4; codeCount++; } else if(((input[matchCount] == 'm') || (input[matchCount] == 'n')) && (scode[codeCount-1] != 5)) { scode[codeCount] = 5; codeCount++; } else if((input[matchCount] == 'r') && (scode[codeCount-1] != 6)) { scode[codeCount] = 6; codeCount++; } matchCount++; } while(codeCount < 4) { scode[codeCount] = 0; codeCount++; } scode[4] = '\0'; cout << scode << endl; } I'm not sure if it's because of my overuse of strlen, but for some reason while the program is running within the first while loop none of the characters are actually converted to code (i.e. none of the if statements are actually run). So what am I doing wrong? Any help would be greatly appreciated.
Instead of scode[codeCount] = 1; you should write scode[codeCount] = '1'; as you are forming a char array, the former is actually the first ascii character while the latter is the character '1'.
776,624
776,677
What's faster, iterating an STL vector with vector::iterator or with at()?
In terms of performance, what would work faster? Is there a difference? Is it platform dependent? //1. Using vector<string>::iterator: vector<string> vs = GetVector(); for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it) { *it = "Am I faster?"; } //2. Using size_t index: for(size_t i = 0; i < vs.size(); ++i) { //One option: vs.at(i) = "Am I faster?"; //Another option: vs[i] = "Am I faster?"; }
Why not write a test and find out? Edit: My bad - I thought I was timing the optimised version but wasn't. On my machine, compiled with g++ -O2, the iterator version is slightly slower than the operator[] version, but probably not significantly so. #include <vector> #include <iostream> #include <ctime> using namespace std; int main() { const int BIG = 20000000; vector <int> v; for ( int i = 0; i < BIG; i++ ) { v.push_back( i ); } int now = time(0); cout << "start" << endl; int n = 0; for(vector<int>::iterator it = v.begin(); it != v.end(); ++it) { n += *it; } cout << time(0) - now << endl; now = time(0); for(size_t i = 0; i < v.size(); ++i) { n += v[i]; } cout << time(0) - now << endl; return n != 0; }
776,960
777,049
What's the best way to implement a operator overload?
Among all things I've learned in C++ (which isn't so much), operator overloading seems the most difficult. In general terms, when is it best to write an operator overload as a friend function? When do I have to explicilty use *this? Is always bad to use a temporary object?
Neil's answer is correct. In addition, this link provides a lot of good information about when, where, why, and how to use the various types of operator overloading in C++. In general, I'd try to stick with overloads that are intuitive -- use of the '+' operator should reflect something analogous to addition, etc. If you find yourself doing string comparisons with the '+' operator or something like that, you should probably be using standard functions instead.
776,976
777,052
Getting different instances to communicate
Suppose I have two instances of the same class. The class has a pointer to some data, and I want the instances to exchange the pointers as part of some private function's algorithm, but without compromising the data to everybody else by giving a direct access to it through a public function. My first idea was to add a static variable of type bool called exchange, and two methods: a private one: void requestExchange() and a public one: Data** respond(). requestExchange would set exchange to true, and will be immediately followed with respond() from the instance of choice, which will do the following: if(exchange==true){ exchange=false; return data; } else{return...?! This was when I realized that I have no way of simulating "NO OP" since data may in fact be NULL, so supposedly everything goes as a response. Any ideas as to what can be done? UPDATE: I thought a bit about it, and since the request-respond combo will only be called in the context where NULL as a result will be meaningful (exchange is most certainly true) I suppose I can simply return NULL and simulate a NO OP this way. To an outsider NULL as a result will be useless... But I'm still interested in suggestions. There must be a more well structured way of doing this.
Objects of the same class can access each others' private data directly. You often see this in copy constructors, for example.
777,261
777,359
Avoiding unused variables warnings when using assert() in a Release build
Sometimes a local variable is used for the sole purpose of checking it in an assert(), like so - int Result = Func(); assert( Result == 1 ); When compiling code in a Release build, assert()s are usually disabled, so this code may produce a warning about Result being set but never read. A possible workaround is - int Result = Func(); if ( Result == 1 ) { assert( 0 ); } But it requires too much typing, isn't easy on the eyes and causes the condition to be always checked (yes, the compiler may optimize the check away, but still). I'm looking for an alternative way to express this assert() in a way that wouldn't cause the warning, but still be simple to use and avoid changing the semantics of assert(). (disabling the warning using a #pragma in this region of code isn't an option, and lowering warning levels to make it go away isn't an option either...).
We use a macro to specifically indicate when something is unused: #define _unused(x) ((void)(x)) Then in your example, you'd have: int Result = Func(); assert( Result == 1 ); _unused( Result ); // make production build happy That way (a) the production build succeeds, and (b) it is obvious in the code that the variable is unused by design, not that it's just been forgotten about. This is especially helpful when parameters to a function are not used.
777,485
777,520
What is double(C++) in C#?
What is the double type(C++) in C#? double experience; At first,I thought its UInt32,but its not. How to declare it in C#?
This is a question that is dependent upon the particular C++ compiler implementation you are using. The double type can be either 4 or 8 bytes according to the C++ standard. Most compilers do use 8 bytes though. Here are the closest representations 4 bytes: float 8 bytes: double Reference: http://msdn.microsoft.com/en-us/library/cc953fe1.aspx
777,764
782,146
What modern C++ libraries should be in my toolbox?
I've been out of the C++ game for about 10 years and I want to get back in and start on a commercial app. What libraries are in use these days? User interface (e.g, wxWidgets, Qt) Database General purpose (e.g. Boost, Loki, STL) Threading Testing Network/sockets I looking to be cross-platform compatible (as much as possible out-of-the-box). What libraries to do you rely on? What features do they provide that make them "indispensable"? See my answer below for a summary.
Cross-platform libraries that are free for commercial (or non-commercial) applications Feel free to expand this list General Purpose Boost Loki MiLi POCO STL (of course) STXXL (STL re-implementation for extra large data sets) Qt ASL JUCE Audio FMOD Synthesis ToolKit Database SOCI OTL LMDB++ Design IoC Frameworks Hypodermic PocoCapsule Wallaroo Documents LibreOffice API PoDoFo Graphics Allegro OGRE SFML GUI FLTK GTK Qt Qwt wxWidgets VTK Hashing MurmurHash3 Imaging Boost.GIL CImg DevIL EasyBMP FreeImage ITK OpenCV Logging Boost.Log log4cxx Pantheios Mocking Google Mock Hippo Mocks Turtle (C++ mock object library for Boost) Multimedia openframework Cinder SDL Networking ACE Boost.Asio ICE Testing Boost.Test Google Test UnitTest++ doctest Threading Boost.Thread Version Control libgit2 Web Application Framework CppCMS Wt XML Libxml2 pugixml RapidXml TinyXML Xerces-C++ Links to additional lists of open source C++ libraries: http://en.cppreference.com/w/cpp/links/libs