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
224,204
224,215
Why use infinite loops?
Another poster asked about preferred syntax for infinite loops. A follow-up question: Why do you use infinite loops in your code? I typically see a construct like this: for (;;) { int scoped_variable = getSomeValue(); if (scoped_variable == some_value) { break; } } Which lets you get around not being able to see the value of scoped_variable in the for or while clause. What are some other uses for "infinite" loops?
A loop like: while (true) { // do something if (something else) break; // do more } lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while). If you've got a complex condition, you might also want to use this style to make the code clearer.
224,225
224,372
Create an Application without a Window
How would you program a C/C++ application that could run without opening a window or console?
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different. This causes the compiler to create an entry in the executable file format (PE format) that marks the executable as a windows executable. Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs. But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it. All you need to do, to achieve all this is, #include <Windows.h> int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int cmdShow) { /* do your stuff here. If you return from this function the program ends */ } The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.
224,234
224,259
Is there a way to check if an istream was opened in binary mode?
I'm using an istream which could be stringstream, ifstream or a user-defined stream type and I need to know if, in the case of an ifstream, it was not opened in binary mode (so I can throw an exception). I have tried the following method: if ((_is.flags() & ios::binary) == 0) throw exception(...) but no exception is ever thrown. The test fails in this case because _is.flags() returns 0x201 and ios::binary is 0x20. Is there a way to find out if a stream was opened in text mode?
flags() returns ios_base::fmtflags which is formatting flags, whereas binary is an ios_base::openmode flag. I'm not sure if there is a way to find these out once the stream is already open. I was thinking that maybe there was a virtual member of the streambuf class that could help, but there doesn't really seem to be.
224,397
224,420
Why do people use __ (double underscore) so much in C++
I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names. return __CYGWIN__; Just wondering: Is there a reason for this, or is it just some people's code styles? I would think that it makes it hard to read.
From Programming in C++, Rules and Recommendations : The use of two underscores (`__') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard. Underscores (`_') are often used in names of library functions (such as "_main" and "_exit"). In order to avoid collisions, do not begin an identifier with an underscore.
224,421
224,442
Constant value in conditional expression
In a coding style question about infinite loops, some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant. This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoiding #ifdef hell. For instance, you can have in your header: #ifdef CONFIG_FOO extern int foo_enabled; #else #define foo_enabled 0 #endif And the code can simply use a conditional and trust the compiler to elide the dead code when CONFIG_FOO isn't defined: if (foo_enabled) { ... } Instead of having to test for CONFIG_FOO every time foo_enabled is used: #ifdef CONFIG_FOO if (foo_enabled) { ... } #endif This design pattern is used all the time in the Linux kernel (for instance, include/linux/cpumask.h defines several macros to 1 or 0 when SMP is disabled and to a function call when SMP is enabled). What is the reason for that MSVC warning? Additionally, is there a better way to avoid #ifdef hell without having to disable that warning? Or is it an overly broad warning which should not be enabled in general?
A warning doesn't automatically mean that code is bad, just suspicious-looking. Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. That one that fires anytime you cast anything to a bool is usually the first to go.
224,500
224,521
How does "Edit and continue" work in Visual Studio?
I have always found this to be a very useful feature in Visual Studio. For those who don't know about it, it allows you to edit code while you are debugging a running process, re-compile the code while the binary is still running and continue using the application seamlessly with the new code, without the need to restart it. How is this feature implemented? If the code I am modifying is in a DLL loaded by the application, does the application simply unload the DLL and reload it again? This would seem to me like it would be prone to instability issues, so I assume it would be smarter than this. Any ideas?
My understanding is that when the app is compiled with support for Edit and Continue enabled, the compiler leaves extra room around the functions in the binary image to allow for adding additional code. Then the debugger can compile a new version of the function, replace the existing version (using the padding space as necessary), fix up the stack, set the instruction pointer, and keep going. That way you don't have to fix up any jump pointers, as long as you have enough padding. Note that Edit and Continue doesn't usually work on code in libs/dlls, only with the main executable code.
224,704
231,060
boost lambda or phoenix problem: using std::for_each to operate on each element of a container
I ran into a problem while cleaning up some old code. This is the function: uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output ) { output.resize(chunks.size()); for(chunk_vec_t::iterator it = chunks.begin(); it < chunks.end(); ++it) { uint32_t success = (*it)->get_connectivity_data(output[it-chunks.begin()]); } return TRUE; } What i am interested in doing is cleaning up the for loop to be a lambda expression but quickly got stuck on how exactly I would pass the correct argument to get_connectivity_data. get_connectivity_data takes a std::vector by reference and fills it with some data. output contains a std::vector for each "chunk". Basically my conclusion for this was that it was substantially easier, cleaner and shorter to leave my code as-is. EDIT: So the closest answer to my question as I envisioned it would look was this: std::for_each( chunks.begin(), chunks.end(), bind( &chunk_vec_t::value::type::get_connectivity_data, _1, output[ std::distance( _1, chunks.begn() ] ) ); Yet that code does not compile, I made some modifications to the code to get it to compile but I ran into 2 issues: _ 1 is a smart ptr, and std::distance did not work on it, I think i needed to use &chunks[0] as the start Since _ 1 is a smart pointer, I had to do: &chunk_vec_t::value_ type::ValueType::get_ connectivity_ data which caused a crash in the VC9 compiler... The answer regarding zip_ iterators looked good until i read more into it and discovered that for this particular use, the amount of extra code needed was substantial (binding this and that, etc). EDIT2: I found an acceptable solution that is both low on extraneous syntax and clear, which I've posted here and below. std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );
After a bit of work I came up with this solution: std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) ); It required that I change get_connectivity_data to return std::vector instead of taking one by reference, and it also required that I change the elements of chunks to be boost::shared_ptr instead of Loki::SmartPtr.
224,777
224,802
Thread local storage with __declspec(thread) fails in C++/CLI
I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration: __declspec(thread) int lastId = 0; However, at the first access of the variable, I get a NullReferenceException. To be more precise, the declaration is done within a ref class (a .NET class implemented in C++/CLI). I have already read something about __declspec(thread) does not work with delay loaded DLLs. Am I using delay loaded DLLs automatically if I use .NET?
It seems that __declspec(thread) isn't supported by CLR. Take in mind that .net threads aren't necesarily native threads, but can be also fibers, so standard API's for threads don't work on them. If you have a managed class, then you should use managed threading API's for thread local storage. There are a lot of articles regarding this difference. This is just to get you started. As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve performance. In case you are working with ASP.NET applications, you need to remember some things about TLS.
224,966
224,977
What is the difference between private and protected members of C++ classes?
What is the difference between private and protected members in C++ classes? I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected. What's the difference and which should I use?
Private members are only accessible within the class defining them. Protected members are accessible in the class that defines them and in classes that inherit from that class. Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes. Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.
225,283
225,763
Best XML serialization library for a MFC C++ app
I have an application, written in C++ using MFC and Stingray libraries. The application works with a wide variety of large data types, which are all currently serialized based on MFC Document/View serialize derived functionality. I have also added options for XML serialization based on the Stingray libraries, which implements DOM via the Microsoft XML SDK. While easy to implement the performance is terrible, to the extent that it is unusable on anything other than very small documents. What other XML serialization tools would you folks recommend for this scenario. I don't want DOM, as it seems to be a memory hog, and I'm already dealing with large in memory data. Ideally, i'd like a streaming parser that is fast, and easy to use with MFC. My current front runner is expat which is fast and simple, but would require a lot of class by class serialization code to be added. Any other efficient and easier to implement alternatives out there that people would recommend?
The Boost Serialization library supports XML. This library basically consists in: Start from the principles of MFC serialization and take all the good things it provides. Solve every single issue of MFC serialization! Among the improvements compared to MFC is support for XML. Note that you don't necessarily control the XML schema of this serialization. It uses its own schema.
225,362
225,435
Convert a number to a string with specified length in C++
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492'). In other words, I need to add correct amount of leading zeros to the number. int n = 999; string str = some_function(n,6); //str = '000999' Is there a function like this in C++?
or using the stringstreams: #include <sstream> #include <iomanip> std::stringstream ss; ss << std::setw(10) << std::setfill('0') << i; std::string s = ss.str(); I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.
225,480
225,658
Embed image in code, without using resource section or external images
I'm looking for a way to embed an image in a library (Windows-only). I don't want to go the 'traditional' way of putting it in the resources (because of special circumstances that make it not so convenient to mess around with the resource handle. Ideally, there would be something like xpm files: a 'text' representation of an image that is put in a c array and that some code converts into a bitmap in memory, which can then somehow be loaded into an HIMAGE or an HICON. The images I want to embed are 32-bit bitmaps (bmp). Any ideas? I'm using MFC so an MFC library would be fine, but of course I can use a library that doesn't use MFC too. Thanks.
Google for a bin2c utility (something like http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c). It takes a file's binary representation and spits out a C source file that includes an array of bytes initialized to that data. Just link the file in and you have your image sitting in a chunk of memory. Using this kind of tool is really common on embedded systems where such things as 'resources' and even files might not exist.
226,064
226,104
True color CImageList
How do I load a true color image into a CImageList? Right now I have mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255)); Where IDB_IMGLIST_BGTASK is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the resource to load from.
Needs 4 lines of code, but this works: CBitmap bm; bm.LoadBitmap(IDB_IMGLIST_BGTASK); mImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4); mImageList.Add(&bm, RGB(255,0,255));
226,144
226,251
Overload a C++ function according to the return value
We all know that you can overload a function according to the parameters: int mul(int i, int j) { return i*j; } std::string mul(char c, int n) { return std::string(n, c); } Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used: int n = mul(6, 3); // n = 18 std::string s = mul(6, 3); // s = "666" // Note that both invocations take the exact same parameters (same types) You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.
class mul { public: mul(int p1, int p2) { param1 = p1; param2 = p2; } operator int () { return param1 * param2; } operator std::string () { return std::string(param2, param1 + '0'); } private: int param1; int param2; }; Not that I would use that.
226,377
226,566
Operating System compile time
This is just a general question - I was sitting and waiting for a bit of software to compile (we use Incredibuild here but can still take 10/15 mins) and it got me wondering, does anyone know how long it took to compile Windows XP or Vista? I did some googling but didn't really find any useful information
OP is asking about Windows: "There are no other software projects like this," Lucovsky said, "but the one thing that's remained constant [over the years] is how long it takes to build [Windows]. No matter which generation of the product, it takes 12 hours to compile and link the system." Even with the increase in processing horsepower over the years, Windows has grown to match, and the development process has become far more sophisticated, so that Microsoft does more code analysis as part of the daily build. "The CPUs in the build lab are pegged constantly for 12 hours," he said. "We've adapted the process since Windows 2000. Now, we decompose the source [code] tree into independent source trees, and use a new build environment. It's a multi-machine environment that lets us turn the crank faster. But because of all the new code analysis, it still takes 12 hours." SOURCE Also see Mark Lucovsky classic presentation on developing Windows NT/2000. I don't work at Microsoft, so I don't know for sure...
226,402
226,733
Make Eclipse treat .h file as C++?
All of our C++ headers use a .h extension. Eclipse thinks these are C headers and flags them with lots of syntax errors on things like classes and namespaces. I've tried to change the file type association from: Preferences > C/C++ > File types but it's "locked". Interestingly, "*.h" is associated with both C and C++ headers, but it seems to be using C. How can I get Eclipse to treat .h files as C++?
Try creating a new project and specify your source area as the location. However, be sure you select C++ project (I usually use the makefile option). This is all you should have to do in order to make the parser recognize C++ syntax.
226,577
226,674
Strange program hang, what does this mean in debug?
Strange program hang, what does this mean in debug? After attaching windbg I found the following: (1714.258): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=015b5c74 ebx=178a13e0 ecx=dddddddd edx=009a8ca0 esi=09fbf698 edi=09fbf594 eip=005ae2f7 esp=09fbf4a4 ebp=09fbf594 iopl=0 nv up ei ng nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010286 TestApplication!std::_Container_base::_Orphan_all+0x57: 005ae2f7 c70100000000 mov dword ptr [ecx],0 ds:0023:dddddddd=???????? Call stack: TestApplication!std::_Container_base::_Orphan_all+0x57 TestApplication!std::vector >::operator=+0x37 TestApplication!boost::asio::detail::win_iocp_io_service::do_one+0x189 TestApplication!boost::asio::detail::win_iocp_io_service::run+0xa2 TestApplication!boost::asio::io_service::run+0x3a
The problem First chance exceptions means that the debugger is giving you, the person who is using the debugger, the first chance to debug the exception, before it throws it back at the program to handle the issue. In this case the exception is "Access violation". This means that your program is trying to read / write from an illegal memory location. Access violations are serious coz it could be corrupting some memory which is critical for your program and this would be the likely reason that your program hangs. From the faulting instruction it seems as if you are trying to get the contents of a 4 byte value from an illegal instruction. Debugging the Problem If this is your code then you can easily debug this issue by setting the debug symbol location to the output folder of your compiler (this would contain the relevant pdb files) When you get this exception get the call stack (one of the view windows would have it) This would show you the location in your code where the faulting stack has originated. Now open the file that contains this source and set a breakpoint there and the program would hit this point and stop inside the windebugger. Debug from this point and you would know exactly from which line of code this violation is thrown Tip : Boost comes with source so you can easily put a break point inside this code. Be sure to press F11 while debugging when you get to asio::detail::win_iocp_io_service::do_one.
226,939
274,246
Code Synthesis doesn't seem to generate a "valid" xml tree
I've been working with code synthesis xsd to generate an xml tree to ensure constinency of the xml output to the original xsd. After initial testing, everything looked ok but when I tried entering invalid values (correct type, but outside the defined range), the values were allowed. Although the xml is well formed and conforms to the types set in the xsd, it is not a valid xml wrt the schema. Has anybody else used this tool and/or come up across this problem?
The tool may not do the sort of checking you want when creating the document. If your document is small, you may just want to generate the XML,then re-parse it with XSD checking on and let that be your checking.
227,001
227,014
Best method to determine changed data in C++
I need to write a tool in C++ to determine the changed bits in a file compared against another file for replication. What would be the best method of accomplishing this? I don't have a specific OS or library in mind, I'm open to suggestions. My primary goal is reducing the amount of network traffic involved in replicating.
Look at rsync - it splits the file into blocks, calculates a checksum for each block, and transmits only the checksum to determine if there are any changesto the destination before transmitting the block data only if necessary.
227,762
12,829,806
Looking for 16-bit x86 compiler
I am working on an embedded systems project and have run into an issue of the compiler being programatically embedded in the Paradigm C++ IDE. I would like to be able to automate building. The processor is the AMD186ES. I am not working with the OS - just baremetal stuff. I need to generate real-mode 16-bit 8086 machine code from C++. My googling indicates that G++ can build such code. My questions are: Can g++ be configured to build this machine code? Are there other C++ compilers that can do it as well?
I am currently using gnu as (part of binutils and the assembler used for gcc) and I have successfully been assembling 16bit assembly code with the following: as <file> ld --oformat binary -Ttext 0x0 -e start <file> with my assembly files starting out with: .code16 .globl start .text start: since its plain binary omitting the lines, .globl start start: will simply yield an warning, even though flat binaries need no entry point. something I learned the hard way; -Ttext 0x0 is critical, otherwise the .text segment is pushed outside of 16bit addressing range (don't ask me why) I am personally still learning assembly, so this is just my way, not necessarily the best way. EDIT: If you are writing boot code, you should change -Ttext 0x0 to -Ttext 0x7c00 this will offset your memory addresses by 0x7c00 since boot code is usually loaded at 0x7c00 by the BIOS.
228,005
228,039
Alternative to itoa() for converting integer to string C++?
I was wondering if there was an alternative to itoa() for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use std::to_string: #include <string> std::string s = std::to_string(5); If you're working with prior to C++11, you could use C++ streams: #include <sstream> int i = 5; std::string s; std::stringstream out; out << i; s = out.str(); Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
228,036
228,065
C++ template instantiation of function template parameters
I have the following problem using template instantiation [*]. file foo.h class Foo { public: template <typename F> void func(F f) private: int member_; }; file foo.cc template <typename F> Foo::func(F f) { f(member_); } file caller.cc Foo::func(boost::bind(&Bar::bar_func, bar_instance, _1)); While this compiles fine, the linker complains about an undefined symbol: void Foo::func<boost::_bi::bind_t...> How can I instantiate the function Foo::func? Since it takes a function as argument, I am little bit confused. I tried to add an instantiation function in foo.cc, as I am used to with regular non-function types: instantiate() { template<> void Foo::func<boost::function<void(int)> >(boost::function<void(int)>); } Obviously, this does not work. I would appreciate if someone can point me in the right direction. Thanks! [*] Yes, I read the parashift FAQ lite.
The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. If you're using Visual C++, and any other compiler that can't do this, you may as well put the function definition in the header. Don't worry about duplicate definitions if the header is included by multiple .cc files. The compiler marks template-generated methods with a special attribute so the linker knows to throw away duplicates instead of complaining. This is one reason why C++ has the "one definition rule". Edit: The above comments apply in the general case where your template must be capable of linking given any type parameters. If you know a closed set of types that clients will use, you can ensure they are available by using explicit instantiation in the template's implementation file, which will cause the compiler to generate definitions for other files to link against. But in the general case where your template needs to work with types possibly only known to the client, then there is little point in separating the template into a header file and and implementation file; any client needs to include both parts anyway. If you want to isolate clients from complex dependencies, hide those dependencies behind non-templated functions and then call into them from the template code.
228,304
601,719
Is there any C++ lib to read thumbnails from thumb.db in Windows Folder?
I want to read all thumbnails from a folder with images in Windows XP. But if I read image file to get thumbnail, it seems a bit slow, so I wish I can first read the windows image thumbnail cache:thumb.db. Is there any lib in c++ or c to read thumbnails from thumb.db.
You might find this useful: ThumbsDBLib in C++ http://www.windameister.org/blog/index.php/thumbslib-in-cpp
228,404
228,546
Extending an existing class like a namespace (C++)?
I'm writing in second-person just because its easy, for you. You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code. So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option? So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..." Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching). If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it. If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation. For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
228,617
228,625
How do I clear the console in BOTH Windows and Linux using C++
I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).
Short answer: you can't. Longer answer: Use a curses library (ncurses on Unix, pdcurses on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that behave like console windows). Most difficult answer: Use #ifdef _WIN32 and stuff like that to make your code act differently on different operating systems.
228,620
228,722
Garbage Collection in C++ -- why?
I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right? My only experience with garbage collection was on a couple of cheap eighties home computers, where it meant that the system would freeze up for a few seconds every so often. I'm sure it has improved since then, but as you can guess, that didn't leave me with a high opinion of it. What advantages could garbage collection offer an experienced C++ developer?
I keep hearing people complaining that C++ doesn't have garbage collection. I am so sorry for them. Seriously. C++ has RAII, and I always complain to find no RAII (or a castrated RAII) in Garbage Collected languages. What advantages could garbage collection offer an experienced C++ developer? Another tool. Matt J wrote it quite right in his post (Garbage Collection in C++ -- why?): We don't need C++ features as most of them could be coded in C, and we don't need C features as most of them could coded in Assembly, etc.. C++ must evolve. As a developer: I don't care about GC. I tried both RAII and GC, and I find RAII vastly superior. As said by Greg Rogers in his post (Garbage Collection in C++ -- why?), memory leaks are not so terrible (at least in C++, where they are rare if C++ is really used) as to justify GC instead of RAII. GC has non deterministic deallocation/finalization and is just a way to write a code that just don't care with specific memory choices. This last sentence is important: It is important to write code that "juste don't care". In the same way in C++ RAII we don't care about ressource freeing because RAII do it for us, or for object initialization because constructor do it for us, it is sometimes important to just code without caring about who is owner of what memory, and what kind pointer (shared, weak, etc.) we need for this or this piece of code. There seems to be a need for GC in C++. (even if I personaly fail to see it) An example of good GC use in C++ Sometimes, in an app, you have "floating data". Imagine a tree-like structure of data, but no one is really "owner" of the data (and no one really cares about when exactly it will be destroyed). Multiple objects can use it, and then, discard it. You want it to be freed when no one is using it anymore. The C++ approach is using a smart pointer. The boost::shared_ptr comes to mind. So each piece of data is owned by its own shared pointer. Cool. The problem is that when each piece of data can refer to another piece of data. You cannot use shared pointers because they are using a reference counter, which won't support circular references (A points to B, and B points to A). So you must know think a lot about where to use weak pointers (boost::weak_ptr), and when to use shared pointers. With a GC, you just use the tree structured data. The downside being that you must not care when the "floating data" will really be destroyed. Only that it will be destroyed. Conclusion So in the end, if done properly, and compatible with the current idioms of C++, GC would be a Yet Another Good Tool for C++. C++ is a multiparadigm language: Adding a GC will perhaps make some C++ fanboys cry because of treason, but in the end, it could be a good idea, and I guess the C++ Standards Comitee won't let this kind of major feature break the language, so we can trust them to make the necessary work to enable a correct C++ GC that won't interfere with C++: As always in C++, if you don't need a feature, don't use it and it will cost you nothing.
228,675
228,733
How to select and highlight a window in another application?
I would like to send some keystrokes from a C++ program into another window. For that reason I would like to have the user select the target window similar to how it is done in the Spy++ utility that comes with Visual Studio (drag a crosshair cursor over target window and have target window highlighted by a frame). How is this dragging and selecting done in Windows? I am completely lost as to where I might start to look for a mechanism to implement this feature.
Here's how it's usually done: Capture the mouse using SetCapture. This will cause all mouse messages to be routed toward your app's window. Handle the WM_MOUSEMOVE message. In your handler code, grab the window underneath the mouse using WindowFromPoint. That will get you the HWND of the window the mouse is currently over. Now that you've got the window, you need a device context (HDC). You can get one using GetWindowDC for the specified window. Now you can draw into the DC using typical GDI functions. There are some things you have to look out for - cleanly erasing the selection rectangle and so forth, but that's one way to do it. You could also draw into a screen DC to do this, but in any case you'll need the window handle in order to get the window rect. If you Google around Spy++ source code you'll see a few examples of this technique.
228,881
228,899
How can I specify that library X must be linked statically?
I have a piece of software which is linked against several libraries. They all exists in a dynamic (.so) and a static (.a) version. By default, when using g++ it chooses the dynamic version of the libraries and that's fine with me. However, one of them absolutely needs to be linked statically. I thought about using -static but then it uses a static version for all of them, which is not what I want. How can I specify that library X must be linked statically, while the others continue to be linked against the shared version of the libs ?
g++ -o foo (foo-objects) -Wl,-Bstatic -lmustbestatic -Wl,-Bdynamic -lother-lib
228,908
228,914
Is list::size() really O(n)?
Recently, I noticed some people mentioning that std::list::size() has a linear complexity. According to some sources, this is in fact implementation dependent as the standard doesn't say what the complexity has to be. The comment in this blog entry says: Actually, it depends on which STL you are using. Microsoft Visual Studio V6 implements size() as {return (_Size); } whereas gcc (at least in versions 3.3.2 and 4.1.0) do it as { return std::distance(begin(), end()); } The first has constant speed, the second has o(N) speed So my guess is that for the VC++ crowd size() has constant complexity as Dinkumware probably won't have changed that fact since VC6. Am I right there? What does it look like currently in gcc? If it is really O(n), why did the developers choose to do so?
Pre-C++11 answer You are correct that the standard does not state what the complexity of list::size() must be - however, it does recommend that it "should have constant complexity" (Note A in Table 65). Here's an interesting article by Howard Hinnant that explains why some people think list::size() should have O(N) complexity (basically because they believe that O(1) list::size() makes list::splice() have O(N) complexity) and why an O(1) list::size() is be a good idea (in the author's opinion): http://howardhinnant.github.io/On_list_size.html I think the main points in the paper are: there are few situations where maintaining an internal count so list::size() can be O(1) causes the splice operation to become linear there are probably many more situations where someone might be unaware of the negative effects that might happen because they call an O(N) size() (such as his one example where list::size() is called while holding a lock). that instead of permitting size() be O(N), in the interest of 'least surprise', the standard should require any container that implements size() to implement it in an O(1) fashion. If a container cannot do this, it should not implement size() at all. In this case, the user of the container will be made aware that size() is unavailable, and if they still want or need to get the number of elements in the container they can still use container::distance( begin(), end()) to get that value - but they will be completely aware that it's an O(N) operation. I think I tend to agree with most of his reasoning. However, I do not like his proposed addition to the splice() overloads. Having to pass in an n that must be equal to distance( first, last) to get correct behavior seems like a recipe for hard to diagnose bugs. I'm not sure what should or could be done moving forward, as any change would have a significant impact on existing code. But as it stands, I think that existing code is already impacted - behavior might be rather significantly different from one implementation to another for something that should have been well-defined. Maybe onebyone's comment about having the size 'cached' and marked known/unknown might work well - you get amortized O(1) behavior - the only time you get O(N) behavior is when the list is modified by some splice() operations. The nice thing about this is that it can be done by implementors today without a change to the standard (unless I'm missing something). As far as I know, C++0x is not changing anything in this area.
229,069
229,121
Dead code detection in legacy C/C++ project
How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that?
You could use a code coverage analysis tool for this and look for unused spots in your code. A popular tool for the gcc toolchain is gcov, together with the graphical frontend lcov (http://ltp.sourceforge.net/coverage/lcov.php). If you use gcc, you can compile with gcov support, which is enabled by the '--coverage' flag. Next, run your application or run your test suite with this gcov enabled build. Basically gcc will emit some extra files during compilation and the application will also emit some coverage data while running. You have to collect all of these (.gcdo and .gcda files). I'm not going in full detail here, but you probably need to set two environment variables to collect the coverage data in a sane way: GCOV_PREFIX and GCOV_PREFIX_STRIP... After the run, you can put all the coverage data together and run it through the lcov toolsuite. Merging of all the coverage files from different test runs is also possible, albeit a bit involved. Anyhow, you end up with a nice set of webpages showing some coverage information, pointing out the pieces of code that have no coverage and hence, were not used. Off course, you need to double check if the portions of code are not used in any situation and a lot depends on how good your tests exercise the codebase. But at least, this will give an idea about possible dead-code candidates...
229,664
230,222
Native VC++ using external (not project) dll reference how to specify path to dll
I have a native VC++ project that uses a dll (which is not in a project). Now, I must to put the dll in one the "Search Path Used by Windows to Locate a DLL" link but I don't want the dll to sit in the exectuable or current or windows or system directory. So my only option according to that is adding the path to the %PATH% environment variable. Is there any other way? Is there an elegant way to do so (adding to PATH)? should I do this on installation? should I be concerned if i'm doing this?
Summing up all the techniques I have found: If you use a managed project as the startup project (which is actually my case) use Enviroment class string temp = "myFullDirectoryPathToDll"; string temp2 =Environment.GetEnvironmentVariable("PATH") + ";" + temp; Environment.SetEnvironmentVariable("PATH", temp2); this, and I think MSDN should have stressed that, changes the environment variable PATH only in this process. when debugging in VS the appPath doesn't 'work' use properties->debug->environment and merge environment variables link If you use a native: do explicit linking - seems like big work for something simple, maybe use appPath registery key on deployment link, nobody had a tested-and-proved answer
229,671
229,704
C for loop implemented differently than other languages?
I read the following in a review of Knuth's "The Art of Computer Programming": "The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop." (http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N) What is this guy talking about? How could you implement a for loop that wasn't just syntactic sugar for a while loop?
Consider this: for i:=0 to 100 do { ... } In this case, we could replace the final value, 100, by a function call: for i:=0 to final_value() do { ... } ... and the final_value-function would be called only once. In C, however: for (int i=0; i<final_value(); ++i) // ... ... the final_value-function would be called for each iteration through the loop, thus making it a good practice to be more verbose: int end = final_value(); for (int i=0; i<end; ++i) // ...
229,924
230,878
Difference between files written in binary and text mode
What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C. unsigned char buffer[256]; for (int i = 0; i < 256; i++) buffer[i]=i; int size = 1; int count = 256; Binary mode: FILE *fp_binary = fopen(filename, "wb"); fwrite(buffer, size, count, fp_binary); Versus text mode: FILE *fp_text = fopen(filename, "wt"); fwrite(buffer, size, count, fp_text);
I believe that most platforms will ignore the "t" option or the "text-mode" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: MSDN, you will see that specifying the "t" option will have the following effect: line feeds ('\n') will be translated to '\r\n" sequences on output carriage return/line feed sequences will be translated to line feeds on input. If the file is opened in append mode, the end of the file will be examined for a ctrl-z character (character 26) and that character removed, if possible. It will also interpret the presence of that character as being the end of file. This is an unfortunate holdover from the days of CPM (something about the sins of the parents being visited upon their children up to the 3rd or 4th generation). Contrary to previously stated opinion, the ctrl-z character will not be appended.
230,687
230,729
Counterpart of PHP's isset() in C/C++
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not. Can we build similar feature for C/C++ (some kind of symbol table lookup)?
I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe). You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously explicitly defined. There really is no such thing as an "unset" variable in C++. Even if you say "int var;" and do not initialize it, the variable has a value, usually garbage, but it's still "set" in the PHP sense. The closes I suppose would be the preprocessor's #ifdef and #ifndef which only checks to see if you've defined a variable using #define. But in my experience this is mostly used for omitting or adding code based on flags. For example: // code code code #ifdef DEBUG // debug only code that will not be included in final product. #endif // more code more code You can define DEBUG using #define to determine whether to include "DEBUG" code now. Perhaps telling a bit more about what you're trying to do with the C++ equivalent of isset will give you a better idea of how to go about doing it "The C++ Way".
230,715
231,117
Mixed Mode Library and CRT Dependencies - HELP
Alright, after doing a ton of research and trying almost every managed CPP Redist I can find as well as trying to copy my DLLs locally to the executing directory of the app I cannot figure out what dependencies i'm missing for this mixed mode library. Basically I have a large C# application and I'm trying to use a mixed mode library I made. On the development machine it works perfect (of course) but deployed when the library needs to be loaded for use it exceptions out because of missing CRT dependencies (I assume). I have used dependency walker to check all the DLLs referenced and ensured they exist on the deployment machine with no luck, I'm wondering if maybe it's some dependencies that need to be registered that I am missing, but i can't figure out what. I get the following exception when code tries to instantiate a class from the mixed mode library. Exception Detail: System.IO.FileLoadException: Could not load file or assembly 'USADSI.MAPI, Version=1.0.3174.25238, Culture=neutral, PublicKeyToken=null' or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1) I am compiling the library using VS2008 SP1 with /clr:oldSyntax specified. The intermediate manifest looks like this: <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level='asInvoker' uiAccess='false' /> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly> I can provide any more information as needed, unfortunately i'm not well versed in making mixed mode libraries so this has thrown me off. If anyone can offer any advice I would greatly appreciate it!
Did you deploy the CRT libraries on the target machine? Long shot: since you have a dependency on 32-bit code, you should set Target Platform in the Build property tab to x86. EDIT: trouble-shoot side-by-side resolving problems with the Sxstrace.exe utility, available on Vista.
230,790
230,806
Can initialization list in constructors be used in template classes?
I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class. For example, I have code like this: template <class T> class Stack { T* data; std::size_t count; std::size_t capacity; enum {INIT = 5}; public: Stack() { count = 0; capacity = INIT; data = new T [INIT]; } Can I replace the constructor with Stack(): count(0), capacity(INIT), data(new T [INIT])
Yes. Did the compiler tell you otherwise?
231,128
231,200
C++ Error Handling -- Good Sources of Example Code?
Just about every piece of example code everywhere omits error handling (because it "confuses the issue" that the example code is addressing). My programming knowledge comes primarily from books and web sites, and you seldom see any error handling in use at all there, let alone good stuff. Where are some places to see good examples of C++ error handling code? Specific books, specific open-source projects (preferably with the files and functions to look at), and specific web pages or sites will all be gratefully accepted.
Herb Sutter's and Andrei Alexandrescu's book C++ Coding Standards comes with a whole chapter on Error Handling and Exceptions including Assert liberally to document internal assumptions and invariants Establish a rational error handling policy, and follow it strictly Distinguish between errors and non-errors Design and write error-safe code Prefer to use exceptions to report errors Throw by value, catch by reference Report, handle, and translate errors appropriately Avoid exception specifications Every topic also includes an example and I found it to be a very valuable resource.
231,146
231,173
std::string erase last character fails?
I'm trying to change user input in wildcard form ("*word*") to a regular expression format. To that end, I'm using the code below to strip off the '*' at the beginning and end of the input so that I can add the regular expression characters on either end: string::iterator iter_begin = expressionBuilder.begin(); string::iterator iter_end = expressionBuilder.end(); iter_end--; if ((char)*iter_begin == '*' && (char)*iter_end == '*') { expressionBuilder.erase(iter_begin); expressionBuilder.erase(iter_end); expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b"; } However, the call to "expressionBuilder.erase(iter_end)" does not erase the trailing '*' from the input string so I wind up with an incorrect regular expression. What am I doing wrong here? "(char)*iter_end == '*'" must be true for the code inside the if statment to run (which it does), so why doesn't the same iterator work when passed to erase()?
Try erasing them in the opposite order: expressionBuilder.erase(iter_end); expressionBuilder.erase(iter_begin); After erasing the first *, iter_end refers to one character past the end of the string in your example. The STL documentation indicates that iterators are invalidated by erase(), so technically my example is wrong too but I believe it will work in practice.
231,198
231,319
Correct way to use custom functor with std::generate_n() algorithm?
The following code compiles correctly under VC++ 8 on XPSP3, but running it causes a runtime error. My header looks like: #include <stdexcept> #include <iterator> #include <list> template<typename T> class test_generator { public: typedef T result_type; //constructor test_generator() { std::generate_n( std::back_inserter( tests ), 100, rand ); value = tests.begin(); } result_type operator()( void ) { if( value == tests.end() ) { throw std::logic_error( "" ); } return *value++; } private: std::list<T> tests; typename std::list<T>::iterator value; }; My implementation looks like: #include <functional> #include <algorithm> #include <iostream> #include <deque> #include "test.h" int main() { test_generator<double> test; std::deque<double> tests; std::generate_n( std::back_inserter( tests ), 10, test ); return 0; } This compiles fine, it generates an exception (not the logic_error exception defined in the header). If I change the implementation to use a function instead of a functor, it works: int main() { std::deque<int> tests; std::generate_n( std::back_inserter( tests ), 10, rand ); return 0; } What's wrong with using a functor here?
The test_generator constructor initialises the value iterator to reference the first element in the tests list (which is a member of test_generator). When you call std::generate_n, a copy of the test is made (because the object is passed by value). In the copied object, the value iterator refers to the tests list in the original object, not the copy. Because of the iterator debugging checks performed in the Visual Studio STL implementation, this triggers an assertion, because an iterator obtained from one container should not be compared against an iterator from another container. To fix the problem, you could either implement a copy constructor for your test_generator class, or defer initialisation of value until the first time operator() is invoked.
231,220
231,244
Window Handle and window dimension
The MFC application that i created is dialog based. Just one dialog thats all. How do I get the window handle to this window, while the application is performing the InitDialog. I need to find out its dimension as well. GetForegroundWindow not necessarily gives you the handle to this window that is loading up
Check the m_hWnd member of your dialog object. GetClientRect() should work to give you the size of client (interior) of the dialog. GetWindowRect() will give you the total size including window borders, but the position will be off.
231,318
231,392
A Strategy against Policy and a Policy against Strategy
When I first discovered the Strategy pattern, I was amazed of the seemingly endless possibilities it offered to me and my programs. I could better encapsulate my models' behaviour and even exchange this behaviour on the fly. But the strategy could also be used to to provide traits and payload to the containing object - data that was declared in a superclass. Life was fine. class MyMonsterAI { float const see_radius_; virtual void attack () = 0; /* .. */ }; class ElveAI { ElveAI() : see_radius_(150.0f) {} /* ... */ }; class CycloneAI { CycloneAI() : see_radius_(50.0f) {} /* ... */ }; class Monster { MyMonsterAI* ai_; }; And along came the Policy pattern and it would allow me even greater flexibility in supplying parameters to a containing class - whole classes, outfitted however I liked, albeit dynamically exchanging the behaviour... that was not too easy (unless part of the policy was to have a strategy!). class MyMonsterTrait { typedef typename ElveAI AI; }; template< class MonsterTrait > class Monster : public MonsterTrait::AI { void idle (void) { attack(); } }; Both patterns seem to be very powerful to me and I like to use both, in different circumstances. But I'm not sure if there are particular/typical/more-practical applications for either at some situations. I am wondering: where do you use strategies and where policies? Where are either better suited?
Policies are largely set at compile time, while strategies are set at runtime. Further, policies are generally a C++ concept, and apply only to a minority of other languages(for example D), while strategy pattern is available to many (most?) object oriented languages, and languages that treat functions as first class citizens like python. That being said: A policy, being determined at compile time, is generally only useful for special situations where you want different application logic on a per-binary basis. For instance you might develop software that is slightly customized for each customer, whether via a web interface, or by hand, this would be a policy-based pattern. A strategy is determined at runtime, and in fact can be changed on the fly. For instance you might have software which implements a different user interface and logic for the salesforce than for the support group, but they all have to deal with the same customer and licensing info so rather than having two separately maintained apps you simply have one app whose interface changes as needed. -Adam
231,381
231,398
Is this prime generator inefficient C++?
Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower? I am trying to submit this to SPOJ and it tells me that my time limit exceeded... #include <iostream> #include <sstream> using namespace std; int main() { int testCases, first, second, counter = 0; bool isPrime = true; stringstream out; cin >> testCases; for (int i = 0; i < testCases; i++) { // get the next two numbers cin >> first >> second; if (first%2 == 0) first++; // find the prime numbers between the two given numbers for (int j = first; j <= second; j+=2) { // go through and check if j is prime for (int k = 2; k < j; k++) { if (j%k == 0) { isPrime = false; break; } } if (isPrime) { out << j << "\n"; } isPrime = true; } out << "\n"; } cout << out.str(); return 0; } EDIT: The program is supposed to generate prime numbers between the numbers specified in the input. (See here for more details: Prime Generator Problem ) -Tomek
This is one step (skipping even numbers) above the naive algorithm. I would suggest the Sieve Of Eratosthenes as a more efficient algorithm. From the above link: The complexity of the algorithm is O((nlogn)(loglogn)) with a memory requirement of O(n). The segmented version of the sieve of Eratosthenes, with basic optimizations such as wheel factorization, uses O(n) operations and O(n1 / 2loglogn / logn) bits of memory. The algorithm you give is somewhere near O(n^2). The speedup you get by skipping evens isn't that great because you would find an even number not to be prime on the first test. The sieve has a much greater memory requirement, but the runtime complexity is far superior for large N.
231,491
231,495
how-to initialize 'const std::vector<T>' like a c array
Is there an elegant way to create and initialize a const std::vector<const T> like const T a[] = { ... } to a fixed (and small) number of values? I need to call a function frequently which expects a vector<T>, but these values will never change in my case. In principle I thought of something like namespace { const std::vector<const T> v(??); } since v won't be used outside of this compilation unit.
For C++11: vector<int> luggage_combo = { 1, 2, 3, 4, 5 }; Original answer: You would either have to wait for C++0x or use something like Boost.Assign to do that. e.g.: #include <boost/assign/std/vector.hpp> using namespace boost::assign; // bring 'operator+=()' into scope vector<int> v; v += 1,2,3,4,5;
231,547
234,108
Tracing which process that has opened a particular file
From kernel mode in Windows I'm able to intercept and monitor virtually all actions performed on a particular disk. When a file is opened for any purpose I get an event. Now I want to trace which application that opened it. I think this should be possible but don't know how. I'm using the standard file management functions in Windows Win32 API. Thanks in advance. /Robert
Just use Win32 N.API to get the pid from the File handle. It's a FAQ for 15 years...
231,746
231,809
How do I Monitor Text File Changes with C++? Difficulty: No .NET
Use case: 3rd party application wants to programatically monitor a text file being generated by another program. Text file contains data you want to analyze as it's being updated. I'm finding a lot of answers to this question wrapped around FileSystemWatcher but let's say you are writing an application for a Windows machine and can't guarantee .NET is installed. Are there any libraries out there available for this, or am I just going to have to roll my own solution then? Thanks.
You can monitor a directory with FindFirstChangeNotification works on any windows. It's efficent if you know where the file is - otherwise you can use the virtual driver/Filemon described below to check for changes anywhere on the system. Example code here
231,868
239,654
C++ two or more data types in declaration
I'm getting a strange error from g++ 3.3 in the following code: #include <bitset> #include <string> using namespace std; template <int N, int M> bitset<N> slice_bitset(const bitset<M> &original, size_t start) { string str = original.to_string<char, char_traits<char>, allocator<char> >(); string newstr = str.substr(start, N); return bitset<N>(newstr); } int main() { bitset<128> test; bitset<12> result = slice_bitset<12, 128>(test, 0); return 0; } The error is as follows: In function `std::bitset slice_bitset(const std::bitset&, unsigned int)': syntax error before `,' token `char_traits' specified as declarator-id two or more data types in declaration of `char_traits' `allocator' specified as declarator-id two or more data types in declaration of `allocator' syntax error before `>' token It has to be something really silly, but I've already told it to my rubber duck and a friend to no avail. Thanks, Lazyweb.
The selected answer from CAdaker solves the problem, but does not explain why it solves the problem. When a function template is being parsed, lookup does not take place in dependent types. As a result, constructs such as the following can be parsed: template <typename T> class B; template <typename T> void foo (B<T> & b) { // Use 'b' here, even though 'B' not defined } template <typename T> class B { // Define 'B' here. }; However, this "feature" has a cost, and in this case it is that the definition of 'foo' requires hints on the contents of the template 'B'. If 'foo' uses a nested type of 'B', then the typename keyword is required to tell the compiler that the name is a type: template <typename T> void foo (B<T> & b) { typename B<T>::X t1; // 'X' is a type - this declares t1 B<T>::Y * t1; // 'Y' is an object - this is multiplication } Without 'typename' in the above the compiler will assume that X is an object (or function). Similarly, if a member function is called and the call has explicit template arguments then the compiler needs to know to treat the < as the start of a template argument list and not the less than operator: template <typename T> void foo (B<T> & b) { b.template bar<int> (0); // 'bar' is a template, '<' is start of arg list b.Y < 10; // 'Y' is an object, '<' is less than operator } Without template, the compiler assumes that < is the less than operator, and so generates the syntax error when it sees int> since that is not an expression. These hints are required even when the definition of the template is visible. The reason is that an explicit specialization might later change the definition that is actually chosen: template <typename T> class B { template <typename S> void a(); }; template <typename T> void foo (B<T> & b) { b.a < 10; // 'B<int>::a' is a member object } template <> class B<int> { int a; };
231,885
231,921
Violation reading location in std::map operator[]
I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence frequency may be indicative of a race condition, but I don't know why one would cause an exception in this case. Here is the code in question: MyClass::Dostuff() { static map<char, int> mappedChars; if (mappedChars.empty()) { for (char c = '0'; c <= '9'; ++c) { mappedChars[c] = c - '0'; } } // More code here, but mappedChars in not changed. } The exception is thrown in the map's operator[] implementation, on the very first call to the operator[] (Using the VS2005 implementation of STL.) mapped_type& operator[](const key_type& _Keyval) { iterator _Where = this->lower_bound(_Keyval); //exception thrown on the first line // More code here } I already tried freezing threads in operator[] and trying to get them to all run through it at the same time, but I was unable to reproduce the exception using that methodology. Can you think of any reason why that would throw, and only some of the time? (Yes, I know STL is not thread-safe and I'll need to make changes here. I am mostly curious as to WHY I'm seeing the behavior I described above.) As requested, here some further details about the exception: Unhandled exception at 0x00639a1c (app.exe) in app15-51-02-0944_2008-10-23.mdmp: 0xC0000005: Access violation reading location 0x00000004. Thanks to everyone suggesting solutions to multithreading issues, but this isn't what this question is meant to address. Yes, I understand the presented code is not protected correctly and is overkill in what it's trying to accomplish. I already have the fix for it implemented. I'm just trying to get a better understanding of why this exception was thrown to begin with.
Given an address of "4", Likely the "this" pointer is null or the iterator is bad. You should be able to see this in the debugger. If this is null, then the problem isn't in that function but who ever is calling that function. If the iterator is bad, then it's the race condition you alluded to. Most iterators can't tolerate the list being updated. Okay wait - No FM here. Static's are initialized on first use. The code that does this is not multi-thread safe. one thread is doing the initialization while the 2nd thinks it's already been done but it's still in progress. The result is that is uses an uninitialized variable. You can see this in the assembly below: static x y; 004113ED mov eax,dword ptr [$S1 (418164h)] 004113F2 and eax,1 004113F5 jne wmain+6Ch (41141Ch) 004113F7 mov eax,dword ptr [$S1 (418164h)] 004113FC or eax,1 004113FF mov dword ptr [$S1 (418164h)],eax 00411404 mov dword ptr [ebp-4],0 0041140B mov ecx,offset y (418160h) 00411410 call x::x (4111A4h) 00411415 mov dword ptr [ebp-4],0FFFFFFFFh The $S1 is set to 1 when it init's. If set, (004113F5) it jumps over the init code - freezing the threads in the fnc won't help because this check is done on entry to a function. This isn't null, but one of the members is. Fix by moving the map out of the method and into the class as static. Then it will initialize on startup. Otherwise, you have to put a CR around the calls do DoStuff(). You can protect from the remaining MT issues by placing a CR around the use of the map itself (e.g. where DoStuff uses operator[]).
232,030
232,045
C++ Parent class calling a child virtual function
I want a pure virtual parent class to call a child implementation of a function like so: class parent { public: void Read() { //read stuff } virtual void Process() = 0; parent() { Read(); Process(); } } class child : public parent { public: virtual void Process() { //process stuff } child() : parent() { } } int main() { child c; } This should work, but I get an unlinked error :/ This is using VC++ 2k3 Or shouldn't it work, am I wrong?
Title of the following article says it all: Never Call Virtual Functions during Construction or Destruction.
232,161
232,176
Debugging Multi-Project (C++) Solutions in Visual Studio 2005
I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As such, the launcher project is set as the "Startup Project" and, as a result, it's the only one I can set break points in and debug due to my limited knowledge of VS2005. Is there a way to set multiple breakpoints across my five c++ projects in my single VS solution and debug them at the same time if the launcher project is the only project executed from VS? Note: Manually starting new instances of each project via Visual Studio is not an option since their execution needs to be synchronized by the launcher.exe. I apologize if this is convoluted, it's the best I can explain it. Thanks in advance for your help!
What you need is in the Tools menu: Attach to Process. This gives you a list of running processes and allows you to attach your debugger to those processes. For local debugging, Transport and Qualifier should keep their default values. The Attach To value just above the list determines which type of debugging you'll be doing (native or managed are the most common types), and normally the debugger can figure out a good default here as well. The main interesting part is the list of processes - look in this list for the sub-processes you want to debug. Once you've found and selected the process, click Attach in the lower right corner (or just double-click the process), and the debugger will attach to that process and start debugging it. You'll probably also want to enable the Debug Location toolbar, which provides a way to change the focus of the debugger to the various processes and threads you're attached to. Multi-process debugging within one Visual Studio instance can be tricky, so you can always consider starting separate instances to debug each different process. Another tricky aspect of this can be debugging the initial startup of the sub-processes. Often the thing you want to debug happens before you can get the debugger attached, so you need some way to cause the process to wait for you to be ready. An easy way to do this in C++ is to use the IsDebuggerPresent function. Try adding this code to the very beginning of your main() function (or equivalent): while( !IsDebuggerPresent() ) Sleep( 500 ); Or try this code for C#: while( !System.Diagnostics.Debugger.IsAttached ) System.Threading.Thread.Sleep( 500 );
232,926
232,959
How to make consistent dll binaries across VS versions?
For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't changed much. It works some what ok. But when they include this with a C# app, the C# app gets access violation errors, but with classic C++ application it works fine. Is there a strategy that I should know when I provide dlls ?
First, dont pass anything other than plain old data accross DLL boundries. i.e. structs are fine. classes are not. Second, make sure that ownership is not transferred - i.e. any structs passed accross the dll boundry are never deallocated outside the dll. So, if you dll exports a X* GetX() function, there is a corresponding FreeX(X*) type function ensuring that the same runtime that allocated is responsible for de-allocation. Next: Get your DLLs to link to the static runtime. Putting together a project comprimising dls from several 3rd parties, each linked to and expecting different runtimes, potentially different to the runtime expected by the app, is a pain, potentially forcing the installer software to install runtimes for 7.0, 7.1, 8.0 and 9.0 - several of which exist in different service packs which may or may not cause issues. Be kind - statically link your dll projects. -- Edit: You cannot export a c++ class directly with this approach. Sharing class definitions between modules means you MUST have a homogeneous runtime environment as different compilers or versions of compilers will generate decorated names differently. You can bypass this restriction by exporting your class instead as a COM style interface... which is to say, while you cannot export a class in a runtime independent way, you CAN export an "interface", which you can easilly make by declaring a class containing only pure virtual functions... struct IExportedMethods { virtual long __stdcall AMethod(void)=0; }; // with the win32 macros: interface IExportedMethods { STDMETHOD_(long,AMethod)(THIS)PURE; }; In your class definition, you inherit from this interface: class CMyObject: public IExportedMethods { ... You can export interfaces like this by making C factory methods: extern "C" __declspec(dllexport) IExportedClass* WINAPI CreateMyExportedObject(){ return new CMyObject; } This is a very lightweight way of exporting compiler version and runtime independent class versions. Note that you still cannot delete one of these. You Must include a release function as a member of the dll or the interface. As a member of the interface it could look like this: interface IExportedMethods { STDMETHOD_(void) Release(THIS) PURE; }; class CMyObject : public IExportedMethods { STDMETHODIMP_(void) Release(){ delete this; } }; You can take this idea and run further with it - inherit your interface from IUnknown, implement ref counted AddRef and Release methods as well as the ability to QueryInterface for v2 interfaces or other features. And finally, use DllCreateClassObject as the means to create your object and get the necessary COM registration going. All this is optional however, you can easilly get away with a simple interface definition accessed through a C function.
233,035
233,143
What are underscored symbols in a VB DLL?
I have a C++ app in VS2005 and import a VB DLL. IntelliSense shows me all the symbols in the DLL as expected but it also shows all (or nearly all) of them again with an underscore prefix (no @s in them though). Why is this? What are the differences between the underscored items and the normal items?
Assuming you're talking VB6, the leading underscore version _Klass is the Vb-generated default interface for the class Klass. This site has a nice explanation: http://www.15seconds.com/issue/040721.htm
233,127
32,428,427
How can I propagate exceptions between threads?
We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread. The result is that the caller can use the function naively, and internally it'll make use of multiple cores. All good so far.. The problem we have is dealing with exceptions. We don't want exceptions on the worker threads to crash the application. We want the caller to the function to be able to catch them on the main thread. We must catch exceptions on the worker threads and propagate them across to the main thread to have them continue unwinding from there. How can we do this? The best I can think of is: Catch a whole variety of exceptions on our worker threads (std::exception and a few of our own ones). Record the type and message of the exception. Have a corresponding switch statement on the main thread which rethrows exceptions of whatever type was recorded on the worker thread. This has the obvious disadvantage of only supporting a limited set of exception types, and would need modification whenever new exception types were added.
C++11 introduced the exception_ptr type that allows to transport exceptions between threads: #include<iostream> #include<thread> #include<exception> #include<stdexcept> static std::exception_ptr teptr = nullptr; void f() { try { std::this_thread::sleep_for(std::chrono::seconds(1)); throw std::runtime_error("To be passed between threads"); } catch(...) { teptr = std::current_exception(); } } int main(int argc, char **argv) { std::thread mythread(f); mythread.join(); if (teptr) { try{ std::rethrow_exception(teptr); } catch(const std::exception &ex) { std::cerr << "Thread exited with exception: " << ex.what() << "\n"; } } return 0; } Because in your case you have multiple worker threads, you will need to keep one exception_ptr for each of them. Note that exception_ptr is a shared ptr-like pointer, so you will need to keep at least one exception_ptr pointing to each exception or they will be released. Microsoft specific: if you use SEH Exceptions (/EHa), the example code will also transport SEH exceptions like access violations, which may not be what you want.
233,258
233,313
Is there an acceptable limit for memory leaks?
I've just started experimenting with SDL in C++, and I thought checking for memory leaks regularly may be a good habit to form early on. With this in mind, I've been running my 'Hello world' programs through Valgrind to catch any leaks, and although I've removed everything except the most basic SDL_Init() and SDL_Quit() statements, Valgrind still reports 120 bytes lost and 77k still reachable. My question is: Is there an acceptable limit for memory leaks, or should I strive to make all my code completely leak-free?
Be careful that Valgrind isn't picking up false positives in its measurements. Many naive implementations of memory analyzers flag lost memory as a leak when it isn't really. Maybe have a read of some of the papers in the external links section of the Wikipedia article on Purify. I know that the documentation that comes with Purify describes several scenarios where you get false positives when trying to detect memory leaks and then goes on to describe the techniques Purify uses to get around the issues. BTW I'm not affiliated with IBM in any way. I've just used Purify extensively and will vouch for its effectiveness. Edit: Here's an excellent introductory article covering memory monitoring. It's Purify specific but the discussion on types of memory errors is very interesting. HTH. cheers, Rob
233,328
233,339
How do I print the full value of a long string in gdb?
I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?
set print elements 0 From the GDB manual: set print elements number-of-elements Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.
233,446
233,456
Monitor battery charge with Win32 API
I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.
For Vista and up you can use RegisterPowerSettingNotification For earlier functions see the Power Management Functions in this section of the MSDN page "Power Management Functions: Windows Server 2003 and Earlier" You can see example code of the Vista method on codeproject.
233,911
235,713
ie useragent wxWidgets
Im currently using ie as an active x com thing on wxWidgets and was wanting to know if there is any easy way to change the user agent that will always work. Atm im changing the header but this only works when i manually load the link (i.e. call setUrl)
The only way that will "always work," so far as I've been able to find, is changing the user-agent string in the registry. That will, of course, affect every web browser instance running on that machine. You might also try a Google search on DISPID_AMBIENT_USERAGENT. From this Microsoft page: MSHTML will also ask for a new user agent via DISPID_AMBIENT_USERAGENT when navigating to clicked hyperlinks. This ambient property can be overridden, but it is not used when programmatically calling the Navigate method; it will also not cause the userAgent property of the DOM's navigator object or clientInformation behavior to be altered - this property will always reflect Internet Explorer's own UserAgent string. I'm not familiar with the MSHTML component, so I'm not certain that's helpful. I hope that at least gives you a place to start. :-)
234,012
234,420
How can I set the flag FILE_FLAG_BACKUP_SEMANTICS for an fstream object?
How can I set the flag FILE_FLAG_BACKUP_SEMANTICS for an fstream object? You can set most flags with fstream, but it seems like this one is not availble. You can read about the flag here.
I've done this sort thing in the past but it's been a while so I'm not sure I have it right. Not well documented, but in vs2008, fstream takes a FILE object as a constructor. You can create a FILE object from a file id with _fdopen(). You can get a file id from an os handle using _open_osfhandle. So I think it's like: int id = _open_osfhandle(CreateFile(..., FILE_FLAG_BACKUP_SEMANTICS...)); fstream f = new fstream(_fdopen(id));
234,027
234,277
How can I find the index in a string that matches a boost regex?
How can I find the index in a string that matches a boost regex?
If you use boost::regex_match it's the whole string that's matching. Maybe you mean to use regex_search: void index(boost::regex& re,const std::string& input){ boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; std::string::const_iterator s = input.begin(); std::string::const_iterator e = input.end(); while (boost::regex_search(s,e,what,re,flags)){ std::cout << what.position() << std::endl; std::string::difference_type l = what.length(); std::string::difference_type p = what.position(); s += p + l; } }
234,171
234,183
Parse a Date from a String in Win32
I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of GetDateFormat().
No, but you can write a function that will convert the date format string into a sscanf format string and series of variables. Then copy the data from the variables to the SYSTEMTIME structure and you're all set. It's not trivial, but it is probably the most flexible arrangement if you must support many different date formats.
234,234
234,273
Are pipes considered dangerous to use in Windows, from a security standpoint?
Are pipes considered dangerous to use in Windows, from a security standpoint?
Pipes aren't a particular security risk in Windows. If you're worried about security, make sure you set the security descriptor on the pipe to an appropriate DACL. If your usage requires that the pipe is open for anyone to connect to, then you have to treat the incoming data as suspicious, just like any file or network input.
234,365
234,505
Is TCHAR still relevant?
I'm new to Windows programming and after reading the Petzold book I wonder: is it still good practice to use the TCHAR type and the _T() function to declare strings or if I should just use the wchar_t and L"" strings in new code? I will target only Windows 2000 and up and my code will be i18n from the start up.
I would still use the TCHAR syntax if I was doing a new project today. There's not much practical difference between using it and the WCHAR syntax, and I prefer code which is explicit in what the character type is. Since most API functions and helper objects take/use TCHAR types (e.g.: CString), it just makes sense to use it. Plus it gives you flexibility if you decide to use the code in an ASCII app at some point, or if Windows ever evolves to Unicode32, etc. If you decide to go the WCHAR route, I would be explicit about it. That is, use CStringW instead of CString, and casting macros when converting to TCHAR (eg: CW2CT). That's my opinion, anyway.
234,388
234,407
Generating a Deck of Cards
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards. #include <iostream> #include <vector> using namespace std; int main() { vector<char> deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'}; for (int j=0; j<13; j++) { for (int i=0; i<4; i++) { deck.push_back(card[j] suit[i]); } } return 0; } I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.
Try to create class of Card with suit and card as a member and set it as a type of vector. Like public class Card { public: Card(char suit, char card); char suit, card; }; int main() { vector<Card> deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'}; for (int j=0; j<13; j++) { for (int i=0; i<4; i++) { deck.push_back(new Card(card[j],suit[i])); } } return 0; } also using enums instead of chars in suit and card would make it clearer.
234,458
234,491
Do polymorphism or conditionals promote better design?
I recently stumbled across this entry in the google testing blog about guidelines for writing more testable code. I was in agreement with the author until this point: Favor polymorphism over conditionals: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many places in your class you should again think polymorphism. Polymorphism will break your complex class into several smaller simpler classes which clearly define which pieces of the code are related and execute together. This helps testing since simpler/smaller class is easier to test. I simply cannot wrap my head around that. I can understand using polymorphism instead of RTTI (or DIY-RTTI, as the case may be), but that seems like such a broad statement that I can't imagine it actually being used effectively in production code. It seems to me, rather, that it would be easier to add additional test cases for methods which have switch statements, rather than breaking down the code into dozens of separate classes. Also, I was under the impression that polymorphism can lead to all sorts of other subtle bugs and design issues, so I'm curious to know if the tradeoff here would be worth it. Can someone explain to me exactly what is meant by this testing guideline?
Actually this makes testing and code easier to write. If you have one switch statement based on an internal field you probably have the same switch in multiple places doing slightly different things. This causes problems when you add a new case as you have to update all the switch statements (if you can find them). By using polymorphism you can use virtual functions to get the same functionality and because a new case is a new class you don't have to search your code for things that need to be checked it is all isolated for each class. class Animal { public: Noise warningNoise(); Noise pleasureNoise(); private: AnimalType type; }; Noise Animal::warningNoise() { switch(type) { case Cat: return Hiss; case Dog: return Bark; } } Noise Animal::pleasureNoise() { switch(type) { case Cat: return Purr; case Dog: return Bark; } } In this simple case every new animal causes requires both switch statements to be updated. You forget one? What is the default? BANG!! Using polymorphism class Animal { public: virtual Noise warningNoise() = 0; virtual Noise pleasureNoise() = 0; }; class Cat: public Animal { // Compiler forces you to define both method. // Otherwise you can't have a Cat object // All code local to the cat belongs to the cat. }; By using polymorphism you can test the Animal class. Then test each of the derived classes separately. Also this allows you to ship the Animal class (Closed for alteration) as part of you binary library. But people can still add new Animals (Open for extension) by deriving new classes derived from the Animal header. If all this functionality had been captured inside the Animal class then all animals need to be defined before shipping (Closed/Closed).
234,482
234,593
using STL to find all elements in a vector
I have a collection of elements that I need to operate over, calling member functions on the collection: std::vector<MyType> v; ... // vector is populated For calling functions with no arguments it's pretty straight-forward: std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc)); A similar thing can be done if there's one argument to the function I wish to call. My problem is that I want to call a function on elements in the vector if it meets some condition. std::find_if returns an iterator to the first element meeting the conditions of the predicate. std::vector<MyType>::iterator it = std::find_if(v.begin(), v.end(), MyPred()); I wish to find all elements meeting the predicate and operate over them. I've been looking at the STL algorithms for a "find_all" or "do_if" equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.
Boost Lambda makes this easy. #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> std::for_each( v.begin(), v.end(), if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ] ); You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant "is divisible by 2": std::for_each( v.begin(), v.end(), if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ] ); Update: Doing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2): std::for_each( v.begin(), v.end(), [](MyType& mt ) mutable { if( mt % 2 == 0) { mt.myfunc(); } } ); At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax... where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality.
234,503
234,513
What are you using to unit test your C++ code?
I'm looking into some possible options for unit testing C++ classes. So, short and to the point, what are you using?
I'm using cppunit. It is a pretty good port of the iconic JUnit to c++.
234,724
234,740
Is it possible to serialize and deserialize a class in C++?
Is it possible to serialize and deserialize a class in C++? I've been using Java for 3 years now, and serialization / deserialization is fairly trivial in that language. Does C++ have similar features? Are there native libraries that handle serialization? An example would be helpful.
The Boost::serialization library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here. The only native way to do it is to use streams. That's essentially all the Boost::serialization library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format. For built-in types, or your own types with operator<< and operator>> properly defined, that's fairly simple; see the C++ FAQ for more information.
234,866
234,879
Variable Naming Conventions in C++
I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members. For example, the legacy code that I've inheritted has alot of these: struct MyStruct { TCHAR szMyChar[STRING_SIZE]; bool bMyBool; unsigned long ulMyLong; void* pMyPointer; MyObject** ppMyObjects; } Coming from a C# background I was shocked to see the variables with hungarian notation (I couldn't stop laughing at the pp prefix the first time I saw it). I would much rather name my variables this way instead (although I'm not sure if capitalizing the first letter is a good convention. I've seen other ways (see links below)): struct MyStruct { TCHAR MyChar[STRING_SIZE]; bool MyBool; unsigned long MyLong; void* MyPointer; MyObject** MyObjects; } My question: Is this (the former way) still a preferred way to name variables in C++? References: http://geosoft.no/development/cppstyle.html http://www.syntext.com/books/syntext-cpp-conventions.htm http://ootips.org/hungarian-notation.html Thanks!
That kind of Hungarian Notation is fairly useless, and possibly worse than useless if you have to change the type of something. (The proper kind of Hungarian Notation is a different story.) I suggest you use whatever your group does. If you're the only person working on the program, name them whatever way makes the most sense to you.
234,872
235,121
Changing folder security permissions via Win32 API
My C++ application stores some common user data in %CSIDL_COMMON_APPDATA%\Company\Product. I want to make sure the Users group has write permissions to this folder which on Vista it does not. How would do I do this?
Figured it out myself using ATL... CDacl oDacl; AtlGetDacl(strFolder, SE_FILE_OBJECT, &oDacl); oDacl.RemoveAces(Sids::Users()); // Remove existing "Users" access oDacl.AddAllowedAce(Sids::Users(), FILE_ALL_ACCESS, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE); AtlSetDacl(strFolder, SE_FILE_OBJECT, oDacl); Of course my real code contains error checking.
235,072
235,103
Do modern compilers optimize the x * 2 operation to x << 1?
Does the C++ compiler optimize the multiply by two operation x*2 to a bitshift operation x<<1? I would love to believe that yes.
Actually VS2008 optimizes this to x+x: 01391000 push ecx int x = 0; scanf("%d", &x); 01391001 lea eax,[esp] 01391004 push eax 01391005 push offset string "%d" (13920F4h) 0139100A mov dword ptr [esp+8],0 01391012 call dword ptr [__imp__scanf (13920A4h)] int y = x * 2; 01391018 mov ecx,dword ptr [esp+8] 0139101C lea edx,[ecx+ecx] In an x64 build it is even more explicit and uses: int y = x * 2; 000000013FB9101E mov edx,dword ptr [x] printf("%d", y); 000000013FB91022 lea rcx,[string "%d" (13FB921B0h)] 000000013FB91029 add edx,edx This is will the optimization settings on 'Maximize speed' (/O2)
235,326
236,364
Simplest, safest way of holding a bunch of const char* in a set?
I want to hold a bunch of const char pointers into an std::set container [1]. std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers. I know I can define my own functor and implement the operator() by casting the pointers to integers and comparing them, but is there a cleaner, 'standard' way of doing it? Please do not suggest creating std::strings - it is a waste of time and space. The strings are static, so they can be compared for (in)equality based on their address. 1: The pointers are to static strings, so there is no problem with their lifetimes - they won't go away.
Just go ahead and use the default ordering which is less<>. The Standard guarantees that less will work even for pointers to different objects: "For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not." The guarantee is there exactly for things like your set<const char*>.
235,376
235,503
C++ dynamic class ( dynamic hack )
Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet : Myobject *ob; // create an object ob->addField("newField",44); // we add the field to the class and we assign an initial value to it printf("%d",ob->newField); // now we can access that field I don't really care how it would be done , I don't care if it's an ugly hack or not , I would like to know if it could be done , and a small example , if possible . Another Example: say I have an XML file describing this class : <class name="MyClass"> <member name="field1" /> <member name="field2" /> </class> and I want to "add" the fields "field1" and "field2" to the class (assuming the class already exists) . Let's say this is the code for the class : class MyClass { }; I don't want to create a class at runtime , I just want to add members/fields to an existing one . Thank you !
Use a map and a variant. For example, using boost::variant. See http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html (But of course, you can create your own, to suit the types of your XML attributes.) #include <map> #include <boost/variant.hpp> typedef boost::variant< int, std::string > MyValue ; typedef std::map<std::string, MyValue> MyValueMap ; By adding MyValueMap as a member of your class, you can add properties according to their names. Which means the code: oMyValueMap.insert(std::make_pair("newField", 44)) ; oMyValueMap.insert(std::make_pair("newField2", "Hello World")) ; std::cout << oMyValueMap["newField"] ; std::cout << oMyValueMap["newField2"] ; By encapsulating it in a MyObject class, and adding the right overloaded accessors in this MyObject class, the code above becomes somewhat clearer: oMyObject.addField("newField", 44) ; oMyObject.addField("newField2", "Hello World") ; std::cout << oMyObject["newField"] ; std::cout << oMyObject["newField2"] ; But you lose somewhat the type safety of C++ doing so. But for XML, this is unavoidable, I guess.
235,422
235,468
Is there a standard way to do findfirst, findnext with gcc on linux using stl?
I can't seem to find the _findfirst / findfirst, _findnext / findnext API on gcc for Linux, and would actually rather use the Standard Template Library (STL) for that if it is included there. Does anyone know what API there is available for listing files in a directory under Linux for C++ (gcc)?
Check out the Boost.Filesystem library. In particular, the basic_directory_iterator.
235,570
235,693
Can the overall implementation of a component be divided in two objects?
I've seen with Microsoft COM and XPCOM, at least from what I've read and gathered so far, that the implementations of interfaces in a component have to essentially be in the single class that derives all the virtual interfaces. Is this correct? What am I missing? Is there a way to have multiple objects (possibly in separate DLL's) each provide their functionality and still be able to freely transition between them using QueryIterface? What I'm looking for is to have a component with some functionality, but still allow external client code to create new extensions of the component with (possibly) new interfaces. Ideally this should happen without divulging the current source of the component and its implementation.
This should be possible, although probably not supported by the standard high-level wrappers. Most of the wrappers (ATL, MFC, etc.) only support mapping a COM object to a single class. However, QueryInterface is allowed to return a different pointer and calls COM object code, so the first COM object could load a different DLL, instantiate a different object, and return a pointer to it's interface (vtable). It's all possible as far as I know, you'll just likely be writing a lot of the low-level glue code yourself.
235,616
235,623
Multiple definitions of a function template
Suppose a header file defines a function template. Now suppose two implementation files #include this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type. // header.hh template <typename T> void f(const T& o) { // ... } // impl1.cc #include "header.hh" void fimpl1() { f(42); } // impl2.cc #include "header.hh" void fimpl2() { f(24); } One may expect the linker would complain about multiple definitions of f(). Specifically, if f() wouldn't be a template then that would indeed be the case. How come the linker doesn't complain about multiple definitions of f()? Is it specified in the standard that the linker must handle this situation gracefully? In other words, can I always count on programs similar to the above to compile and link? If the linker can be clever enough to disambiguate a set of function template instantiations, why can't it do the same for regular functions, given they are identical as is the case for instantiated function templates?
In order to support C++, the linker is smart enough to recognize that they are all the same function and throws out all but one. EDIT: clarification: The linker doesn't compare function contents and determine that they are the same. Templated functions are marked as such and the linker recognizes that they have the same signatures.
235,664
236,025
How to use std::signaling_nan?
After looking at another question on SO (Using NaN in C++) I became curious about std::numeric_limits<double>::signaling_NaN(). I could not get signaling_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catching SIGFPE but nope... Here is my code: double my_nan = numeric_limits<double>::signaling_NaN(); my_nan++; my_nan += 5; my_nan = my_nan / 10; my_nan = 15 / my_nan; cout << my_nan << endl; numeric_limits<double>::has_signaling_NaN evaluates to true, so it is implemented on my system. Any ideas? I am using ms visual studio .net 2003's C++ compiler. I want to test it on another when I get home. Thanks!
You can use the _control87() function to enable floating-point exceptions. From the MSDN documentation on _control87(): Note: The run-time libraries mask all floating-point exceptions by default. When floating point exceptions are enabled, you can use signal() or SEH (Structured Exception Handling) to catch them.
235,762
235,776
How do you throttle the bandwidth of a socket connection in C?
I'm writing a client-server app using BSD sockets. It needs to run in the background, continuously transferring data, but cannot hog the bandwidth of the network interface from normal use. Depending on the speed of the interface, I need to throttle this connection to a certain max transfer rate. What is the best way to achieve this, programmatically?
The problem with sleeping a constant amount of 1 second after each transfer is that you will have choppy network performance. Let BandwidthMaxThreshold be the desired bandwidth threshold. Let TransferRate be the current transfer rate of the connection. Then... If you detect your TransferRate > BandwidthMaxThreshold then you do a SleepTime = 1 + SleepTime * 1.02 (increase sleep time by 2%) Before or after each network operation do a Sleep(SleepTime) If you detect your TransferRate is a lot lower than your BandwidthMaxThreshold you can decrease your SleepTime. Alternatively you could just decay/decrease your SleepTime over time always. Eventually your SleepTime will reach 0 again. Instead of an increase of 2% you could also do an increase by a larger amount linearly of the difference between TransferRate - BandwidthMaxThreshold. This solution is good, because you will have no sleeps if the user's network is already not as high as you would like.
235,763
235,772
Cancel libcurl easy handle
Is there an easy way to cancel a curl_easy_perform from another thread?
You have to use the callback functions (write/read/progress) to perform the cancel. The other thread needs to set a flag and the callback function checks the flag and returns the proper value to cancel the operation.
236,035
236,052
Unmanaged DLLs in C++
I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you. So, let's assume I have just a function like so: public int calculateSquare(int num) { return num*num; } Ignoring the actual code, what do I require to make this simple function, by itself, into a DLL which I can then call? Do I just add __dllexport or whatever it is to the first line or do I require a header? I am perplexed by all of this.
I cannot stress this enough, the C++ compiler does not see header files, after the preprocessor is done, there's just one big source file ( also called the compilation unit ). So strictly you don't need a header to export this function from a dll. What you do need is some form of conditional compilation to export the function in the dll that you are compiling and to import it in the client code. Typically this is done with a combination of macros and header files. You create a macro called MYIMPORTEXPORT and through the use of macro conditional statements you make it work like __declspec ( dllexport ) in the dll, and __declspec( dllimport ) in the client code. in file MYIMPORTEXPORT.h #ifdef SOME_CONDITION #define MYIMPORTEXPORT __declspec( dllexport ) #else #define MYIMPORTEXPORT __declspec( dllimport ) #endif in file MyHeader.h #include <MyImportExport.h> MYIMPORTEXPORT public int calculateSquare(int num) { return num*num; } in dll .cpp file #define SOME_CONDITION #include <MyHeader.h> in client code .cpp file #include <MyHeader.h> Of course you also need to signal to the linker that you are building a dll with the /DLL option. The build process will also make a .lib file, this is a static lib - called the stub in this case - which the client code needs to link to as if it were linking to a real static lib. Automagically, the dll will be loaded when the client code is run. Of course the dll needs to be found by the OS through its lookup mechanism, which means you cannot put the dll just anywhere, but in a specific location. Here is more on that. A very handy tool to see whether you exported the correct function from the dll, and whether the client code is correctly importing is dumpbin. Run it with /EXPORTS and /IMPORTS respectively.
236,086
236,144
Parsing C++ to generate unit test stubs
I've recently been trying to create units tests for some legacy code. I've been taking the approach of using the linker to show me which functions cause link errors, greping the source to find the definition and creating a stub from that. Is there an easier way? Is there some kind of C++ parser that can give me class definitions, in some easy to use form, from which I can generate stubs?
You may want to investigate http://os.inf.tu-dresden.de/vfiasco/related.html#parsing. But C++ parsing is hard. On the other hand, maybe ctags or something similar can extract class definitions... You may also try to write your own simple (?) parser to generate class stubs from header files... I tried to give you some pointers. As you see, the problem is not easy. But hopefully you can automate at least some part of it.
236,125
351,292
How to convert (not necessarily programmatically) between Windows' wchar_t and GCC/Linux one?
Suppose I have this Windows wchar_t string: L"\x4f60\x597d" and L"\x00e4\x00a0\x597d" and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concrete case would be helpful as well) Please don't direct me to character conversion sites. I would like to convert from L"\x(something)" form and not "end character" form.
One of the most used libraries to do character conversion is the ICU library http://icu-project.org/ It is e.g. used by some boost http://www.boost.org/ libraries.
236,129
237,280
How do I iterate over the words of a string?
How do I iterate over the words of a string composed of words separated by whitespace? Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution: #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string s = "Somewhere down the road"; istringstream iss(s); do { string subs; iss >> subs; cout << "Substring: " << subs << endl; } while (iss); }
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL. #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { using namespace std; string sentence = "And I feel fine..."; istringstream iss(sentence); copy(istream_iterator<string>(iss), istream_iterator<string>(), ostream_iterator<string>(cout, "\n")); } Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic copy algorithm. vector<string> tokens; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens)); ... or create the vector directly: vector<string> tokens{istream_iterator<string>{iss}, istream_iterator<string>{}};
236,156
236,263
Could you recommend any open source projects where the source is extensively tested with unit tests?
Programming is learned by writing programs. But code reading is said to be another good way of learning. I would like to improve my unit-testing skills by reading, examining real-world code. Could you recommend any open source projects where the source is extensively tested with unit tests? I'm interested in code written in C++.
AFAIK C++ Boost libraries - http://boost.org/ - have broadly covered code base, and a policy that every new piece of code must have unit tests with it. Might be worth checking.
236,172
236,199
How do I sort a std::vector by the values of a different std::vector?
I have several std::vector, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold ints and some of them std::strings. Pseudo code: std::vector<int> Index = { 3, 1, 2 }; std::vector<std::string> Values = { "Third", "First", "Second" }; Transformation = sort(Index); Index is now { 1, 2, 3}; ... magic happens as Transformation is applied to Values ... Values are now { "First", "Second", "Third" };
friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…n, along with the elements from the vector dictating the sorting order: typedef vector<int>::const_iterator myiter; vector<pair<size_t, myiter> > order(Index.size()); size_t n = 0; for (myiter it = Index.begin(); it != Index.end(); ++it, ++n) order[n] = make_pair(n, it); Now you can sort this array using a custom sorter: struct ordering { bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) { return *(a.second) < *(b.second); } }; sort(order.begin(), order.end(), ordering()); Now you've captured the order of rearrangement inside order (more precisely, in the first component of the items). You can now use this ordering to sort your other vectors. There's probably a very clever in-place variant running in the same time, but until someone else comes up with it, here's one variant that isn't in-place. It uses order as a look-up table for the new index of each element. template <typename T> vector<T> sort_from_ref( vector<T> const& in, vector<pair<size_t, myiter> > const& reference ) { vector<T> ret(in.size()); size_t const size = in.size(); for (size_t i = 0; i < size; ++i) ret[i] = in[reference[i].first]; return ret; }
236,335
236,338
When I calculate a large factorial, why do I get a negative number?
So, simple procedure, calculate a factorial number. Code is as follows. int calcFactorial(int num) { int total = 1; if (num == 0) { return 0; } for (num; num > 0; num--) { total *= num; } return total; } Now, this works fine and dandy (There are certainly quicker and more elegant solutions, but this works for me) for most numbers. However when inputting larger numbers such as 250 it, to put it bluntly, craps out. Now, the first couple factorial "bits" for 250 are { 250, 62250, 15126750, 15438000, 3813186000 } for reference. My code spits out { 250, 62250, 15126750, 15438000, -481781296 } which is obviously off. My first suspicion was perhaps that I had breached the limit of a 32 bit integer, but given that 2^32 is 4294967296 I don't think so. The only thing I can think of is perhaps that it breaches a signed 32-bit limit, but shouldn't it be able to think about this sort of thing? If being signed is the problem I can solve this by making the integer unsigned but this would only be a temporary solution, as the next iteration yields 938043756000 which is far above the 4294967296 limit. So, is my problem the signed limit? If so, what can I do to calculate large numbers (Though I've a "LargeInteger" class I made a while ago that may be suited!) without coming across this problem again?
2^32 doesn't give you the limit for signed integers. The signed integer limit is actually 2147483647 (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar). You'll need a C++ large number library like this one.
236,399
236,418
What advantages does C++ have over other languages for Qt development?
As well-known, C++ has steeper learning curve than most of the mainstream languages, which results in better performance . But, does using C++ over other languages[like Java,Ruby,Python] for Qt development have still (major) advantages,let's say about Qtopia? If any, what are they?
Qt is natively a C++ API, so any other languages have to have wrapper code around it which needs to be maintained, etc. The primary documentation will also be for the C++ API. I'm not sure if there are any "official" bindings to other languages which are maintained and released together with Qt.
236,669
236,674
What's an easy way to obtain the current svn revision in a c++ visual studio application
Is there any easy way to access the SVN repository revision number and store it in a c++ string in a c++ visual studio application? Thanks for your help in advance!
If you have tortoise SVN you can use SubWCRev.exe Create a file called: RevisionInfo.tmpl int SvnRevision = $WCREV$; Then execute this command: SubWCRev.exe . RevisionInfo.tmpl RevisionInfo.cpp It will create a file ReivisonInfo.cpp with your revision number as follows: int SvnRevision = 5000; From your other files just do something like: extern int SvnRevision; to access the global variable from within that file. You could also use SvnRev
236,792
242,676
designing business msgs parser / rewriting from scratch
I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD policy and I have 20% unit test coverage (thank you Michael Feathers for your book!), most of it in critical parts. I have some white-box Fitness tests as well (whole business scenarios are covered there). I feel that I cannot further refactor this app and I'm safe to play hard with it. It's designed so badly, I want to rewrite it. App itself is around 20k of challenging legacy C/C++ code. There were other dependencies but I manged to decouple most of them. All I have is Sun C++ compiler, cppunitlite, STLPort and Boost. Please do not suggest other technologies (no XML, Java etc) as this is not the option in my organization. I'd like to do it with modern C++ (perhaps play with metaprogramming...), TDD from start to the end. There are about 30 types of msgs I need to parse. Each of them is composed of 3-10 lines, most of them are pretty similar. This is root of all evil -> lots of code duplication. Each msgs has a class describing how it should be parsed. Take a look at the main inheritance tree: MSG_A MSG_B / \ / \ MSG_A_NEW MSG_A_CNL MSG_B_NEW MSG_B_CNL Both trees goes much deeper. There are very small differences between MSG_A_NEW and MSG_B_NEW. It should be handled by single class that could be injected with some small customization. My initial plan it to have one generic msg class that will be customized. Some entity (builder... ?) will take a look at the msgs and initialize proper object that will be able to parse the msg. Another entity will be able to discover what line is it and this info will be used by builder. I'm planning to write several parsers that are responsible for parsing just one specific line. This will allow me to reuse it in parsing different msgs. There are several challenges that I struggle to solve in an elegant and extensible way. Each type of msg: has min and max number if lines - has some must-have lines - has some optional lines - certain lines must be at certain places (i.e. date cannot be before msg type), order matters I need to be able to validate format of the msgs. I'm not sure if I explained the design challenge here good enough. My design experience is very limited. I've been bug-fixing for a while now and finally I will have a change to do some fun codding :) What high-level advice do you have for that? Which design patterns can you identify in this description? Main design constraint is maintainability and extensibility with performance at the bottom (we have other bottlenecks anyway...).
I would advise you not to inherit your specific message handling classes from base classes that contain the common code like this: CommonHandler ^ ^ | | = inheritance MsgAHandler ^ ^ | | ANewHandler ACnlHandler This approach suffers from bad reusability: for example if you want to handle some kind of message that needs to do things from A_NEW and A_CNL, you would end up with multiple inheritance rather quickly. Instead I would choose a class containing the common code, that makes calls to an interface to customize that common code. Something like this: BasicHandler <>--- IMsgHandler ------------\ 1 1 ^ ^ ^ ^ * | ^ | | | | | | = inheritance MsgAHandler | | ANewHandler 1 | ACnlHandler HandlerContainer <>-/ <>- = containment The HandlerContainer class can be used to group the behaviour of other handlers together. This pattern is called 'Composite', if I'm not mistaken. And to create the correct instances of the handlers, you will of course need some kind of factory. Good luck!
236,801
237,074
Should operator<< be implemented as a friend or as a member function?
That's basically the question, is there a "right" way to implement operator<< ? Reading this I can see that something like: friend bool operator<<(obj const& lhs, obj const& rhs); is preferred to something like ostream& operator<<(obj const& rhs); But I can't quite see why should I use one or the other. My personal case is: friend ostream & operator<<(ostream &os, const Paragraph& p) { return os << p.to_str(); } But I could probably do: ostream & operator<<(ostream &os) { return os << paragraph; } What rationale should I base this decision on? Note: Paragraph::to_str = (return paragraph) where paragraph's a string.
The problem here is in your interpretation of the article you link. Equality This article is about somebody that is having problems correctly defining the bool relationship operators. The operator: Equality == and != Relationship < > <= >= These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members). There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous. Streaming The stream operators: operator << output operator >> input When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you. It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together. #include <iostream> class Paragraph { public: explicit Paragraph(std::string const& init) :m_para(init) {} std::string const& to_str() const { return m_para; } bool operator==(Paragraph const& rhs) const { return m_para == rhs.m_para; } bool operator!=(Paragraph const& rhs) const { // Define != operator in terms of the == operator return !(this->operator==(rhs)); } bool operator<(Paragraph const& rhs) const { return m_para < rhs.m_para; } private: friend std::ostream & operator<<(std::ostream &os, const Paragraph& p); std::string m_para; }; std::ostream & operator<<(std::ostream &os, const Paragraph& p) { return os << p.to_str(); } int main() { Paragraph p("Plop"); Paragraph q(p); std::cout << p << std::endl << (p == q) << std::endl; }
237,064
237,072
C++ Nested classes driving me crazy
i am trying to compile this very simple piece of code class myList { public: std::vector<std::string> vec; class Items { public: void Add(std::string str) { myList::vec.push_back(str); }; }items; }; int main() { myList newList; newList.items.Add("A"); } what can i do to make this work without creating more objects that needed or overcomplicating stuff...
Add a couple of constructors and a pointer to the parent class. #include <string> #include <vector> class myList { public: std::vector<std::string> vec; myList(): items(this) {} // Added class Items { public: Items(myList *ml): self(ml) {} // Added void Add(std::string str) { self->vec.push_back(str); // Changed }; myList *self; //Added }items; }; int main() { myList newList; newList.items.Add("A"); } You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance. As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.
237,285
237,341
Where do you find templates useful?
At my workplace, we tend to use iostream, string, vector, map, and the odd algorithm or two. We haven't actually found many situations where template techniques were a best solution to a problem. What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a new solution to a problem that you encountered in real life. As a bribe, expect an up vote for your answer.
I've used a lot of template code, mostly in Boost and the STL, but I've seldom had a need to write any. One of the exceptions, a few years ago, was in a program that manipulated Windows PE-format EXE files. The company wanted to add 64-bit support, but the ExeFile class that I'd written to handle the files only worked with 32-bit ones. The code required to manipulate the 64-bit version was essentially identical, but it needed to use a different address type (64-bit instead of 32-bit), which caused two other data structures to be different as well. Based on the STL's use of a single template to support both std::string and std::wstring, I decided to try making ExeFile a template, with the differing data structures and the address type as parameters. There were two places where I still had to use #ifdef WIN64 lines (slightly different processing requirements), but it wasn't really difficult to do. We've got full 32- and 64-bit support in that program now, and using the template means that every modification we've done since automatically applies to both versions.
237,370
283,023
Does "std::size_t" make sense in C++?
In some code I've inherited, I see frequent use of size_t with the std namespace qualifier. For example: std::size_t n = sizeof( long ); It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?). Isn't it true that size_t is built into C++ and therefore in the global namespace? Is a header file include needed to use size_t in C++? Another way to ask this question is, would the following program (with no includes) be expected to compile on all C++ compilers? size_t foo() { return sizeof( long ); }
There seems to be confusion among the stackoverflow crowd concerning this ::size_t is defined in the backward compatibility header stddef.h . It's been part of ANSI/ISO C and ISO C++ since their very beginning. Every C++ implementation has to ship with stddef.h (compatibility) and cstddef where only the latter defines std::size_t and not necessarily ::size_t. See Annex D of the C++ Standard.
237,425
237,454
What are the coolest examples of metaprogramming that you've seen in C++?
What are the coolest examples of metaprogramming that you've seen in C++? What are some practical uses of metaprogramming that you've seen in C++?
Personally, I think Boost.Spirit is a pretty amazing example of meta-programming. It's a complete parser generator that lets you express grammars using C++ syntax.
237,542
237,635
Getting base name of the source file at compile time
I'm using GCC; __FILE__ returns the current source file's entire path and name: /path/to/file.cpp. Is there a way to get just the file's name file.cpp (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings? I am using this in an error logging macro. I really do not want my source's full path making its way into the executable.
If you're using a make program, you should be able to munge the filename beforehand and pass it as a macro to gcc to be used in your program. For example, in your makefile, change the line: file.o: file.c gcc -c -o file.o src/file.c to: file.o: src/file.c gcc "-DMYFILE=\"`basename $<`\"" -c -o file.o src/file.c This will allow you to use MYFILE in your code instead of __FILE__. The use of basename of the source file $< means you can use it in generalized rules such as .c.o. The following code illustrates how it works. First, a makefile: mainprog: main.o makefile gcc -o mainprog main.o main.o: src/main.c makefile gcc "-DMYFILE=\"`basename $<`\"" -c -o main.o src/main.c Then a file in a subdirectory, src/main.c: #include <stdio.h> int main (int argc, char *argv[]) { printf ("file = %s\n", MYFILE); return 0; } Finally, a transcript showing it running: pax:~$ mainprog file = main.c Note the file = line which contains only the base name of the file, not the directory name as well.
237,716
237,779
Is it possible to write a function like next_permutation but that only permutes r values, instead of n?
std::next_permutation (and std::prev_permutation) permute all values in the range [first, last) given for a total of n! permutations (assuming that all elements are unique). is it possible to write a function like this: template<class Iter> bool next_permutation(Iter first, Iter last, Iter choice_last); That permutes the elements in the range [first, last) but only chooses elements in the range [first, choice_last). ie we have maybe 20 elements and want to iterate through all permutations of 10 choices of them, 20 P 10 options vs 20 P 20. Iter is a random access iterator for my purposes, but if it can be implemented as a bidirectional iterator, then great! The less amount of external memory needed the better, but for my purposes it doesn't matter. The chosen elements on each iteration are input to the first elements of the sequence. Is such a function possible to implement? Does anyone know of any existing implementations? Here is essentially what I am doing to hack around this. Suggestions on how to improve this are also welcome. Start with a vector V of N elements of which I want to visit each permutation of R elements chosen from it (R <= N). Build a vector I of length R with values { 0, 1, 2, ... R - 1 } to serve as an index to the elements of V On each iteration, build a vector C of length R with values { V[I[0]], V[I[1]], ... V[I[R - 1]] } Do something with the values in C. Apply a function to permute the elements of I and iterate again if it was able to. That function looks like this: bool NextPermutationIndices(std::vector<int> &I, int N) { const int R = I.size(); for (int i = R - 1; ; --i) { if (I[i] < N - R + i) { ++I[i]; return true; } if (i == 0) return false; if (I[i] > I[i-1] + 1) { ++I[i-1]; for (int j = i; j < R; ++j) I[j] = I[j-1] + 1; return true; } } } That function is very complicated due to all the possible off-by-one errors, as well everything using it are more complicated than is probably necessary. EDIT: It turns out that it was significantly easier than I had even imagined. From here, I was able to find exact implementations of many of the exact algorithms I needed (combinations, permutations, etc.). template<class BidirectionalIterator> bool next_partial_permutation(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { std::reverse(middle, last); return std::next_permutation(first, last); } Plus there is a combination algorithm there that works in a similar way. The implementation of that is much more complication though.
To iterate over nPk permutations, I've used the for_each_permutation() algorithm presented in this old CUJ article before. It uses a nice algorithm from Knuth which rotates the elements in situ, leaving them in the original order at the end. Therefore, it meets your no external memory requirement. It also works for BidirectionalIterators. It doesn't meet your requirement of looking like next_permutation(). However, I think this is a win - I don't like stateful APIs.
237,804
7,906,630
What new capabilities do user-defined literals add to C++?
C++11 introduces user-defined literals which will allow the introduction of new literal syntax based on existing literals (int, hex, string, float) so that any type will be able to have a literal presentation. Examples: // imaginary numbers std::complex<long double> operator "" _i(long double d) // cooked form { return std::complex<long double>(0, d); } auto val = 3.14_i; // val = complex<long double>(0, 3.14) // binary values int operator "" _B(const char*); // raw form int answer = 101010_B; // answer = 42 // std::string std::string operator "" _s(const char* str, size_t /*length*/) { return std::string(str); } auto hi = "hello"_s + " world"; // + works, "hello"_s is a string not a pointer // units assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds At first glance this looks very cool but I'm wondering how applicable it really is, when I tried to think of having the suffixes _AD and _BC create dates I found that it's problematic due to operator order. 1974/01/06_AD would first evaluate 1974/01 (as plain ints) and only later the 06_AD (to say nothing of August and September having to be written without the 0 for octal reasons). This can be worked around by having the syntax be 1974-1/6_AD so that the operator evaluation order works but it's clunky. So what my question boils down to is this, do you feel this feature will justify itself? What other literals would you like to define that will make your C++ code more readable? Updated syntax to fit the final draft on June 2011
Here's a case where there is an advantage to using user-defined literals instead of a constructor call: #include <bitset> #include <iostream> template<char... Bits> struct checkbits { static const bool valid = false; }; template<char High, char... Bits> struct checkbits<High, Bits...> { static const bool valid = (High == '0' || High == '1') && checkbits<Bits...>::valid; }; template<char High> struct checkbits<High> { static const bool valid = (High == '0' || High == '1'); }; template<char... Bits> inline constexpr std::bitset<sizeof...(Bits)> operator"" _bits() noexcept { static_assert(checkbits<Bits...>::valid, "invalid digit in binary string"); return std::bitset<sizeof...(Bits)>((char []){Bits..., '\0'}); } int main() { auto bits = 0101010101010101010101010101010101010101010101010101010101010101_bits; std::cout << bits << std::endl; std::cout << "size = " << bits.size() << std::endl; std::cout << "count = " << bits.count() << std::endl; std::cout << "value = " << bits.to_ullong() << std::endl; // This triggers the static_assert at compile time. auto badbits = 2101010101010101010101010101010101010101010101010101010101010101_bits; // This throws at run time. std::bitset<64> badbits2("2101010101010101010101010101010101010101010101010101010101010101_bits"); } The advantage is that a run-time exception is converted to a compile-time error. You couldn't add the static assert to the bitset ctor taking a string (at least not without string template arguments).
237,899
246,936
How to draw a filled envelop like a cone on OpenGL (using GLUT)?
I am using freeglut for opengl rendering... I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied. Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)? or is there some other api that has an inbuilt support for filled up geometries.. Edit1: just to clarify the 2D cone thing... the envelop is the graphical interpretation of the coverage area of an aircraft during interception(of an enemy aircraft)...that resembles a sector of a circle..i should have mentioned sector instead.. and glutSolidCone doesnot help me as i want to draw a filled sector of a circle...which i have already done...what remains to do is to fill it with some color... how to fill geometries with color in opengl? Edit2: All the answers posted to this questions can work for my problem in a way.. But i would definitely would want to know a way how to fill a geometry with some color. Say if i want to draw an envelop which is a parabola...in that case there would be no default glut function to actually draw a filled parabola(or is there any?).. So to generalise this question...how to draw a custom geometry in some solid color? Edit3: The answer that mstrobl posted works for GL_TRIANGLES but for such a code: glBegin(GL_LINE_STRIP); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); which draws a square...only a wired square is drawn...i need to fill it with blue color. anyway to do it? if i put some drawing commands for a closed curve..like a pie..and i need to fill it with a color is there a way to make it possible... i dont know how its possible for GL_TRIANGLES... but how to do it for any closed curve?
On Edit3: The way I understand your question is that you want to have OpenGL draw borders and anything between them should be filled with colors. The idea you had was right, but a line strip is just that - a strip of lines, and it does not have any area. You can, however, have the lines connect to each other to define a polygon. That will fill out the area of the polygon on a per-vertex basis. Adapting your code: glBegin(GL_POLYGON); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); Please note however, that drawing a polygon this way has two limitations: The polygon must be convex. This is a slow operation. But I assume you just want to get the job done, and this will do it. For the future you might consider just triangulating your polygon.
237,978
238,032
What is std::safe_string?
An answer to one of my questions included the following line of code: label = std::safe_string(name); // label is a std::string The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of safe_string and neither, apparently, has google (nor could I find it in the 98 standard). Does anyone know what this is about?
After searching google code search (I should have thought of this first...) I found this: //tools-cgi.cpp string safe_string (const char * s) { return (s != NULL) ? s : ""; } Which converts NULLs to zero length strings. Although this is not standard it's probably some sort of extension in a specific STL implementation which was referred to in the answer.
238,008
238,023
Relative performance of std::vector vs. std::list vs. std::slist?
For a simple linked list in which random access to list elements is not a requirement, are there any significant advantages (performance or otherwise) to using std::list instead of std::vector? If backwards traversal is required, would it be more efficient to use std::slist and reverse() the list prior to iterating over its elements?
As usual the best answer to performance questions is to profile both implementations for your use case and see which is faster. In general if you have insertions into the data-structure (other than at the end) then vector may be slower, otherwise in most cases vector is expected to perform better than list if only for data locality issues, this means that if two elements that are adjacent in the data-set are adjacent in memory then the next element will already be in the processor's cache and will not have to page fault the memory into the cache. Also keep in mind that the space overhead for a vector is constant (3 pointers) while the space overhead for a list is paid for each element, this also reduces the number of full elements (data plus overhead) that can reside in the cache at any one time.
238,441
238,461
Can a C compiler rearrange stack variables?
I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had: void func() { char c; int i; short s; ... } We would reorder this to be: void func() { int i; short s; char c; ... } Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes. Is this standard behavior for C compilers or just a shortcoming of the compiler we were using? It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to. It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way. As a bonus question, does this also apply to C++ compilers? Edit If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this? I'd like to see compiler documentation or something similar that backs this up. Edit Again Thanks everybody for your help. For documentation, the best thing I've been able to find is the paper Optimal Stack Slot Assignment in GCC(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003. The project in question here was using the ADS compiler for ARM development. It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame. That compiler didn't automatically rearrange locals to take advantage of this. The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could. I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct. Thanks again.
As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that. It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment. IIRC newer MSVC compilers use that freedom in their fight against buffer overflows of locals. As a side note, in C++, the order of destruction must be reverse order of declaration, even if the compiler reorders the memory layout. (I can't quote chapter and verse, though, this is from memory.)
238,465
238,928
Static or dynamic linking the CRT, MFC, ATL, etc
Back in the 90s when I first started out with MFC I used to dynamically link my apps and shipped the relevant MFC DLLs. This caused me a few issues (DLL hell!) and I switched to statically linking instead - not just for MFC, but for the CRT and ATL. Other than larger EXE files, statically linking has never caused me any problems at all - so are there any downsides that other people have come across? Is there a good reason for revisiting dynamic linking again? My apps are mainly STL/Boost nowadays FWIW.
There are some downsides: Bigger exe size (esp if you ship multiple exe's) Problems using other DLL's which rely on or assume dynamic linking (eg: 3rd party DLL's which you cannot get as static libraries) Different c-runtimes between DLL's with independent static linkage (no cross-module allocate/deallocate) No automatic servicing of shared components (no ability to have 3rd party module supplier update their code to fix issues without recompiling and updating your application) We do static linking for our Windows apps, primarily because it allows xcopy deployment, which is just not possible with installing or relying on SxS DLL's in a way which works, since the process and mechanism is not well documented or easily remotable. If you use local DLL's in the install directory it will kinda work, but it's not well supported. The inability to easily do remote installation without going through a MSI on the remote system is the primary reason why we don't use dynamic linking, but (as you pointed out) there are many other benefits to static linking. There are pros and cons to each; hopefully this helps enumerate them.