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
308,061
308,075
Virtualization in Super Class Constructor
I was of the opinion that virtualization doesnt work in the super class constructor as per the design of OOP. For example, consider the following C# code. using System; namespace Problem { public class BaseClass { public BaseClass() { Console.WriteLine("Hello, World!"); this.PrintRandom(); } public virtual void PrintRandom() { Console.WriteLine("0"); } } public class Descendent : BaseClass { private Random randomValue; public Descendent() { Console.WriteLine("Bonjour, Monde!"); randomValue = new Random(); } public override void PrintRandom() { Console.WriteLine(randomValue.NextDouble().ToString()); } public static void Main() { Descendent obj = new Descendent(); obj.PrintRandom(); Console.ReadLine(); } } } This code breaks because when the object of Descendent is made, it calls the base class constructor and we have a virtual method call in Base Class constructor which in turn calls the Derived class's method and hence, it crashes since randomValue is not intialized by that time. A similar code works in C++ because the call to PrintRandom is not routed to the derived class since IMO, the order in C++ is something like: 1. call for base class constructor 2. Update V - Table for this class 3. call the constructor code My Question is that firstly whether I am right that as per OOP principles, virtualization shouldn't/doesn't work in the super class constructor and secondly if I am right, then why the behavior is different in all .NET languages ( I have tested it with C#, VB.NET and MC++)
In native C++, the program works as expected: you get the call to the base class version of the virtual function within the base class constructor. At the time of the constructor call, only the base class and its virtual functions exist, so you get the lowest-level version of the virtual function defined at the time. This does not imply that virtualization cannot be used, you just won't get the subclass versions of virtual methods in the constructors of base classes (which is why it's not recommended). Obviously, as you can see, managed code works differently, because (iirc) the entire object is built before the constructors are called, and thus you get the subclass virtual function before the subclass constructor. This is a documented difference between the behaviors of the languages, but should be consistent across .NET languages (since they all compile to the same IL).
308,276
308,318
Can I call a constructor from another constructor (do constructor chaining) in C++?
As a C# developer I'm used to running through constructors: class Test { public Test() { DoSomething(); } public Test(int count) : this() { DoSomethingWithCount(count); } public Test(int count, string name) : this(count) { DoSomethingWithName(name); } } Is there a way to do this in C++? I tried calling the Class name and using the 'this' keyword, but both fail.
C++11: Yes! C++11 and onwards has this same feature (called delegating constructors). The syntax is slightly different from C#: class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} }; C++03: No Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this: You can combine two (or more) constructors via default parameters: class Foo { public: Foo(char x, int y=0); // combines two constructors (char) and (char, int) // ... }; Use an init method to share common code: class Foo { public: Foo(char x); Foo(char x, int y); // ... private: void init(char x, int y); }; Foo::Foo(char x) { init(x, int(x) + 7); // ... } Foo::Foo(char x, int y) { init(x, y); // ... } void Foo::init(char x, int y) { // ... } See the C++FAQ entry for reference.
308,277
308,286
What are the consequences of ignoring: warning: unused parameter
I am working on a C++ project and I noticed that we have a number of warnings about unused parameters. What effect could it have if these warnings are ignored?
The function with an unused parameter may have a real bug in the following cases: There is an output parameter, which is not being assigned or written into, resulting in undefined value for the caller. One of parameters is a callback function pointer, which you must invoke and forget to do so. May happen if there is a lot of #ifdefs in the function. You declare a local variable with the same name that shadows a parameter and subsequently use the wrong value down in the function. Not using an input parameters may be harmless, but you can reduce the noise to see useful warnings by marking unused input parameters explicitly in the beginning of the function by casting it to void (works for both C and C++): (void)param1; Or, #define UNUSED(expr) do { (void)(expr); } while (0) ... void foo(int param1, int param2) { UNUSED(param2); bar(param1); } Or omit parameter name (C++ only): void foo(int param1, int /*param2*/) { bar(param1); }
308,279
308,724
C++ strings: [] vs. *
Been thinking, what's the difference between declaring a variable with [] or * ? The way I see it: char *str = new char[100]; char str2[] = "Hi world!"; .. should be the main difference, though Im unsure if you can do something like char *str = "Hi all"; .. since the pointer should the reference to a static member, which I don't know if it can? Anyways, what's really bugging me is knowing the difference between: void upperCaseString(char *_str) {}; void upperCaseString(char _str[]) {}; So, would be much appreciated if anyone could tell me the difference? I have a hunch that both might be compiled down the same, except in some special cases? Ty
Let's look into it (for the following, note char const and const char are the same in C++): String literals and char * "hello" is an array of 6 const characters: char const[6]. As every array, it can convert implicitly to a pointer to its first element: char const * s = "hello"; For compatibility with C code, C++ allows one other conversion, which would be otherwise ill-formed: char * s = "hello"; it removes the const!. This is an exception, to allow that C-ish code to compile, but it is deprecated to make a char * point to a string literal. So what do we have for char * s = "foo"; ? "foo" -> array-to-pointer -> char const* -> qualification-conversion -> char *. A string literal is read-only, and won't be allocated on the stack. You can freely make a pointer point to them, and return that one from a function, without crashing :). Initialization of an array using a String literal Now, what is char s[] = "hello"; ? It's a whole other thing. That will create an array of characters, and fill it with the String "hello". The literal isn't pointed to. Instead it is copied to the character-array. And the array is created on the stack. You cannot validly return a pointer to it from a function. Array Parameter types. How can you make your function accept an array as parameter? You just declare your parameter to be an array: void accept_array(char foo[]); but you omit the size. Actually, any size would do it, as it is just ignored: The Standard says that parameters declared in that way will be transformed to be the same as void accept_array(char * foo); Excursion: Multi Dimensional Arrays Substitute char by any type, including arrays itself: void accept_array(char foo[][10]); accepts a two-dimensional array, whose last dimension has size 10. The first element of a multi-dimensional array is its first sub-array of the next dimension! Now, let's transform it. It will be a pointer to its first element again. So, actually it will accept a pointer to an array of 10 chars: (remove the [] in head, and then just make a pointer to the type you see in your head then): void accept_array(char (*foo)[10]); As arrays implicitly convert to a pointer to their first element, you can just pass an two-dimensional array in it (whose last dimension size is 10), and it will work. Indeed, that's the case for any n-dimensional array, including the special-case of n = 1; Conclusion void upperCaseString(char *_str) {}; and void upperCaseString(char _str[]) {}; are the same, as the first is just a pointer to char. But note if you want to pass a String-literal to that (say it doesn't change its argument), then you should change the parameter to char const* _str so you don't do deprecated things.
308,307
308,346
Setting file version number in Visual Studio 2005 C++
Can anyone point me in the right direction how to configure Visual Studio 2005 with our C++ console project how we can include a 'File Version' in the details section of the file properties. I've tried resource files without any luck. This is with a C++ project just for clarification, and big thank you for the guys you responded with C# suggestions. Thanks in advance.
If you are talking about unmanaged c++, you need to add a version resource to the project. right-click on the project, choose add - Resource.... Choose Version and press new. There you can enter all info you need.
308,364
308,383
C++ bitfield packing with bools
I've just done a test with bitfields, and the results are surprising me. class test1 { public: bool test_a:1; bool test_b:1; bool test_c:1; bool test_d:1; bool test_e:1; bool test_f:1; bool test_g:1; bool test_h:1; }; class test2 { public: int test_a:1; int test_b:1; int test_c:1; int test_d:1; int test_e:1; int test_f:1; int test_g:1; int test_h:1; }; class test3 { public: int test_a:1; bool test_b:1; int test_c:1; bool test_d:1; int test_e:1; bool test_f:1; int test_g:1; bool test_h:1; }; The results were:- sizeof(test1) = 1 // This is what I'd expect. 8 bits in a byte sizeof(test2) = 4 // Reasonable. Maybe padded out to the size of an int. sizeof(test3) = 16 // What??? Is this what you'd expect, or a compiler bug? (Codegear C++ Builder 2007, btw...)
your compiler has arranged all of the members of test3 on integer size boundaries. Once a block has been used for a given type (integer bit-field, or boolean bit-field), the compiler does not allocate any further bit fields of a different type until the next boundary. I doubt it is a bug. It probably has something to do with the underlying architecture of your system. edit: c++ compilers will allocate bit-fields in memory as follows: several consecutive bit-field members of the same type will be allocated sequentially. As soon as a new type needs to be allocated, it will be aligned with the beginning of the next logical memory block. The next logical block will depend on your processor. Some processors can align to 8-bit boundaries, while others can only align to 16-bit boundaries. In your test3, each member is of a different type than the one before it, so the memory allocation will be 8 * (the minimum logical block size on your system). In your case, the minimum block size is two bytes (16-bit), so the size of test3 is 8*2 = 16. On a system that can allocate 8-bit blocks, I would expect the size to be 8.
308,450
308,657
Netbeans or Eclipse for C++?
I'm currently working on a pet project and need to do C++ development on Windows, Mac, Linux, and Solaris, and I've narrowed it down to Netbeans and Eclipse, so I was wonderig which is more solid as a C++ editor. I just need solid editing, good autocompletion for templated code ad external libraries, and project file management, the build tools are external, so thats irrelevant here, for my comparison. Thus which is a better choice? Note: I know I should be using emacs or vim, but the issue is, my theory at least, that I'm left handed, so I use my right side (design,creativity) of the brain more than the left side (logic, memory), so I just simply cannot use emacs or vim, my brain simply isn't compatible, I tried them many times too, even used emacs for a few months but it drove me crazy... Thanks
I haven't used NetBeans, but Eclipse CDT (C Developer Tools, which includes C++), especially with the latest version, is really quite excellent: Syntax checking and spell checking Syntax highlighting that distinguishes between library calls and your function calls and between local and member variables and is even applied to code that's #ifdef'ed out Macro expansion that can step you through each level of macro application or show the final result even of very complex Boost Preprocessor macros A file and class outline view that updates dynamically to show where you are in a file. (Commercial IDE's I've used fail to do this.) Powerful, flexible Find/Replace and Find in Files features with complete Perl-style regex support. It's also supposed to be able to do a C/C++ Find in Files that can search based on language semantics (e.g., only find references, not declarations), although this sometimes doesn't work for me. Automatic tracking of TODO and other comment tags Mouseover tips that show the exact declaration of a variable or function, including any comments, instead of just where a variable or function is declared. (Again, commercial IDE's I've used fail to do this.) Support via plugins for Subversion, Doxygen, etc. Some refactoring support - rename, extract constant, extract function, a few others Code reformatter, based on user-definable code styles You'd asked specifically about its editor; the Eclipse editor is good enough that I use it in preference to the commercial IDE for our product whenever I don't need the commercial IDE's forms designer. Eclipse's debugger integration (using gdb) is tolerable but not great, and its memory usage is high. A few features (like the C/C++ Find in Files) don't work reliably or require reindexing (which is time consuming) for no apparent reason, but the latest version seems more reliable in this regard. Can someone who's used NetBeans fill in how it compares?
308,477
308,661
C++ Smart Pointer performance
How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components?
Dereferencing smart pointers is typically trivial, certainly for boost in release mode. All boost checks are at compile-time. (Smart pointers could in theory do smart stuff across threads). This still leaves a lot of other operations. Nicola mentioned construction, copying and destruction. This is not the complete set, though. Other important operations are swapping, assignment and resetting to NULL. Basically, any operation that requires smartness. Note that some of these operations are excluded by some smart pointers. E.g. boost::scoped_ptr cannot even be copied, let alone be assigned. As this leaves less operations, the implementation can be optimized for these fewer methods. In fact, with TR1 coming up, it's quite likely that compilers can do better with smart pointers than raw pointers. E.g. it's possible that a compiler can prove that a smart non-copyable pointer is not aliased in some situations, merely because it's non-copyable. Think about it: aliasing occurs when two pointers are created pointing to the same object. If the first pointer cannot be copied, how would a second pointer end up pointing to the same object? (There are ways around that, too - operator* has to return an lvalue)
308,619
308,632
STL Vector comparison issue
With a vector defined as std::vector<std::string>, Wondering why the following is valid: if ( vecMetaData[0] != "Some string" ) { ... But not this: switch ( vecMetaData[1] ) { ... Visual studio complains : error C2450: switch expression of type 'std::basic_string<_Elem,_Traits,_Ax>' is illegal 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits<char>, 1> _Ax=std::allocator<char> 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
switch() needs an integral type (like int, char, ...) string is not an integral type, neither does string have an implicit conversion to an integral type, so it can't be used in a switch statement
309,491
309,523
How do I read the results of a system() call in C++?
I'm using the following code to try to read the results of a df command in Linux using popen. #include <iostream> // file and std I/O functions int main(int argc, char** argv) { FILE* fp; char * buffer; long bufSize; size_t ret_code; fp = popen("df", "r"); if(fp == NULL) { // head off errors reading the results std::cerr << "Could not execute command: df" << std::endl; exit(1); } // get the size of the results fseek(fp, 0, SEEK_END); bufSize = ftell(fp); rewind(fp); // allocate the memory to contain the results buffer = (char*)malloc( sizeof(char) * bufSize ); if(buffer == NULL) { std::cerr << "Memory error." << std::endl; exit(2); } // read the results into the buffer ret_code = fread(buffer, 1, sizeof(buffer), fp); if(ret_code != bufSize) { std::cerr << "Error reading output." << std::endl; exit(3); } // print the results std::cout << buffer << std::endl; // clean up pclose(fp); free(buffer); return (EXIT_SUCCESS); } This code is giving me a "Memory error" with an exit status of '2', so I can see where it's failing, I just don't understand why. I put this together from example code that I found on Ubuntu Forums and C++ Reference, so I'm not married to it. If anyone can suggest a better way to read the results of a system() call, I'm open to new ideas. EDIT to the original: Okay, bufSize is coming up negative, and now I understand why. You can't randomly access a pipe, as I naively tried to do. I can't be the first person to try to do this. Can someone give (or point me to) an example of how to read the results of a system() call into a variable in C++?
Why would std::malloc() fail? The obvious reason is "because std::ftell() returned a negative signed number, which was then treated as a huge unsigned number". According to the documentation, std::ftell() returns -1 on failure. One obvious reason it would fail is that you cannot seek in a pipe or FIFO. There is no escape; you cannot know the length of the command output without reading it, and you can only read it once. You have to read it in chunks, either growing your buffer as needed or parsing on the fly. But, of course, you can simply avoid the whole issue by directly using the system call df probably uses to get its information: statvfs().
309,581
309,589
What is the difference between const_iterator and non-const iterator in the C++ STL?
What is the difference between a const_iterator and an iterator and where would you use one over the other?
const_iterators don't allow you to change the values that they point to, regular iterators do. As with all things in C++, always prefer const, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not const to change the pointed-to value).
309,672
586,954
Can I use boost on uclibc linux?
Does anyone have any experience with running C++ applications that use the boost libraries on uclibc-based systems? Is it even possible? Which C++ standard library would you use? Is uclibc++ usable with boost?
We use Boost together with GCC 2.95.3, libstdc++ and STLport on an ARMv4 platform running uClinux. Some parts of Boost are not compatible with GCC 2.x but the ones that are works well in our particular case. The libraries that we use the most are date_time, bind, function, tuple and thread. Some of the libraries we had issues with were lambda, shared_pointer and format. These issues were most likely caused by our version of GCC since it has problems when you have too many includes or deep levels of template structures. If possible I would recommend you to run the boost test suite with your particular toolchain to ensure compatibility. At the very least you could compile a native toolchain in order to ensure that your library versions are compatible. We have not used uClibc++ because that is not what our toolchain provider recommends so I cannot comment on that particular combination.
310,031
310,053
Open a Specified File in Excel from a GUI - Borland C++
I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints on this, or at least a place to look online, would be greatly appreciated.
Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel. If that isn't the case, and you can assume that Excel is installed, you could instead pass "excel" to ShellExecute() as the application, and the path of the file as the parameter. (Note that I didn't test this, but it worked from the Run dialog, so I think that it should work from ShellExecute() as well).
310,108
310,166
Can I make GCC warn on passing too-wide types to functions?
Following is some obviously-defective code for which I think the compiler should emit a diagnostic. But neither gcc nor g++ does, even with all the warnings options I could think of: -pedantic -Wall -Wextra #include <stdio.h> short f(short x) { return x; } int main() { long x = 0x10000007; /* bigger than short */ printf("%d\n", f(x)); /* hoping for a warning here */ return 0; } Is there a way to make gcc and g++ warn about this? On a side note, do you have another compiler which warns about this by default or in a fairly common extra-warnings configuration? Note: I'm using GCC (both C and C++ compilers) version 4.2.4. Edit: I just found that gcc -Wconversion does the trick, but the same option to g++ doesn't, and I'm really using C++ here, so I need a solution for g++ (and am now wondering why -Wconversion doesn't seem to be it). Edit: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389 suggests that this may be fixed in g++ 4.4...maybe? It's not clear to me yet if it's the same issue and/or if the fix is really coming in that version. Maybe someone with 4.3 or 4.4 can try my test case.
Use -Wconversion -- the problem is an implicit cast (conversion) from long x to short when the function f(short x) is called [not printf], and -Wconversion will say something like "cast from long to short may alter value". .. Edit: just saw your note. -Wconversion results in a warning for me, using g++ 4.3.2 on Linux... (4.3.2-1 on Debian)
310,175
311,698
What is the widget name of the Kde bar used in program like Kate? (image inside)
What is the object name of the Kde bar that provide buttons to hide/unhide widgets? I can't find on kde official API references. It's used in program like Kate, Kdevelop. Here the screenshot of the bar of Kate bottom: http://emilio.plugs.it/bar.png alt text http://emilio.plugs.it/bar.png
Isn't that a KMultiTabBar?
310,192
310,195
Visual Studio C++ project management. How do I handle non-code files in a project?
I have a project in a c++ solution. For that project, I have some config files that I would like to manage from within the project and when I build the project, have those config files added to the executable build path in the proper directory structure. Example: test.exe references config/myconfig.txt Is there a way to setup myconfig.txt and my project so when I build test.exe, I get / as well as //config/config.txt so when I run test, all paths stay in the proper order without me having to go in and manually create those directories. I'm not sure I'm making sense here, but maybe one of you will understand where I'm going.
You could use pre-build events to create the directories and copy the files.
310,333
310,364
tr1::mem_fn and tr1::bind: on const-correctness and overloading
What's wrong with the following snippet ? #include <tr1/functional> #include <functional> #include <iostream> using namespace std::tr1::placeholders; struct abc { typedef void result_type; void hello(int) { std::cout << __PRETTY_FUNCTION__ << std::endl; } void hello(int) const { std::cout << __PRETTY_FUNCTION__ << std::endl; } abc() {} }; int main(int argc, char *argv[]) { const abc x; int a = 1; std::tr1::bind(&abc::hello, x , _1)(a); return 0; } Trying to compile it with g++-4.3, it seems that cv-qualifier overloaded functions confuse both tr1::mem_fn<> and tr1::bind<> and it comes out the following error: no matching function for call to ‘bind(<unresolved overloaded function type>,... Instead the following snippet compiles but seems to break the const-correctness: struct abc { typedef void result_type; void operator()(int) { std::cout << __PRETTY_FUNCTION__ << std::endl; } void operator()(int) const { std::cout << __PRETTY_FUNCTION__ << std::endl; } abc() {} }; ... const abc x; int a = 1; std::tr1::bind( x , _1)(a); Any clue?
The lookup is done at a time when the constness of this is not known. You just have to give it a hint via casting. Try this: typedef void (abc::*fptr)(int) const; // or remove const std::tr1::bind((fptr)&abc::hello, x , _1)(a); You may also notice here that removing the const still works. This is because you should be passing x by pointer (because the first argument to a C++ member function, the implicit this parameter, is always a pointer). Try this instead: typedef void (abc::*fptr)(int) const; // won't compile without const (good!) std::tr1::bind((fptr)&abc::hello, &x , _1)(a); As discovered during within my comments below, if you omit the & as you originally did, you'll be passing x by value, which is usually not what you want (though it makes little practical difference in your particular example). This actually seems like an unfortunate pitfall for bind.
310,358
310,455
Quick file access in a directory with 500,000 files
I have a directory with 500,000 files in it. I would like to access them as quickly as possible. The algorithm requires me to repeatedly open and close them (can't have 500,000 file open simultaneously). How can I do that efficiently? I had originally thought that I could cache the inodes and open the files that way, but *nix doesn't provide a way to open files by inode (security or some such). The other option is to just not worry about it and hope the FS does good job on file look up in a directory. If that is the best option, which FS's would work best. Do certain filename patterns look up faster than others? eg 01234.txt vs foo.txt BTW this is all on Linux.
Assuming your file system is ext3, your directory is indexed with a hashed B-Tree if dir_index is enabled. That's going to give you as much a boost as anything you could code into your app. If the directory is indexed, your file naming scheme shouldn't matter. http://lonesysadmin.net/2007/08/17/use-dir_index-for-your-new-ext3-filesystems/
310,363
310,374
How to add one day to a time obtained from time()
I have a time represented as the number of seconds elapsed since midnight, January 1, 1970, UTC (the results of an earlier call to time()). How do I add one day to this time? Adding 24 * 60 * 60 works in most cases, but fails if the daylight saving time comes on or off in between. In other words, I mostly want to add 24 hours, but sometimes 23 or 25 hours. To illustrate - the program: #include <time.h> #include <iostream> int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { time_t time = base + i * 24 * 60 * 60; std::cout << ctime(&time); } return 0; } Produces: Sat Mar 11 08:00:00 2006 Sun Mar 12 09:00:00 2006 Mon Mar 13 09:00:00 2006 Tue Mar 14 09:00:00 2006 I want the times for March 12, 13, ... to also be 8 AM. The answer provided by FigBug pointed me in the right direction. But I had to use localtime instead of gmtime. int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; std::cout << asctime(tm); } return 0; } Give me: Sat Mar 11 08:00:00 2006 Sat Mar 12 08:00:00 2006 Sat Mar 13 08:00:00 2006 Sat Mar 14 08:00:00 2006 Which is what I want. Using gmtime gives me the times at 14:00:00 However, note that all days are Sat. Also, it goes to March 32, 33, etc. If I throw in the mktime function I am back where I started: #include <time.h> #include <iostream> int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; time_t time = mktime(tm); std::cout << asctime(tm); } return 0; } Gives me: Sat Mar 11 08:00:00 2006 Sun Mar 12 09:00:00 2006 Mon Mar 13 09:00:00 2006 Tue Mar 14 09:00:00 2006 What am I missing??? OK, I have tried out FigBug's latest suggestion that is to use: std::cout << ctime(&time); instead of asctime, but I get the same results. So I guess that my library and/or compiler is messed up. I am using g++ 3.4.4 on cygwin. I copied the files over to Solaris 5.8 and used g++ 3.3 there to compile. I get the correct results there! In fact I get the correct results whether I use ctime or asctime for output: Sat Mar 11 08:00:00 2006 Sun Mar 12 08:00:00 2006 Mon Mar 13 08:00:00 2006 Tue Mar 14 08:00:00 2006 I also get the correct results (with both output functions) on Red Hut Linux with g++ 3.4.6. So I guess that I have come across a Cygwin bug. Thank you for all your help and advice....
use gmtime() to convert the time_t to a struct tm add one to the day (tm_mday) use mktime() to convert the struct tm back to a time_t see time.h for more info Edit: I just tried it, this works: int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; time_t next = mktime(tm); std::cout << ctime(&next); } return 0; }
310,392
310,404
Char ^= 0xB3 equivalent in VBScript
I have the following C++ code: Char ^= 0xB3; Char is a single character in a string. Is there an equivalent in VBScript?
Char = chr(asc(Char) xor &HB3)
310,408
310,499
Deriving an abstract class from concrete class
Let's say we have a concrete class Apple. (Apple objects can be instantiated.) Now, someone comes and derives an abstract class Peach from Apple. It's abstract because it introduces a new pure virtual function. The user of Peach is now forced to derive from it and define this new function. Is this a common pattern? Is this correct to do? Sample: class Apple { public: virtual void MakePie(); // more stuff here }; class Peach : public Apple { public: virtual void MakeDeliciousDesserts() = 0; // more stuff here }; Now let's say we have a concrete class Berry. Someone derives an abstract class Tomato from Berry. It's abstract because it overwrites one of Berry's virtual functions, and makes it pure virtual. The user of Tomato has to re-implement the function previously defined in Berry. Is this a common pattern? Is this correct to do? Sample: class Berry { public: virtual void EatYummyPie(); // more stuff here }; class Tomato : public Berry { public: virtual void EatYummyPie() = 0; // more stuff here }; Note: The names are contrived and do not reflect any actual code (hopefully). No fruits have been harmed in the writing of this question.
Re Peach from Apple: Don't do it if Apple is a value class (i.e. has copy ctor, non-identical instances can be equal, etc). See Meyers More Effective C++ Item 33 for why. Don't do it if Apple has a public nonvirtual destructor, otherwise you invite undefined behaviour when your users delete an Apple through a pointer to Peach. Otherwise, you're probably safe, because you haven't violated Liskov substitutability. A Peach IS-A Apple. If you own the Apple code, prefer to factor out a common abstract base class (Fruit perhaps) and derive Apple and Peach from it. Re Tomato from Berry: Same as above, plus: Avoid, because it's unusual If you must, document what derived classes of Tomato must do in order not to violate Liskov substitutability. The function you are overriding in Berry - let's call it Juice() - imposes certain requirements and makes certain promises. Derived classes' implementations of Juice() must require no more and promise no less. Then a DerivedTomato IS-A Berry and code which only knows about Berry is safe. Possibly, you will meet the last requirement by documenting that DerivedTomatoes must call Berry::Juice(). If so, consider using Template Method instead: class Tomato : public Berry { public: void Juice() { PrepareJuice(); Berry::Juice(); } virtual void PrepareJuice() = 0; }; Now there is an excellent chance that a Tomato IS-A Berry, contrary to botanical expectations. (The exception is if derived classes' implementations of PrepareJuice impose extra preconditions beyond those imposed by Berry::Juice).
310,557
310,566
C++ Nested classes forward declaration error
I am trying to declare and use a class B inside of a class A and define B outside A. I know for a fact that this is possible because Bjarne Stroustrup uses this in his book "The C++ programming language" (page 293,for example the String and Srep classes). So this is my minimal piece of code that causes problems class A{ struct B; // forward declaration B* c; A() { c->i; } }; struct A::B { /* * we define struct B like this becuase it * was first declared in the namespace A */ int i; }; int main() { } This code gives the following compilation errors in g++ : tst.cpp: In constructor ‘A::A()’: tst.cpp:5: error: invalid use of undefined type ‘struct A::B’ tst.cpp:3: error: forward declaration of ‘struct A::B’ I tried to look at the C++ Faq and the closeset I got was here and here but those don't apply to my situation. I also read this from here but it's not solving my problem. Both gcc and MSVC 2005 give compiler errors on this
Define the constructor for A AFTER the definition of struct B.
311,102
324,739
Safely checking the type of a variable
For a system I need to convert a pointer to a long then the long back to the pointer type. As you can guess this is very unsafe. What I wanted to do is use dynamic_cast to do the conversion so if I mixed them I'll get a null pointer. This page says http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm The dynamic_cast operator performs type conversions at run time. The dynamic_cast operator guarantees the conversion of a pointer to a base class to a pointer to a derived class, or the conversion of an lvalue referring to a base class to a reference to a derived class. A program can thereby use a class hierarchy safely. This operator and the typeid operator provide run-time type information (RTTI) support in C++. and I'd like to get an error if it's null so I wrote my own dynamic cast template<class T, class T2> T mydynamic_cast(T2 p) { assert(dynamic_cast<T>(p)); return reinterpret_cast<T>(p); } With MSVC I get the error "error C2681: 'long' : invalid expression type for dynamic_cast". It turns out this will only work with classes which have virtual functions... WTF! I know the point of a dynamic cast was for the up/down casting inheritance problem but I also thought it was to solve the type cast problem dynamically. I know I could use reinterpret_cast but that doesn't guarantee the same type of safety. What should I use to check if my typecast are the same type? I could compare the two typeid but I would have a problem when I want to typecast a derived to its base. So how can I solve this?
I've had to do similar things when loading C++ DLLs in apps written in languages that only support a C interface. Here is a solution that will give you an immediate error if an unexpected object type was passed in. This can make things much easier to diagnose when something goes wrong. The trick is that every class that you pass out as a handle has to inherit from a common base class. #include <stdexcept> #include <typeinfo> #include <string> #include <iostream> using namespace std; // Any class that needs to be passed out as a handle must inherit from this class. // Use virtual inheritance if needed in multiple inheritance situations. class Base { public: virtual ~Base() {} // Ensure a v-table exists for RTTI/dynamic_cast to work }; class ClassA : public Base { }; class ClassB : public Base { }; class ClassC { public: virtual ~ClassC() {} }; // Convert a pointer to a long handle. Always use this function // to pass handles to outside code. It ensures that T does derive // from Base, and that things work properly in a multiple inheritance // situation. template <typename T> long pointer_to_handle_cast(T ptr) { return reinterpret_cast<long>(static_cast<Base*>(ptr)); } // Convert a long handle back to a pointer. This makes sure at // compile time that T does derive from Base. Throws an exception // if handle is NULL, or a pointer to a non-rtti object, or a pointer // to a class not convertable to T. template <typename T> T safe_handle_cast(long handle) { if (handle == NULL) throw invalid_argument(string("Error casting null pointer to ") + (typeid(T).name())); Base *base = static_cast<T>(NULL); // Check at compile time that T converts to a Base * base = reinterpret_cast<Base *>(handle); T result = NULL; try { result = dynamic_cast<T>(base); } catch(__non_rtti_object &) { throw invalid_argument(string("Error casting non-rtti object to ") + (typeid(T).name())); } if (!result) throw invalid_argument(string("Error casting pointer to ") + typeid(*base).name() + " to " + (typeid(T).name())); return result; } int main() { ClassA *a = new ClassA(); ClassB *b = new ClassB(); ClassC *c = new ClassC(); long d = 0; long ahandle = pointer_to_handle_cast(a); long bhandle = pointer_to_handle_cast(b); // long chandle = pointer_to_handle_cast(c); //Won't compile long chandle = reinterpret_cast<long>(c); // long dhandle = pointer_to_handle_cast(&d); Won't compile long dhandle = reinterpret_cast<long>(&d); // send handle to library //... // get handle back try { a = safe_handle_cast<ClassA *>(ahandle); //a = safe_handle_cast<ClassA *>(bhandle); // fails at runtime //a = safe_handle_cast<ClassA *>(chandle); // fails at runtime //a = safe_handle_cast<ClassA *>(dhandle); // fails at runtime //a = safe_handle_cast<ClassA *>(NULL); // fails at runtime //c = safe_handle_cast<ClassC *>(chandle); // Won't compile } catch (invalid_argument &ex) { cout << ex.what() << endl; } return 0; }
311,166
311,252
std::auto_ptr or boost::shared_ptr for pImpl idiom?
When using the pImpl idiom is it preferable to use a boost:shared_ptr instead of a std::auto_ptr? I'm sure I once read that the boost version is more exception friendly? class Foo { public: Foo(); private: struct impl; std::auto_ptr<impl> impl_; }; class Foo { public: Foo(); private: struct impl; boost::shared_ptr<impl> impl_; }; [EDIT] Is it always safe to use std::auto_ptr<> or are there situations when an alternative boost smart pointer is required?
You shouldn't really use std::auto_ptr for this. The destructor won't be visible at the point you declare the std::auto_ptr, so it might not be called properly. This is assuming that you are forward declaring your pImpl class, and creating the instance inside the constructor in another file. If you use boost::scoped_ptr (no need for shared_ptr here, you won't be sharing the pimpl with any other objects, and this is enforced by scoped_ptr being noncopyable), you only need the pimpl destructor visible at the point you call the scoped_ptr constructor. E.g. // in MyClass.h class Pimpl; class MyClass { private: std::auto_ptr<Pimpl> pimpl; public: MyClass(); }; // Body of these functions in MyClass.cpp Here, the compiler will generate the destructor of MyClass. Which must call auto_ptr's destructor. At the point where the auto_ptr destructor is instantiated, Pimpl is an incomplete type. So in to the auto_ptr destructor when it deletes the the Pimpl object, it won't know how to call the Pimpl destructor. boost::scoped_ptr (and shared_ptr) don't have this problem, because when you call the constructor of a scoped_ptr (or the reset method) it also makes a function-pointer-equivalent that it will use instead of calling delete. The key point here is that it instantiates the deallocation function when Pimpl is not an incomplete type. As a side note, shared_ptr allows you to specify a custom deallocation function, so you can use for it for things like GDI handles or whatever else you may want - but that's overkill for your needs here. If you really want to use std::auto_ptr, then you need to take extra care by making sure you define your MyClass destructor in MyClass.cpp when Pimpl is fully defined. // in MyClass.h class Pimpl; class MyClass { private: std::auto_ptr<Pimpl> pimpl; public: MyClass(); ~MyClass(); }; and // in MyClass.cpp #include "Pimpl.h" MyClass::MyClass() : pimpl(new Pimpl(blah)) { } MyClass::~MyClass() { // this needs to be here, even when empty } The compiler will generate the code destruct all of the MyClass members effectively 'in' the empty destructor. So at the point the auto_ptr destructor is instantiated, Pimpl is no longer incomplete and the compiler now knows how to call the destructor. Personally, I don't think it's worth the hassle of making sure everything is correct. There's also the risk that somebody will come along later and tidy up the code by removing the seemingly redundant destructor. So it's just safer all round to go with boost::scoped_ptr for this kind of thing.
311,247
311,556
Changing default behavior in a C++ application with plugins
In short: what is the best way to design and implement a factory+plugin mechanism, so that plugins can replace objects in the main application. We have a code base from which we build our applications. The code base is fine for 70-95% of the applications, meaning that in each new application we need to change 5-30% of the default behavior (add new features, change default logic, add GUI, etc.). The implementation is plugin-based: the code base is built into an EXE and DLLs, and when the main EXE is running we load a DLL which adds the required functionality. Currently each plugin exposes the following function: PluginInterface* PluginInit() { return new MyCustomizedPluginInterface(); } Where PluginInterface is defined as: class PluginInterface { public: virtual SomeClass1* customizedSomeClass1() = 0; virtual SomeClass2* customizedSomeClass2() = 0; }; And SomeClass1/SomeClass2 have some default behavior, but can be overridden and changed by the plugin. The current implementation makes it hard for adding new customized classes. We would like to replace every class in the main application from the plugin, so it makes sense to use object factories. One SDK that I know uses the following technique: PluginInterface* PluginInit(GodObject* godObject) { FactoryForSomeClasses* factoryForSomeClasses = godObject->factoryForSomeClasses(); factoryForSomeClasses->setSomeClass1Creator( MyCustomizedSomeClass1::create); // create is a static creator function. factoryForSomeClasses->setSomeClass2Creator( MyCustomizedSomeClass2::create); } I wonder if there are any alternatives to this approach. How would you recommend designing and implementing a plugin system/factory like I just described?
There was an article a while back in Doctor Dobb's that discussed this exact problem. Here is a link to the article in question. As an aside you may want to stick with a straight C interface for the plugins to your project. That way you can link code written in almost any language into your framework with minimal hassle. While C++ is nice, being able to leverage more than what exists in C++, like the incredible frameworks that exist in Java and Python lands, could prove beneficial in the long run.
311,297
311,606
Fast container for setting bits in a sparse domain, and iterating (C++)?
I need a fast container with only two operations. Inserting keys on from a very sparse domain (all 32bit integers, and approx. 100 are set at a given time), and iterating over the inserted keys. It should deal with a lot of insertions which hit the same entries (like, 500k, but only 100 different ones). Currently, I'm using a std::set (only insert and the iterating interface), which is decent, but still not fast enough. std::unordered_set was twice as slow, same for the Google Hash Maps. I wonder what data structure is optimized for this case?
Depending on the distribution of the input, you might be able to get some improvement without changing the structure. If you tend to get a lot of runs of a single value, then you can probably speed up insertions by keeping a record of the last value you inserted, and don't bother doing the insertion if it matches. It costs an extra comparison per input, but saves a lookup for each element in a run beyond the first. So it could improve things no matter what data structure you're using, depending on the frequency of repeats and the relative cost of comparison vs insertion. If you don't get runs, but you tend to find that values aren't evenly distributed, then a splay tree makes accessing the most commonly-used elements cheaper. It works by creating a deliberately-unbalanced tree with the frequent elements near the top, like a Huffman code.
311,735
311,764
check if X is derived of Y via typeid
i need to convert pointers to long (SendMessage()) and i want to safely check if the variable is correct on the otherside. So i was thinking of doing dynamic_cast but that wont work on classes that are not virtual. Then i thought of doing typeid but that will work until i pass a derived var as its base. Is there any way to check if the pointer is what i am expecting during runtime? Is there a way i can use typeid to see if a pointer is a type derived from a particular base?
If all you have is a long, then there's not really much you can do. There is no general way to determine whether an arbitrary number represents a valid memory address. And even if you know it's a valid memory address, there is no way to determine the type of the thing the pointer points to. If you can't be sure of the real type of the thing before its address was cast to long, then you can't be sure that it's going to be safe to cast the long to whatever type you plan on casting it to. You'll just have to trust that the sender of the message has sent you a valid value. The best you can do is to take some precautions to reduce the consequences to your own program when it receives a bogus value.
311,805
311,974
Access desktop release directory from windows ce device
I am writing a test program to copy some file in Application data folder on device to release directory on desktop. I am not sure how to access release dir on desktop? Is there any shell command to do that? Basically I want to write c++ program that will run on device to accomplish this task.
I found the solution There is API called CoyFile that can copy to release dir. CopyFile(Src file,Dest file,FALSE); Destination file can be given as ce::wstring = L"\release\foo.txt";
311,949
312,042
Unit testing destructors?
Is there any good way to unit test destructors? Like say I have a class like this (contrived) example: class X { private: int *x; public: X() { x = new int; } ~X() { delete x; } int *getX() {return x;} const int *getX() const {return x;} }; Is there any good way to unit test this to make sure x gets deleted without cluttering up my hpp file with #ifdef TESTs or breaking encapsulation? The main problem that I'm seeing is that it's difficult to tell if x really got deleted, especially because the object is out of scope at the time the destructor is called.
There may be something to be said for dependency injection. Instead of creating an object (in this case an int, but in a non-contrived case more likely a user-defined type) in its constructor, the object is passed as a parameter to the constructor. If the object is created later, then a factory is passed to the constructor of X. Then when you're unit testing, you pass in a mock object (or a mock factory which creates mock objects), and the destructor records the fact that it has been called. The test fails if it isn't. Of course you can't mock (or otherwise replace) a builtin type, so in this particular case it's no good, but if you define the object/factory with an interface then you can. Checking for memory leaks in unit tests can often be done at a higher level, as others have said. But that only checks that a destructor was called, it doesn't prove that the right destructor was called. So it wouldn't e.g. catch a missing "virtual" declaration on the destructor of the type of the x member (again, not relevant if it's just an int).
312,077
312,078
Dot product in C++ using generic algorithms
I´m sure there´s a clever one-liner using the C++ stl generic algorithms for implementing the dot product of the elements in any ordered container, such as a vector or list. I just don´t seem to remember it! The fancy implementation would be: template <class containerT> typename containerT::value_type dot_product (const containerT& left, const containerT& right) { assert(left.size()==right.size()); containerT::value_type result = 0; for (containerT::const_iterator l_it = left.begin(), r_it = right.begin(); l_it != left.end(); ++r_it,++l_it) { result += (*l_it) * (*r_it); } return result; } I think that i´m reinventing the wheel and that there´s a more clever way to do this.
See std::inner_product from <numeric>.
312,115
312,402
C++ Linking Errors: Undefined symbols using a templated class
I'm getting some really wierd linking errors from a class I wrote. I am completely unable to find anything that will describe what is happening. Visual Studio (Windows XP) players.obj : error LNK2019: unresolved external symbol "public: __thiscall TreeNode::TreeNode(void)" (??0?$TreeNode@VPlayer@@@@QAE@XZ) referenced in function "public: __thiscall PlayerList::PlayerList(void)" (??0PlayerList@@QAE@XZ) Xcode (OSX 10.5) Undefined symbols: "TreeNode::~TreeNode()", referenced from: PlayerList::~PlayerList()in players.o Header File: generics.h class TreeNode : public BaseNode{ public: const static int MAX_SIZE = -1; //-1 means any size allowed. const static int MIN_SIZE = 0; //getters int size() const; vector<C*> getChildren() const; //setters void setChildren(vector<C*> &list); //Serialization virtual void display(ostream &out) const; virtual void read(istream &in); virtual void write(ostream &out) const; //Overrides so SC acts like an array of sorts. virtual C* get(int id) const; virtual int get(C *child) const; virtual bool has(C *child) const; virtual C* pop(int id); virtual void push(C *child); virtual TreeNode& operator<< (C *child); //append virtual void remove(int id); //Clears memory virtual void remove(C *child); //Clears memory //Initalizers TreeNode(); TreeNode(istream &in); TreeNode(long id, istream &in); TreeNode(BaseNode* parent, istream &in); TreeNode(long id, BaseNode* parent); TreeNode(long id, BaseNode* parent, istream &in); ~TreeNode(); string __name__() const{ return "TreeNode"; } protected: void clearChildren(); void initalizeChildren(); vector<C*> _children; }; Code from a subclass of TreeNode PlayerList::PlayerList() : TreeNode<Player>(){} PlayerList::PlayerList(istream &in) : TreeNode<Player>(in){} PlayerList::~PlayerList(){}
When you define your template in a .cpp file, you have to explicitly instantiate it with all the types / template parameters known the template will be used beforehand like this (put it in the .cpp file): template class TreeNode<Player>; If you don't know with which template parameters the template will be used, you have to put all the definitions into the header. like template<typename T> class TreeNode { public: TreeNode() /* now, also put the code into here: */ { doSomething(); } }; The reason is that when you are going to use the template from somewhere, the compiler has to be able to generate the code for that specific instantiation of the template. But if you place the code into a .cpp file and compile it, there is no way for the compiler to get its hands on the code to generate the instantiation (except when using the infamous export keyword, which is only supported by very few compilers). This is also an entry in my C++ Pitfalls answer: What C++ pitfalls should I avoid?
312,116
312,125
C++ array size dependent on function parameter causes compile errors
I have a simple function in which an array is declared with size depending on the parameter which is int. void f(int n){ char a[n]; }; int main() { return 0; } This piece of code compiles fine on GNU C++, but not on MSVC 2005. I get the following compilation errors: .\main.cpp(4) : error C2057: expected constant expression .\main.cpp(4) : error C2466: cannot allocate an array of constant size 0 .\main.cpp(4) : error C2133: 'a' : unknown size What can I do to correct this? (I'm interested in making this work with MSVC,without using new/delete)
What you have found it one of the Gnu compiler's extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression. There was a feature added to C in the 1999 update to that language called variable length arrays, where this is legal. If you can find a C compiler that supports C99, which is not easy. But this feature is not part of standard C++, not is it going to be added in the next update to the C++ standard. There are two solutions in C++. The first is to use a std::vector, the second is just to use operator new []: char *a = new char [n]; While I was writing my answer, another one posted a suggestion to use _alloca. I would strongly recommend against that. You would just be exchanging one non-standard, non-portable method for another one just as compiler-specific.
312,286
312,288
Returning a pointer from a class
For my programming class I have to write a linked list class. One of the functions we have to include is next(). This function would return the memory address of the next element in the list. #include <iostream> using namespace std; class Set { private: int num; Set *nextval; bool empty; public: Set(); <some return type> next(); }; <some return type> Set::next() { Set *current; current = this; return current->next; } int main() { Set a, *b, *c; for (int i=50;i>=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question // Test the next_element() iterator b = a.next(); c = b->next(); cout << "Third element of b = " << c->value() << endl; return 0; } As you can see, I need to set the pointer *b and *c to the memory address that holds the next element in the list. My question is what kind of return type would I use? I've tried putting Set and Set* in place of but get compiler errors. Any help is greatly appreciated.
Set* is correct. You are suffering from a rather silly bug in this function: Set* Set::next() { Set *current; current = this; return current->next; } The last line should be return current->nextval. Otherwise you are trying to return a pointer to the next function... probably not what you want, ever. :-)
312,312
312,352
What are some reasons a Release build would run differently than a Debug build
I have a Visual Studio 2005 C++ program that runs differently in Release mode than it does in Debug mode. In release mode, there's an (apparent) intermittent crash occurring. In debug mode, it doesn't crash. What are some reasons that a Release build would work differently than a Debug build? It's also worth mentioning my program is fairly complex and uses several 3rd party libraries for XML processing, message brokering, etc... Thanks in advance!
Surviving the Release Version gives a good overview. Things I have encountered - most are already mentioned Variable initialization by far the most common. In Visual Studio, debug builds explicitly initialize allocated memory to given values, see e.g. Memory Values here. These values are usually easy to spot, cause an out of bounds error when used as an index or an access violation when used as a pointer. An uninitialized boolean is true, however, and may cause uninitialized memory bugs going undetected for years. In Release builds where memory isn't explicitely initialized it just keeps the contents that it had before. This leads to "funny values" and "random" crashes, but as often to deterministic crashes that require an apparently unrelated command to be executed before the command that actually crashes. This is caused by the first command "setting up" the memory location with specific values, and when the memory locations are recycled the second command sees them as initializations. That's more common with uninitialized stack variables than heap, but the latter has happened to me, too. Raw memory initialization can also be different in a release build whether you start from visual studio (debugger attached) vs. starting from explorer. That makes the "nicest" kind of release build bugs that never appear under the debugger. Valid Optimizations come second in my exeprience. The C++ standard allows lots of optimizations to take place which may be surprising but are entirely valid e.g. when two pointers alias the same memory location, order of initialization is not considered, or multiple threads modify the same memory locations, and you expect a certain order in which thread B sees the changes made by thread A. Often, the compiler is blamed for these. Not so fast, young yedi! - see below Timing Release builds don't just "run faster", for a variety of reasons (optimizations, logging functions providing a thread sync point, debug code like asserts not executed etc.) also the relative timing between operations change dramatically. Most common problem uncovered by that is race conditions, but also deadlocks and simple "different order" execution of message/timer/event-based code. Even though they are timing problems, they can be surprisingly stable across builds and platforms, with reproductions that "work always, except on PC 23". Guard Bytes. Debug builds often put (more) guard bytes around selected instances and allocations, to protect against index overflows and sometimes underflows. In the rare cases where the code relies on offsets or sizes, e.g. serializing raw structures, they are different. Other code differences Some instructions - e.g asserts - evaluate to nothing in release builds. Sometimes they have different side effects. This is prevalent with macro trickery, as in the classic (warning: multiple errors) #ifdef DEBUG #define Log(x) cout << #x << x << "\n"; #else #define Log(x) #endif if (foo) Log(x) if (bar) Run(); Which, in a release build, evaluates to if (foo && bar) This type of error is very very rare with normal C/C++ code, and macros that are correctly written. Compiler Bugs This really never ever happens. Well - it does, but you are for the most part of your career better off assuming it does not. In a decade of working with VC6, I found one where I am still convinced this is an unfixed compiler bug, compared to dozens of patterns (maybe even hundreds of instances) with insufficient understanding of the scripture (a.k.a. the standard).
312,570
312,613
What are some of the drawbacks to using C-style strings?
I know that buffer overruns are one potential hazard to using C-style strings (char arrays). If I know my data will fit in my buffer, is it okay to use them anyway? Are there other drawbacks inherent to C-style strings that I need to be aware of? EDIT: Here's an example close to what I'm working on: char buffer[1024]; char * line = NULL; while ((line = fgets(fp)) != NULL) { // this won't compile, but that's not the issue // parse one line of command output here. } This code is taking data from a FILE pointer that was created using a popen("df") command. I'm trying to run Linux commands and parse their output to get information about the operating system. Is there anything wrong (or dangerous) with setting the buffer to some arbitrary size this way?
C strings lack the following aspects of their C++ counterparts: Automatic memory management: you have to allocate and free their memory manually. Extra capacity for concatenation efficiency: C++ strings often have a capacity greater than their size. This allows increasing the size without many reallocations. No embedded NULs: by definition a NUL character ends a C string; C++ string keep an internal size counter so they don't need a special value to mark their end. Sensible comparison and assignment operators: even though comparison of C string pointers is permitted, it's almost always not what was intended. Similarly, assigning C string pointers (or passing them to functions) creates ownership ambiguities.
312,749
312,766
Providing an iterator for the first element of a container of pairs
I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner_product, but consider it as a generic problem). The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but on the first element of each pair? I know i can do it manually, providing a hand-made function object that will be a wrapper around the standard container iterator, deferencing it to the first member of the pair intend of the pair itself,but I think there is also a clever one-liner to do it for me. What would it be?
I've looked around and found boost::transform_iterator. I've come up with this code. Surprising how well it works: #include <map> #include <algorithm> #include <iostream> #include <string> #include <iterator> #include <boost/iterator/transform_iterator.hpp> #include <boost/bind.hpp> #include <boost/function.hpp> int main() { typedef std::map<std::string, int>::value_type value_type; std::map<std::string, int> a; a["one"] = 1; a["two"] = 2; // returns the second element boost::function<int(value_type&)> f = boost::bind(&value_type::second, _1); std::copy(boost::make_transform_iterator(a.begin(), f), boost::make_transform_iterator(a.end(), f), std::ostream_iterator<int>(std::cout, " ")); } It's printing "1 2 " to the standard output.
312,895
312,908
What are signals and slots?
Can someone explain in simple terms the "signals and slots" pattern?
Signals and slots are a way of decoupling a sender (the signal) and zero or more receivers (the slots). Let's say you a system which has events that you want to make available to any other part of the system interested in those events. Rather than hard-wiring the code that generates event to the code that wants to know about those events, you would use a signals and slots pattern. When the sender signals an event (usually by calling the function associated with that event/signal) all the receivers for that event are automatically called. This allows you to connect and disconnect receivers as necessary during the lifetime of the program. Since this question was tagged C++, here is a link to the Boost.Signals library which has a much more thorough explanation.
312,957
312,959
How would I use the >> and << operators for binary data in C++?
Is there a way to use these operators to input and output binary data? The reason I want to do this is that it makes the code readable. Ex: infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;
Indeed that can be done, if the library or your code provides the overloads for operator<< and operator>> for it to work. Simple example on how one could do it: class transformer { public: virtual std::iostream& transform(std::iostream&) = 0; }; class noise : public transformer { public: virtual std::iostream& transform(std::iostream&) { /* extract, change and put into again */ } }; class echo : public transformer { public: virtual std::iostream& transform(std::iostream&) { /* extract, change and put into again */ } }; std::iostream& operator>>(std::iostream& io, transformer& ts) { return ts.transform(io); } int main() { std::stringstream data; std::ifstream file("sound.wav"); noise n; echo e; data << file.rdbuf(); data >> n >> e; /* pipelined data now ready to be played back */ } The problem with using a pure std::istream is that you would read, but then you wouldn't have a way to put the transformed data back for the next step in the pipeline. Thus i'm using std::iostream here. This approach doesn't seem to be efficient, as every operator>> call would extract the whole data, and put into again. To have a more performant way to stream this would be to create an expression template. This means, while operator>> is called, you don't do the transforming yet, but you return expression types that will record the chain of operations within its type: typedef transform< echo< noise< istream > > > pipeline; std::ifstream file("file.wav"); pipeline pipe(file); int byte = pipe.get(); would be an example of such a type. The pipelines' structure is decoded into the type itself. Therefore, no virtual functions are needed anymore in the pipeline. It's not constructed on-demand, but using typedef here, to show the principle. Programming such a system is not easy. So you probably should look into existing systems, like Boost.Iostreams (see below). To give you an idea how it would look like, here is an example i just coded up for you :) : #include <iostream> template<typename T> struct transformer { int get() { return static_cast<T*>(this)->read(); } }; struct echot { template<typename Chain> struct chain : transformer< chain<Chain> > { Chain c; int read() { return c.get() + 1; } chain(Chain const& c):c(c) { } }; } echo; struct noiset { template<typename Chain> struct chain : transformer< chain<Chain> > { Chain c; int read() { return c.get() * 2; } chain(Chain c):c(c) { } }; } noise; template<typename T> typename T::template chain<std::istream&> operator>>(std::istream& is, T) { return typename T::template chain<std::istream&>(is); } template<typename T, typename U> typename U::template chain<T> operator>>(T t, U u) { return typename U::template chain<T>(t); } int main() { std::cout << (std::cin >> echo >> noise).get() << std::endl; } Entering 0 yields the ASCII code 48 here, which is added 1, and multiplied by 2, yielding a value of 98, which is also finally output. I think you agree this is not some code a starter would want to write. So maybe look into boost. Boost has an sophisticated iostreams library, which can do many things. I'm sure you would find something fitting to this. Boost.Iostreams
313,141
313,144
static_cast confusion caused by inconsistencies
Why whenever I compile and run the following code in Visual Studio 2008: double value1 = 10.5; double value2 = 15.5; int whole_number = value1 + value2; Console::WriteLine(whole_number); I get an incorrect value of 26 while the answer is 25. However when I use static casts on the doubles, I get the right answer which is 25. How can the wrong output be explained?
It's absolutely right. double value1 = 10.5; double value2 = 15.5; int whole_number = value1 + value2; // int whole_number = 26.0; Console::WriteLine(whole_number); What would you expect instead? The compiler first evaluates the right side, and then implicitly converts to the int. Thus, 26.0 becomes 26 When you cast before you add, then you are going to add 10 and 15, which results in 25 :)
313,432
313,444
C++ extend a vector with another vector
I'm a C/Python programmer in C++ land working with the STL for the first time. In Python, extending a list with another list uses the .extend method: >>> v = [1, 2, 3] >>> v_prime = [4, 5, 6] >>> v.extend(v_prime) >>> print(v) [1, 2, 3, 4, 5, 6] I currently use this algorithmic approach to extend vectors in C++: v.resize(v.size() + v_prime.size()); copy(v_prime.begin(), v_prime.end(), v.rbegin()); Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?
From here // reserve() is optional - just to improve performance v.reserve(v.size() + distance(v_prime.begin(),v_prime.end())); v.insert(v.end(),v_prime.begin(),v_prime.end());
313,446
313,488
Can anyone quantify performance differences between C++ and Java?
Java was initially slow before the JIT but today performance is pretty close to C++. I want to know if someone has done measurable performance comparisons between the two languages? Where does Java fall short when compared to C++? Java provides many productivity gains to developers so they can write applications much quicker because of garbage college, lack of pointers, etc. Applications such as Firefox, Webkit and Open Office, for example, could be developed much more quickly and reliably if written in 100% Java, perhaps by a factor of 2, but developers still choose C/C++ for performance reasons. Can someone demonstrate where Java cannot be made to perform as well as C++ for applications like the ones that I mentioned. Let me just add that much application work is still being done in C++ for a reason. This is meant to be more than a subjective questions. Languages with higher levels of abstraction frequently pay a performance penalty. We would all be programming in higher level languages if this penalty did not exist. Where does still Java pay in comparison to C++? Be specific.
JIT compilers can be faster for many individual code constructs because they can take advantage of runtime profiling of code. For example, VonC in his answer to this question mentions heap allocation for all objects. This is not actually true: the JIT can allocate objects on the stack if it can prove by escape analysis that references to the object will not outlive the stack frame. In this way, the compiler can get the performance benefit of stack allocation while the programmer can rest assured of the safety of assumed GC heap allocation. Similarly, Uri mentions virtual functions (called virtual methods in most non-C++ languages). This is another case that JIT compilers have an advantage that is almost never available to ahead-of-time (AOT) compilers: the JIT can insert an inlined cheap type check (a dereferenced-word comparison) and actually inline a virtual method call if that particular call site happens to be monomorphic (i.e. the actual type is always the same in practice). It turns out that up to 95% of all virtual method calls are monomorphic in practice, so this can be quite a big win - and it's a win that is hard for AOT compilers to take advantage of, since runtime code loading may change runtime characteristics dynamically.
313,712
313,717
What is the best method to ping in c++ under linux?
I have to call ping from c++ code.I'd like to easily read the output for further utilizations. I have come up with two solutions: use a fork and a pipe, redirect ping output to the pipe and then parse it find a library suited for the purpose to use a ping(ip_addresss) function directly I'd like the latter but i didn't find anything that was clearly a standard solution. How would you do it ?
I would go with your first option. Linux is built around the concept of having small, specialized apps which do one thing really well, communicating with pipes. Your app shouldn't include a library to implement ping, since there is already a built-in command to do it, and it works very well!
313,753
313,776
Char array to a class
I have a incoming stream of bytes (unsigned char) from either a file or network. I need this data placed in a class, and is looking for a NET-way of doing this. I bet some does this all the time, so I guess there is a better method to do this than using BitConverter. I realize I supplied too litle information. Let me try with an example class: class data { void doSmething(); int var1; float var2; } Then I want to transfer the data (var1 and var2) contained in this class over f.ex. a network socket and receive the data on the other end
As Jon mentioned, it's not clear, what you need. Maybe you are talking about maybe it is Binary serialization what you are looking for?
313,778
313,787
generate dependencies for a makefile for a project in C/C++
I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?
GNU make's documentation provides a good solution. Absolutely. g++ -MM <your file> will generate a GMake compatible list of dependencies. I use something like this: # Add .d to Make's recognized suffixes. SUFFIXES += .d #We don't need to clean up when we're making these targets NODEPS:=clean tags svn #Find all the C++ files in the src/ directory SOURCES:=$(shell find src/ -name "*.cpp") #These are the dependency files, which make will clean up after it creates them DEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES)) #Don't create dependencies when we're cleaning, for instance ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS)))) #Chances are, these files don't exist. GMake will create them and #clean up automatically afterwards -include $(DEPFILES) endif #This is the rule for creating the dependency files src/%.d: src/%.cpp $(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%.cpp,obj/%.o,$<)' $< -MF $@ #This rule does the compilation obj/%.o: src/%.cpp src/%.d src/%.h @$(MKDIR) $(dir $@) $(CXX) $(CXXFLAGS) -o $@ -c $< Note: $(CXX)/gcc command must be preceded with a hard tab What this will do is automatically generate the dependencies for each file that has changed, and compile them according to whatever rule you have in place. This allows me to just dump new files into the src/ directory, and have them compiled automatically, dependencies and all.
313,882
313,883
Can you invoke an instantiated object's class constructor explicity in C++?
After creating a instance of a class, can we invoke the constructor explicitly? For example class A{ A(int a) { } } A instance; instance.A(2); Can we do this?
You can use placement new, which permits new (&instance) A(2); However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do A instance(2); Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.
313,970
313,990
How to convert an instance of std::string to lower case
I want to convert a std::string to lowercase. I am aware of the function tolower(). However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a std::string would require iterating over each character. Is there an alternative which works 100% of the time?
Adapted from Not So Frequently Asked Questions: #include <algorithm> #include <cctype> #include <string> std::string data = "Abc"; std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return std::tolower(c); }); You're really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise. If you really hate tolower(), here's a specialized ASCII-only alternative that I don't recommend you use: char asciitolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } std::transform(data.begin(), data.end(), data.begin(), asciitolower); Be aware that tolower() can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.
314,012
314,018
Returning an Iterator
I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong? Function: std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField ) { ... return it; ... } Error: error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'
Your search function is returning a const_iterator. You should either return the same type, i.e. std::vector< CClass >::const_iterator, or cast it to a std::vector< CClass >::iterator if you intend the caller to be able to modify the found item through the iterator. EDIT: after seeing your update, it seems the problem is your iterator (it) has a different type than your function return. They should be the same. std::vector< CClass >::iterator it;
314,152
314,180
How to declare/define a class with template template parameters without using an extra template parameter
Consider the following use of template template parameters... #include <iostream> template <typename X> class A { X _t; public: A(X t) :_t(t) { } X GetValue() { return _t; } }; template <typename T, template <typename T> class C > class B { C<T> _c; public: B(T t) :_c(t) { } T GetValue() { return _c.GetValue(); } }; using namespace std; int main() { B<int, A> b(10); cout<<b.GetValue(); return 0; } Is there a way by which the template parameter T can be removed? For example is there a way to make the following work? //Does not compile template <template <typename T> class C > class B { C _c; public: B(T t) :_c(t) { } T GetValue() { return _c.GetValue(); } }; int main() { B< A<int> > b(10); cout<<b.GetValue(); return 0; }
I assume you're after X, as well as A, in your code. The usual pattern is to have template<typename C> struct B { C c; }; and then, inside classes eligible for substitution: template<typename X> class A { typedef X type_name; X t; }; Then you can access the template parameter using C::type_name.
314,176
314,354
Image processing: smart solution for converting superixel (128x128 pixel) coordinates needed
A cancer CT picture is stored inside a unsigned short array (1-dimensional). I have the location information of the cancer region inside the picture, but the coordinates (x,y) are in superpixel (128x128 unsigned short). My task is to highlight this region. I already solved this one by converting superpixel coordinates into a offset a can use for the unsigned short array. It works fine but i wonder if there is a smarter way to solve this problem, since my solution needs 3 nested for-loops. Is it possible to access the ushort array "superpixelwise", so i can navigate the ushort array in superpixels. I know this does not work. To give you an idea what I was thinking of: typedef struct { unsigned short[128x128] } spix; spix *spixptr; unsigned short * bufptr = img->getBuf(); spixptr = bufptr; Update 1: Yep its vague, let me try again with a picture: [0][1][2] ... [127]| ... [x] | [1] | | [2] | | . | | . | <-- this is a superpixel . | | [127] | | -------------------- | . | . | . | [y] |<--whole picture stored in a ushort* buf = new ushort[x*y] ------------------------------ I like to access the 128x128 ushorts at once with a pointer, so I can memcpy data into the 128x128 field. Update 2: The bitblit transfer hint helped a lot.
From what I understand you have: A large image that is a CT scan A rectangular area within that image that is a cancer Then it gets a bit harder to understand. I believe you want to create some sort of class so that you can effectively access 128x128 blocks of the image as if they were a single pixel. So if the image was 1024x1024 pixels you'd want to be able to access it as a 8x8 grid of 128x128 pixel blocks. Now if this is the case what you need is to create a class that represents one of these 128x128 blocks. This class should reference the image, so that you don't copy the image data, and should contain all of the operations that you'd want to do on that "superpixel". However if all you want to do is to be able to extract out a particular 128x128 block from the larger image then what you need is the bit blit algorithm. The bit block transfer (usually called just blit) will allow you to copy the selected bit of data from the larger image to a smaller one. The algorithm can also be adapted to do almost anything you want to a particular area in the larger image. If a blit is all you need then every relatively modern graphics API should have blit function(s).
314,492
314,527
Is there an easy way to sort an array of char*'s ? C++
I've got an array of char* in a file. The company I work for stores data in flat files.. Sometimes the data is sorted, but sometimes it's not. I'd like to sort the data in the files. Now I could write the code to do this, from scratch. Is there an easier way? Of course an in-place sort would be the best option. I'm working on large files and have little RAM. But I'll consider all options. All strings are the same length. This is some sample data: the data is of fixed length the Data is of fixed length thIS data is of fixed lengt This would represent three records of length 28. The app knows the length. Each record ends with CRLF (\r\n), though it shouldn't matter for this sort.
template<size_t length> int less(const char* left, const char* right) { return memcmp(left, right, length) < 0; } std::sort(array, array + array_length, less<buffer_length>);
314,531
314,894
Windows GDI: horizontal/vertical DPI
When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical? For example: HDC dc = ::GetDC(NULL); const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX); const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY); assert(xDPI == yDPI); ::ReleaseDC(NULL, dc); Are these values ever different?
It's possible for it to be different, but that generally only applies to printers. It can be safely assumed that the screen will always have identical horizontal and vertical DPIs.
314,553
314,601
How to use makefiles in Visual Studio?
I heard a lot about makefiles and how they simplify the compilation process. I'm using VS2008. Can somebody please suggest some online references or books where I can find out more about how to deal with them?
A UNIX guy probably told you that. :) You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.
314,584
314,613
Do you declare your module specific functions as static?
I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module. What are your thoughts on this?
If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This only really applies to c because as others have noted, c++ has namespaces to address this issue.
314,931
314,961
glibc's '-lmcheck' option and multithreading
We've been trying to hunt down some heap corruption issues in our multi-threaded C++ apps. As one technique, we tried add -lmcheck to the libraries line of the application. This is causing the app to crash out with apparent heap corruption in relatively short order. Our app does use both malloc/free and new/delete (as appropriate). One of our team wondered if -lmcheck was in fact thread safe, and put a mutex around all malloc/free calls. The crashes went away. Does anyone know if -lmcheck is supposed to support multi-threading? I wonder if we just mis-understand the tool we're trying to use and thereby causing ourselves unneeded worry.
No, mcheck is not thread-safe and should not be used with multi-threaded applications. Doing so can introduce additional problems since there is no synchronization between the threads. Here is the response from Ulrich Drepper (glibc maintainer) on the subject a few months ago: mcheck does not work for multi-threaded code. It cannot possibly do. There is no way to fix this with the technology underlying mcheck.
314,983
315,022
#include header guard format?
I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use? e.g. assuming a header called foo.hpp: #ifndef __FOO_HPP__ ... #ifndef INCLUDED_FOO_HPP ... #ifndef SOME_OTHER_FORMAT I'm sold on the idea of upper-case #defines but cannot settle on a format for these guards.
I always included the namespace or relative path in the include guard, because only the header name alone has proven to be dangerous. For example, you have some large project with the two files somewhere in your code /myproject/module1/misc.h /myproject/module2/misc.h So if you use a consistent naming schema for your include guards you might end up with having _MISC_HPP__ defined in both files (very funny to find such errors). So I settled with MYPROJECT_MODULE1_MISC_H_ MYPROJECT_MODULE2_MISC_H_ These names are rather long, but compared with the pain of double definitions it is worth it. Another option, if you don't need compiler/platform independence you might look for some #pragma once stuff.
315,051
315,064
using a class defined in a c++ dll in c# code
I have a dll that was written in c++, I need to use this dll in my c# code. After searching I found that using P/Invoke would give me access to the function I need, but these functions are defined with in a class and use non-static private member variables. So I need to be able to create an instance of this class to properly use the functions. How can I gain access to this class so that I can create an instance? I have been unable to find a way to do this. I guess I should note that the c++ dll is not my code.
There is no way to directly use a C++ class in C# code. You can use PInvoke in an indirect fashion to access your type. The basic pattern is that for every member function in class Foo, create an associated non-member function which calls into the member function. class Foo { public: int Bar(); }; extern "C" Foo* Foo_Create() { return new Foo(); } extern "C" int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); } extern "C" void Foo_Delete(Foo* pFoo) { delete pFoo; } Now it's a matter of PInvoking these methods into your C# code [DllImport("Foo.dll")] public static extern IntPtr Foo_Create(); [DllImport("Foo.dll")] public static extern int Foo_Bar(IntPtr value); [DllImport("Foo.dll")] public static extern void Foo_Delete(IntPtr value); The downside is you'll have an awkward IntPtr to pass around but it's a somewhat simple matter to create a C# wrapper class around this pointer to create a more usable model. Even if you don't own this code, you can create another DLL which wraps the original DLL and provides a small PInvoke layer.
315,111
315,121
Cross-platform (linux/Win32) nonblocking C++ IO on stdin/stdout/stderr
I'm trying to find the best solution for nonblocking IO via stdin/stdout with the following characteristics: As long as there is enough data, read in n-sized chunks. If there's not enough data, read in a partial chunk. If there is no data available, block until there is some (even though it may be smaller than n). The goal is to allow efficient transfer for large datasets while processing 'control' codes immediately (instead of having them linger in some partially-filled buffer somewhere). I know I can achieve this by using threads and a istream::get() loop, or by writing a bunch of platform-specific code (since you can't select() on file handles in windows)... ((There is also istream::readsome() which seems promising, but the only results I can find on google were of people saying it doesn't actually work well.)) Since I haven't done much coding w/ these APIs, perhaps there is a better way.
Maybe boost::asio can be of use for you?
315,218
315,278
C++ templates and inheritance
My C++ framework has Buttons. A Button derives from Control. So a function accepting a Control can take a Button as its argument. So far so good. I also have List<T>. However, List<Button> doesn't derive from List<Control>, which means a function accepting a list of Controls can't take a list of Buttons as its argument. This is unfortunate. Maybe this is a stupid question, but I don't see how can I solve this :( List<Button> should derive from List<Control>, but I don't see a way to make this happen "automatically".
I hate to tell you but if you're using a list of instances to Control instead of pointers to Control, your buttons will be garbage anyway (Google "object slicing"). If they're lists of pointers, then either make the list<button*> into list<control*> as others have suggested, or do a copy to a new list<control*> from the list<button*> and pass that into the function instead. Or rewrite the function as a template. So if you previously had a function called doSomething that took a list of controls as an argument, you'd rewrite it as: template <class TControl> void doSomething( const std::list<TControl*>& myControls ) { ... whatever the function is currently doing ... } void doSomethingElse() { std::list<Button*> buttons; std::list<Control*> controls; doSomething( buttons ); doSomething( controls ); }
315,261
4,498,486
Using QMDIArea with Qt 4.4.
I'm using the QMdiArea in Qt 4.4. If a new project is created, I add a number of sub windows to a QMdiArea. I'd like to disallow the user to close a sub window during runtime. The sub windows should only be closed if the whole application is closed or if a new project is created. How can I do this?
You need to define your own subWindow. create a subclass of QMdiSubWindow and override the closeEvent(QCloseEvent *closeEvent). you can control it by argument. for example: void ChildWindow::closeEvent(QCloseEvent *closeEvent) { if(/*condition C*/) closeEvent->accept(); else closeEvent->ignore(); // you can do something else, like // writing a string in status bar ... } then subclass the QMdiArea and override QMdiArea::closeAllSubWindows () like this: class MainWindowArea : public QMdiArea { Q_OBJECT public: explicit MainWindowArea(QWidget *parent = 0); signals: void closeAllSubWindows(); public slots: }; // Implementation: MainWindowArea::closeAllSubWindows() { // set close condition (new project is creating, C = true) foreach(QMdiSubWindow* sub,this->subWindowList()) { (qobject_cast<ChildWindow*>(sub))->close(); } } you may also need to override close slot of your mdi area.
315,285
315,392
Can I use two incompatible versions of the same DLL in the same process?
I'm using two commercial libraries that are produced by the same vendor, called VendorLibA and VendorLibB. The libraries are distributed as many DLLs that depend on the compiler version (e.g. VC7, VC8). Both libraries depend on a another library, produced by this vendor, called VendorLibUtils and contained in one DLL. The problem: VendorLibA uses a different version of VendorLibUtils than VendorLibB. The two versions are not binary compatible, and even if they were it would be a bad idea to use the wrong version. Is there any way I could use the two libraries under the same process? Note: LoadLibrary can't solve this since my process is not that one that's importing VendorLibUtils. EDIT: Forgot to mention the obvious, I don't have to source code for any of the commercial libraries and probably I will never have (sigh). EDIT: The alternative btw, is to do this: How to combine GUI applications in Windows
As you are not using VendorLibUtils directly, I assume you can't use LoadLibrary etc. If the VendorLibUtils DLLs only have exports by ordinal, you could probably rename one of the the libraries and patch the corresponding VendorLibX to use a different filename for its imports. If the VendorLibUtils DLLs have one or more exported symbols with the same names, you might need to patch the imports and export tables too, but let's hope not! :-)
315,378
315,399
C++ performance tips and rules of thumb anyone?
When coding, what is a good rule of thumb to keep in mind with respect to performance? There are endless ways to optimize for a specific platform and compiler, but I'm looking for answers that apply equally well (or almost) across compilers and platforms.
A famous quote come to mind: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.) But maybe you should not pass large data structures by value anyway... :-) Edit: And maybe also avoid O(N^2) or more complex algorithms...
315,393
320,769
I can't connect KAction to slot on KMainWindow
I have a KMainWindow: //file.h class MainWindow: public KMainWindow { public: MainWindow(QWidget *parent = 0); ... ... ... private slots: void removeClick(); //file.cpp MainWindow::MainWindow(QWidget *parent) : KMainWindow(parent) {} void MainWindow::removeClick() { std::cout << "Remove" << std::endl; } I can compile it correctly, but when I execute the I get the message Object::connect: No such slot KMainWindow::removeClick() Can anybody help me?
You forgot the Q_OBJECT macro. class MainWindow: public KMainWindow { Q_OBJECT public: // [snip] }
315,437
3,131,331
Detect file handle leaks with Win32 C++
Is there some way to detect file handle leaks at program termination? In particular I would like to make sure that all of my handles that get created are being freed in code. For example, I may have a CreateFile() somewhere, and at program termination I want to detect and ensure that all of them are closed.
I have used !htrace command of windbg. !htrace -enable !htrace -snapshot !htrace -diff Allow you to compare the handle situation of two execution point and help you the locate the point where the leaked handle have been allocated. It worked well for me.
315,743
617,362
Detecting loss of connection to fix gateway? (QuickFix)
I'm trying to find a good way to detect a loss of connection. My adapter is implemented as a Fix::Application based on one of the examples. It uses a socket initiator to connect to the fix gateway. When I unplug the internet it takes about 30 seconds for the Fix::Application's onLogout method to be fired. It seems like some underlying class would be aware that there is a problem with the socket much earlier. Is there a quick way took hook into this?
The best way to solve this would probably be to decrease your Heartbeat Interval so you know sooner. I don't know of any messages that fire for a loss of TCP connection, but I don't think QuickFix is listening for OS events either. Although, it would likely flow through the fromAdmin event if there were such a message. Did you post your question to the QuickFix DL?
315,987
316,038
In C++, what do you do nearly all the time?
There are a few things that I almost always do when I put a class together in C++. 1) Virtual Destructor 2) Copy constructor and assignment operator (I either implement them in terms of a private function called Copy(), or declare them private and thus explicitly disallow the compiler to auto generate them). What things do you find are almost always useful?
I find turning on the gcc flags -Wall, -Werror, and (this is the fun one) -Weffc++ help catch a lot of potential problems. From the gcc man page: -Weffc++ (C++ only) Warn about violations of the following style guidelines from Scott Meyers’ Effective C++ book: · Item 11: Define a copy constructor and an assignment operator for classes with dynamically allocated memory. · Item 12: Prefer initialization to assignment in constructors. · Item 14: Make destructors virtual in base classes. · Item 15: Have "operator=" return a reference to *this. · Item 23: Don’t try to return a reference when you must return an object. and about violations of the following style guidelines from Scott Meyers’ More Effective C++ book: · Item 6: Distinguish between prefix and postfix forms of incre- ment and decrement operators. · Item 7: Never overload "&&", "││", or ",". If you use this option, you should be aware that the standard library headers do not obey all of these guidelines; you can use grep -v to filter out those warnings.
316,181
316,202
Why does the compiler choose bool over string for implicit typecast of L""?
Having recently introduced an overload of a method the application started to fail. Finally tracking it down, the new method is being called where I did not expect it to be. We had setValue( const std::wstring& name, const std::wstring& value ); std::wstring avalue( func() ); setValue( L"string", avalue ); std::wstring bvalue( func2() ? L"true", L"false" ); setValue( L"bool", bvalue ); setValue( L"empty", L"" ); It was changed so that when a bool value is stored we use the same strings (internal data storage of strings) setValue( const std::wstring& name, const std::wstring& value ); setValue( const std::wstring& name, const bool& value ); std::wstring avalue( func() ); setValue( L"string", avalue ); setValue( L"bool", func2() ); setValue( L"empty", L"" ); << --- this FAILS!?! The problem with L"" is that it is implicitly casting and previously it was happy to be a std::wstring, but not it prefers to be a bool. The MSVC compiler does not complain, or raise warning, so I'm worried that even if I "fix" the setValue( L"empty", L"" ); to be setValue( L"empty", std::wstring() ); somebody else may come later and simply use setValue( L"empty", L"" ); and have to track down this issue again. We thought to use explicit on the method but it is not a valid keyword for this usage. Is there some way to get the compiler to complain about this, or otherwise prevent the issue? Otherwise I'm thinking to change the name of the method which takes a bool to ensure it can't make an incorrect guess.
First, the cause of this issue: C++ Standard [over.ics.rank]/2.11 defines an order for conversion sequences. It says that a user defined conversion sequence is worse than a standard conversion sequence. What happens in your case is that the string literal undergoes a boolean-conversion (defined at 4.12. This is a standard conversion). It does not use the user defined conversion to std::wstring which would be needed if it took the other overload. I would recommend to simply change the name of one of the overloads or adding an overload that accepts the string literal directly (using parameter type wchar_t const*). 1) When comparing the basic forms of implicit conversion sequences (as defined in [over.best.ics]) (2.1) a standard conversion sequence is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and (2.2) a user-defined conversion sequence is a better conversion sequence than an ellipsis conversion sequence.
316,200
316,245
Which C++ Library for CGI Programming?
I'm looking at doing some work (for fun) in a compiled language to run some simple tests and benchmarks against php. Basically I'd like to see what other people use for C++ CGI programming. (Including backend database, like mysql++ or something else)
I'm not sure exactly what you're looking for, but there is a C++ web framework called wt (pronounced "witty"). It's been kept pretty much up to date and if you want robust C++ server-side code, this is probably what you're looking for. You can check it out and read more at the wt homepage. P.S. You may have some trouble installing wt if you don't have experience with *nix or C++ libraries. There are walkthroughs but since frameworks like these are the road less traveled, expect to hit a few bumps.
316,400
317,237
Profiling Qt application that uses plugins
I have a medium sized application written in c++ using Qt. I wanted to profile things to see where my least performant code was so I compiled everything with -pg. However, my application makes use of a lot of plugins using the QTPlugin mechanism (boils down to a dlopen and a dlsym of a instance object per plugin). I've noticed that gprof doesn't seem to include functions from plugins. Yes, the plugins are also compiled with -pg and all that. Is there anything special I have to do get everything profiled? Or am I missing something simple?
If you can use it, I think Valgrind's callgrind only needs debug symbols (-g) to profile code. I'm not sure if it works with dynamically linked objects, though.
316,436
316,451
What tools do you use to profile (native)C++ on Windows?
How do Window's programmers profile their native C++ code? On Unix/Linux you have gprof [thanks Evan] & valgrind (I personally used this one, although it's not a real profiler), and recently I'm on Mac and Solaris, which means I moved to dTrace. Now when I've had the need to profile on Windows in the past, like at my previous job, I used Intel's vtune, which is great, however it's commercial, and I don't have a license for private use, so I'm left wondering what's the standard (free is better) tool windows programmers commonly use? Thanks in advance
You should give Xperf a try - it's a new system wide performance tool that can drill down to a particular application and what exactly it's doing inside itself as well as what's it's asking of the OS. It's freely available on the Windows SDK for Windows Server 2008 and .NET Framework 3.5 ISO: Install the SDK by downloading the ISO image, or using the Web based installer. Find the xperf MSI in the SDK's "bin" directory. It will be named xperf_x86.msi, xperf_x64.msi, or xperf_ia64.msi, depending on the architecture for which you install the SDK. You can then install the xperf tools from the MSI directly, or copy the xperf MSI file to another location and install it from there. For example, you could keep the MSI files on a USB key. Source: Pigs Can Fly blog on MSDN.com Just verified that the xperf msi will not install except on windows Vista or Windows 2007. -Adam
316,626
1,174,697
How do I read from a version resource in Visual C++
I have a version resource in my resources in a C++ project which contains version number, copyright and build details. Is there an easy way to access this at run-time to populate my help/about dialog as I am currently maintaining seperate const values of this information. Ideally, the solution should work for Windows/CE mobile and earlier versions of Visual C++ (6.0 upwards).
This is an edited version of my original answer. bool GetProductAndVersion(CStringA & strProductName, CStringA & strProductVersion) { // get the filename of the executable containing the version resource TCHAR szFilename[MAX_PATH + 1] = {0}; if (GetModuleFileName(NULL, szFilename, MAX_PATH) == 0) { TRACE("GetModuleFileName failed with error %d\n", GetLastError()); return false; } // allocate a block of memory for the version info DWORD dummy; DWORD dwSize = GetFileVersionInfoSize(szFilename, &dummy); if (dwSize == 0) { TRACE("GetFileVersionInfoSize failed with error %d\n", GetLastError()); return false; } std::vector<BYTE> data(dwSize); // load the version info if (!GetFileVersionInfo(szFilename, NULL, dwSize, &data[0])) { TRACE("GetFileVersionInfo failed with error %d\n", GetLastError()); return false; } // get the name and version strings LPVOID pvProductName = NULL; unsigned int iProductNameLen = 0; LPVOID pvProductVersion = NULL; unsigned int iProductVersionLen = 0; // replace "040904e4" with the language ID of your resources if (!VerQueryValue(&data[0], _T("\\StringFileInfo\\040904e4\\ProductName"), &pvProductName, &iProductNameLen) || !VerQueryValue(&data[0], _T("\\StringFileInfo\\040904e4\\ProductVersion"), &pvProductVersion, &iProductVersionLen)) { TRACE("Can't obtain ProductName and ProductVersion from resources\n"); return false; } strProductName.SetString((LPCSTR)pvProductName, iProductNameLen); strProductVersion.SetString((LPCSTR)pvProductVersion, iProductVersionLen); return true; }
317,087
317,100
boost lambda for_each / transform puzzle
Does anybody know why vector<int> test(10); int a=0; for_each(test.begin(),test.end(),(_1+=var(a),++var(a))); for_each(test.begin(),test.end(),(cout << _1 << " ")); cout << "\n" Gives : "0 1 2 3 4 5 6 7 8 9" but transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a))); ...(as before) Gives : "1 2 3 4 5 6 7 8 9 10" ?
Comma operator evaluates left to right, so the result of the _1+=var(a), ++var(a) is ++var(a), which you'll store using the transform version. for_each: _1 += var(a) is evaluated, updating your sequence (via the lambda _1), then ++var(a) is evaluated, but this has no effect on your sequence. transform: _1+=var(a) is evaluated, updating your sequence (just like before), then ++var(a) is evaluated, this also gives the result of the whole expression, then that is used to update your sequence again (via the transform)
317,140
317,145
Get dimensions of JPEG in C++
I need to get the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source libraries! Has anyone come across anything that might do the trick, or understand the JPEG file format (I think I probably mean the JFIF file format here) to tell me how I might go about rolling my own solution?
You have this C function which may extract the relevant data for you. This is a C routine but should compile fine with C++. Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and width. Or you may find in the Boost library a jpeg class which has the right function (From Adobe Generic Image Library). jpeg_read_dimensions boost::gil::jpeg_read_dimensions (const char *filename) Returns the width and height of the JPEG file at the specified location. Throws std::ios_base::failure if the location does not correspond to a valid JPEG file.
317,450
317,528
Why override operator()?
In the Boost Signals library, they are overloading the () operator. Is this a convention in C++? For callbacks, etc.? I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me. Any insight as to the reason for this overload?
One of the primary goal when overloading operator() is to create a functor. A functor acts just like a function, but it has the advantages that it is stateful, meaning it can keep data reflecting its state between calls. Here is a simple functor example : struct Accumulator { int counter = 0; int operator()(int i) { return counter += i; } } ... Accumulator acc; cout << acc(10) << endl; //prints "10" cout << acc(20) << endl; //prints "30" Functors are heavily used with generic programming. Many STL algorithms are written in a very general way, so that you can plug-in your own function/functor into the algorithm. For example, the algorithm std::for_each allows you to apply an operation on each element of a range. It could be implemented something like that : template <typename InputIterator, typename Functor> void for_each(InputIterator first, InputIterator last, Functor f) { while (first != last) f(*first++); } You see that this algorithm is very generic since it is parametrized by a function. By using the operator(), this function lets you use either a functor or a function pointer. Here's an example showing both possibilities : void print(int i) { std::cout << i << std::endl; } ... std::vector<int> vec; // Fill vec // Using a functor Accumulator acc; std::for_each(vec.begin(), vec.end(), acc); // acc.counter contains the sum of all elements of the vector // Using a function pointer std::for_each(vec.begin(), vec.end(), print); // prints all elements Concerning your question about operator() overloading, well yes it is possible. You can perfectly write a functor that has several parentheses operator, as long as you respect the basic rules of method overloading (e.g. overloading only on the return type is not possible).
317,719
317,730
C++ Namespace question
I am working on some code written by a co-worker who no longer works with the company, and I have found the following code: (which I have cut down below) namespace NsA { namespace NsB { namespace NsC { namespace { class A { /*etc*/ }; class B { /*etc*/ }; } namespace { class C { /*etc*/ }; } } } } I don't understand the purpose of the namespace commands on lines 3 and 8. Can someone explain what the purpose of an namespace entry with no name is? Thanks
That's an "anonymous namespace" - which creates a hidden namespace name that is guaranteed to be unique per "translation unit" (i.e. per CPP file). This effectively means that all items inside that namespace are hidden from outside that compilation unit. They can only be used in that same file. See also this article on unnamed namespaces.
318,064
318,137
How do you declare an interface in C++?
How do I setup a class that represents an interface? Is this just an abstract base class?
To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't. class IDemo { public: virtual ~IDemo() {} virtual void OverrideMe() = 0; }; class Parent { public: virtual ~Parent(); }; class Child : public Parent, public IDemo { public: virtual void OverrideMe() { //do stuff } }; You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.
318,236
318,281
How do you validate that a string is a valid IPv4 address in C++?
I don't need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, where xxx is between 0 and 255.
You probably want the inet_pton, which returns -1 for invalid AF argument, 0 for invalid address, and +1 for valid IP address. It supports both the IPv4 and future IPv6 addresses. If you still need to write your own IP address handling, remember that a standard 32-bit hex number is a valid IP address. Not all IPv4 addresses are in dotted-decimal notation. This function both verifies the address, and also allows you to use the same address in related socket calls.
318,265
318,314
Launching a Process from a Service
I'm trying to launch another process from a service (it's a console app that collects some data and writes it to the registry) but for some reason I can't get it to launch properly. I basics of what I'm am trying to do is as follows: Launch the process Wait for the process to finish Retrieve the return code from the process I am currently using the following code: STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; if (CreateProcess(PATH, ARGS, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) { ::WaitForSingleObject(processInfo.hProcess, INFINITE); DWORD exit = 100; GetExitCodeProcess(processInfo.hProcess, &exit); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); return exit; } Upon calling CreateProcess(), it succeeds and enters the body of the if statement. The call to WaitForSingleObject returns immediately, which it should not, as the process should take approximately 20-30 seconds to finish. And, finally, calling GetExitCodeProcess() fails and does not set the value "exit". FYI, this is code I have actually used elsewhere with success, just not in a service. Could it be that it's being launched from a service and there are permissions issues?? Edit: I've now realized that it will actually launch the app (I can see it in TaskMan) but it seems to be stuck. It's there, but isn't doing anything. Based on Rob Kennedy's suggestion, I fixed the process handle issue, and it actually does wait for the process to finish. But it never does finish unless I kill it manually.
WaitForSingleObject and GetExitCodeProcess expect the process handle itself, not a pointer to the process handle. Remove the ampersands. Also, check the return values and call GetLastError when they fail. That will help you diagnose future problems. Never assume an API function will always succeed. Once you call the functions right, and the new process starts but makes no progress, you can be reasonably certain that this code is not the culprit. The problem lies in the new process, so focus your debugging tasks there, not in the service process.
318,398
318,440
Why does C++ compilation take so long?
Compiling a C++ file takes a very long time when compared to C# and Java. It takes significantly longer to compile a C++ file than it would to run a normal size Python script. I'm currently using VC++ but it's the same with any compiler. Why is this? The two reasons I could think of were loading header files and running the preprocessor, but that doesn't seem like it should explain why it takes so long.
Several reasons Header files Every single compilation unit requires hundreds or even thousands of headers to be (1) loaded and (2) compiled. Every one of them typically has to be recompiled for every compilation unit, because the preprocessor ensures that the result of compiling a header might vary between every compilation unit. (A macro may be defined in one compilation unit which changes the content of the header). This is probably the main reason, as it requires huge amounts of code to be compiled for every compilation unit, and additionally, every header has to be compiled multiple times (once for every compilation unit that includes it). Linking Once compiled, all the object files have to be linked together. This is basically a monolithic process that can't very well be parallelized, and has to process your entire project. Parsing The syntax is extremely complicated to parse, depends heavily on context, and is very hard to disambiguate. This takes a lot of time. Templates In C#, List<T> is the only type that is compiled, no matter how many instantiations of List you have in your program. In C++, vector<int> is a completely separate type from vector<float>, and each one will have to be compiled separately. Add to this that templates make up a full Turing-complete "sub-language" that the compiler has to interpret, and this can become ridiculously complicated. Even relatively simple template metaprogramming code can define recursive templates that create dozens and dozens of template instantiations. Templates may also result in extremely complex types, with ridiculously long names, adding a lot of extra work to the linker. (It has to compare a lot of symbol names, and if these names can grow into many thousand characters, that can become fairly expensive). And of course, they exacerbate the problems with header files, because templates generally have to be defined in headers, which means far more code has to be parsed and compiled for every compilation unit. In plain C code, a header typically only contains forward declarations, but very little actual code. In C++, it is not uncommon for almost all the code to reside in header files. Optimization C++ allows for some very dramatic optimizations. C# or Java don't allow classes to be completely eliminated (they have to be there for reflection purposes), but even a simple C++ template metaprogram can easily generate dozens or hundreds of classes, all of which are inlined and eliminated again in the optimization phase. Moreover, a C++ program must be fully optimized by the compiler. A C# program can rely on the JIT compiler to perform additional optimizations at load-time, C++ doesn't get any such "second chances". What the compiler generates is as optimized as it's going to get. Machine C++ is compiled to machine code which may be somewhat more complicated than the bytecode Java or .NET use (especially in the case of x86). (This is mentioned out of completeness only because it was mentioned in comments and such. In practice, this step is unlikely to take more than a tiny fraction of the total compilation time). Conclusion Most of these factors are shared by C code, which actually compiles fairly efficiently. The parsing step is a lot more complicated in C++, and can take up significantly more time, but the main offender is probably templates. They're useful, and make C++ a far more powerful language, but they also take their toll in terms of compilation speed.
318,420
318,502
ApplicationVerifier is not detecting handle leaks, what do I do?
I did select the executable correctly, because I can get it to respond to certain things I do. But I can't get ApplicationVerifier to properly detect a handle leak. Here is an example: int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { HANDLE hFile = CreateFile(_T("C:\\test.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); return 0; } ApplicationVerifier doesn't detect this. What can I do to detect the above problem?
Is your code only creating handles through CreateFile? If so you can just macro these methods out to versions that do custom implemented leak detection. It's a lot of work but it will get the job done. #if DEBUG #define CreateFile DebugCreateFile #define CloseHandle DebugCloseHandle #endif // in another cpp file #undef CreateFile #undef CloseHandle HANDLE DebugCreateFile(...) { HANDLE real = ::CreateFile(...); TrackHandle(real); return real; } void DebugCloseHandle(HANDLE target) { if (IsTracked(target)) { Untrack(target); } ::CloseHandle(target); } void CheckForLeaks() { // Look for still registered handles } At the end of your program you'd need to call CheckForLeaks. Like I said though, quite a bit of work but it may help with your scenairo.
318,511
318,520
Init Structure with std::wstring
I've got a structure as follows: typedef struct { std::wstring DevAgentVersion; std::wstring SerialNumber; } DeviceInfo; But when I try to use it I get all sorts of memory allocation errors. If I try to pass it into a function like this: GetDeviceInfo(DeviceInfo *info); I will get a runtime check error complaining that I didn't initialize it before using it, which I seemed to have fixed with: DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo)); But then, in the function, when I try to set either of the structures stings, it complains that I'm trying to access a bad pointer when trying to set a value to the string. What is the best way to initialize this structure (and all of it's internal strings?
You should use new instead of malloc, to assure the constructor gets called for the DeviceInfo and its contained wstrings. DeviceInfo *info = new DeviceInfo; In general, it's best to avoid using malloc in C++. Also, make sure to delete the pointer when you're done using it. Edit: Of course if you only need info in the local scope, you shouldn't allocate it on the heap. Just do this instead: DeviceInfo info; // constructed on the stack GetDeviceInfo( &info ); // pass the address of the info
318,641
319,613
Multiple QMainWindow instances?
The QMainWindow is the main window in a Qt application. So usually you'd have only one, but would it be possible at all to have multiple QMainWindow instances in your application? I am working on integrating a Qt-based GUI application B into another Qt-based GUI application A. Both these applications have a QMainWindow, and I was considering as a first step to create a new QMainWindow that has both old QMainWindows on tabs. That way it would allow me to concentrate on wiring the backend of GUI B to the backend of A without having to change anything in the user interface itself. Is this a viable approach, or do you have other suggestions?
You can have as many QMainWindow instances as you want. A QMainWindow is just a QWidget which provides a menu bar, toolbar, status bar and docking framework. But basically it is just a QWidget so you can have as many as you like. Normally you only have a single QMainWindow for GUI design reasons since it can be confusing to have multiple main windows. However, when implementing applications like QtAssistant which can open a new instance of themselves then the one process has multiple main windows. What you suggest should work. The window with the tabs would not need to be a QMainWindow unless you want to also want add a toolbar to that window as well.
318,835
318,881
Do you add information to the top of each .hpp/.cpp file?
When creating a new C++ header/source file, what information do you add to the top? For example, do you add the date, your name, a description of the file, etc.? Do you use a structured format for this information? e.g. // Foo.cpp - Implementation of the Foo class // Date: 2008-25-11 // Created by: John Smith One team I know embeds CVS commit messages to the foot of each file, but I'm not sure I want to go this far...
Information about who created a file and when and who edited it and when is all in source control. If your team has good practices around check-in comments, then you'll know the reasons for each change too. No need for comments for that stuff. I think it's 100% legit - wise, even - to put a comment block, as long as is necessary, explaining the purpose of the class/module. When the next person goes to change it, they'll have a better idea of the overall vision and whether this file is the appropriate place for their change. Some shops put copyright notices and other legal folderol in source file comments. This strikes me as just silly - if your (non-OSS) source code has made it onto someone else's servers without your knowledge or permission, a copyright notice is probably not going to deter them from doing anything with it. IANAL, YMMV.
319,154
319,196
boost::any_cast - throw only when an implicit conversion isn't available?
I want boost::any_cast<T> to only throw an exception when the type of the any doesn't have an implicit conversion to T. The normal behaviour seems to be to throw an exception if the type of the any is not T, regardless of implicit conversions. Example: boost::any a = 1; boost::any_cast<int>(a); // This succeeds, and rightfully so boost::any_cast<long>(a); // I don't want this to throw boost::any_cast<Widget>(a); // I want this to throw Could anyone tell me if there's a simple way to get the functionality I want, or better yet give me a good reason for why the existing behaviour is the way it is?
Well you can't do it. The any mechanism works like this: struct base { virtual ~base() { } }; template<typename T> struct concrete_base : base { T t; concrete_base(T t):t(t) { } }; struct my_any { base * b; template<typename T> my_any(T t):b(new concrete_base<T>(t)) { } template<typename T> T any_cast() { concrete_base<T> * t = dynamic_cast< concrete_base<T>* >(b); if(!t) throw bad_any_cast(); return t->t; } }; I hope it's clear what the above does. There is no way you could do what you are looking for i think. The reason is that there is no information about the type kept that could prove useful here. RTTI doesn't provide it.
319,171
324,903
What Arguments are you supposed to give to the Windows API call VerQueryValue
I understand the first argument must be the result of GetFileVersionInfo(). The third and forth are target buffer and size What is the second argument, lpSubBlock? Thanks In Advance
When you view the version info through the resource editor you might notice that there is an initial section with FILEVERSION, PRODUCTVERISON etc. and then one or more blocks which contain language specific settings. VS_VERSION_INFO VERSIONINFO FILEVERSION 5,0,0,0 PRODUCTVERSION 5,0,0,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "" VALUE "FileVersion", "5, 0, 0, 0" VALUE "ProductName", "" VALUE "ProductVersion", "5, 0, 0, 0" END BLOCK "000004b0" BEGIN VALUE "CompanyName", "" VALUE "FileVersion", "5, 0, 0, 0" VALUE "ProductName", "" VALUE "ProductVersion", "5, 0, 0, 0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200, 0x409, 1200 END END To get a VS_FIXEDFILEINFO with the non language specific detail use VS_FIXEDFILEINFO *versionInfo; PUINT versionInfoSize; VerQueryValue(buffer.get(), TEXT("\\"), (void**) &versionInfo, &versionInfoSize)) To find out what languages are supported use Var *translationsInfo; PUINT transaltionInfoSize; VerQueryValue(buffer.get(), TEXT("\\VarFileInfo\\Translation"), (void**) &translationsInfo, &transaltionInfoSize)) To get the language specific version detail then use StringTable *stringTable; PUINT stringTableSize; std::wstring path( L"\\StringFileInfo\\" ); path += L"040904b0"; // get this value from the language support list path += L"\\FileVersion"; VerQueryValue(buffer.get(), path.c_str(), (void**) &stringTable, &stringTableSize))
319,292
319,306
Changing the reserve memory of C++ vector
I have a vector with 1000 "nodes" if(count + 1 > m_listItems.capacity()) m_listItems.reserve(count + 100); The problem is I also clear it out when I'm about to refill it. m_listItems.clear(); The capacity doesn't change. I've used the resize(1); but that doesn't seem to alter the capacity. So how does one change the reserve?
vector<Item>(m_listItems).swap(m_listItems); will shrink m_listItems again: http://www.gotw.ca/gotw/054.htm (Herb Sutter) If you want to clear it anyway, swap with an empty vector: vector<Item>().swap(m_listItems); which of course is way more efficient. (Note that swapping vectors basicially means just swapping two pointers. Nothing really time consuming going on)
319,395
319,404
Pointer Pointer Methods C++
I have two questions: 1) How can I make an array which points to objects of integers? int* myName[5]; // is this correct? 2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method: int **getStuff() { // what goes here? return *(myName); // im pretty sure this is not correct } Thanks for the help!
How can I make an array which points to objects? int * myName[5]; /* correct */ If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? Technically, you write this function: int * (* getStuff() )[5] { return &myName; } That returns a pointer to that array. However, you don't want to do that. You wanted to return a pointer to the first element of the array: int ** getStuff() { return myName; /* or return &myName[0]; */ } That way, you can now access items as you want like getStuff()[0] = &someInteger;
319,623
319,663
C++ Parameter Reference
void (int a[]) { a[5] = 3; // this is wrong? } Can I do this so that the array that is passed in is modified? Sorry for deleting, a bit new here... I have another question which might answer my question: If I have void Test(int a) { } void Best(int &a) { } are these two statements equivalent? Test(a); Best(&a);
void Test(int a[]) { a[5] = 3; } just alternate syntax for: void Test(int* a) { *(a+5) = 3; } No array is passed, just a pointer. The original array is modified. As for your second revision, given: void Test(int a) { } void Best(int &a) { } then Test(aa); // Passes aa by value. Changes to a in Test() do not effect aa Best(aa); // Passes aa by reference; Changes to a DO effect aa Best(&aa); // Is a syntax error: Passing a pointer instead of an int.
319,790
319,930
SQLite C/C++ API unsigned char *
Why does the SQLite C/C++ API return unsigned char *s for text values as opposed to the more de-facto char * type? This is somewhat related to the unsigned char question, except that the SQLite API's decision seems opposite of the conventional char * advice given for string-like values. For example: const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
From the SQLite documentation: (H13821) The sqlite3_column_text(S,N) interface converts the Nth column in the current row of the result set for the prepared statement S into a zero-terminated UTF-8 string and returns a pointer to that string. UTF-8 wants byte values ranging from 0x00 to 0xFF. char can range from -0x80 to 0x7F (signed) or 0x00 to 0xFF (unsigned). Forcing unsigned allows the proper encoding of a UTF-8 string.
319,880
319,901
Integer division rounding with negatives in C++
Suppose a and b are both of type int, and b is nonzero. Consider the result of performing a/b in the following cases: a and b are both nonnegative. a and b are both negative. Exactly one of them is negative. In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.
According to the May 2008 revision, You're right: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined75). Note 75 says: According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero. Chances are that C++ will lag C in this respect. As it stands, it's undefined but they have an eye towards changing it. I work in the same department as Stroustrup and with a member of the committee. Things take AGES to get accomplished, and its endlessly political. If it seems silly, it probably is.
320,124
320,136
Debugging an application in Linux
I want to debug an application in Linux. The application is created in C++. The GUI is created using QT. The GUI is linked with a static library that can be treated as the back end of the application. I want to debug the static library but am not sure how to do that. I tried using gdb gdb GUI But how can I attach the library? Has anyone had experience in debugging libraries in linux?
gdb will automatically debug functions in the library when they are called. just call it like gdb ./foo run :) . Be sure you build foo with debugging flags (-g3 will enable all debugging stuffs for gcc :). You should not optimize when debugging (pass at most -O1 to gcc, do not optimize further). It can confuse the debugger.
320,506
320,515
C++: how to create an array of objects on the stack?
Consider the following piece of Java code. int N = 10; Object obj[] = new Object[N]; for (int i = 0; i < N; i++) { int capacity = 1000 * i; obj[i] = new ArrayList(capacity); } Because in Java, all objects live on the Heap, the array does not contain the objects themselves, but references to the objects. Also, the array itself is also an object, thus it lives on the heap. What is the equivalent in C++, but keeping the array and objects on the stack, to avoid as much as possible needing new and delete ? Edit: changed the code to use a custom constructor.
For an array of ArrayList objects: ArrayList obj[10]; The objects will be default initialised, which is fine for user-defined types, but may not be what you want for builtin-types. Consider also: std::vector<ArrayList> obj(10, ArrayList()); This initialises the objects by copying whatever you pass as the second parameter. So they're all the same, but not necessarily default. And as litb points out, the "10" in the vector can be replaced by a non-constant expression, whereas the "10" in the array declaration can't. This doesn't actually put the ArrayList objects on the stack, it puts all 10 in a single allocation from the heap. So there may very rarely be performance concerns, if you really can't afford a single allocation. However, the std::vector is on the stack and it deletes any heap objects it uses when it is destroyed. So for the purposes of making sure your resources are freed, the vector behaves "as though" it were all on the stack. Note that mixing a container of Object, with ArrayList values, as you do in your example Java code, is fraught with peril in C++. Basically you can't do it, even if ArrayList extends Object, because the array would only contain the storage for 10 Objects, and ArrayList likely requires more bytes to store than Object. The result is that any ArrayList you try to copy into the array would get "sliced": only the initial part of its representation is put in the array. If you want a container of a type saying that it contains Objects, but which actually contains ArrayLists, then you need a container of pointers. To get good resource-handling, this probably means you need a container of smart pointers.
320,600
320,701
How to automatically create a file with the latest compile time and include it into a library?
I have a library consisting of approx 100 source files. I want one of the sources to be always rebuilt if any of the other files have been compiled but I don't want it built every time I run the make/build. Basically I want this file to have the last build date/time built into it so any application linking to the library can check the last build time/date. Is there any other way to do this?
To expand slightly on JesperE's solution. Let the object file depend on all targets which the executable depends on, (excluding itself). So if all the executable depends on is objects, then JesperE is completely correct. Otherwise, you could rebuild the executable without updating the timestamp, in the case where one of the other dependencies changes but none of your object files does. So the two things mentioned in the question, "has the last build time/date" and "rebuilt if any of the sources has been compiled", aren't actually the same thing, so it depends which you want. Examples could include a library you statically link against, or some script which is used to do the linking and which changes a lot so has been made a dependency for the convenience of developers. This still won't update the timestamp if you just delete the executable and rebuild it (perhaps because something has changed which is relevant, but not a dependency, such as because you've grabbed the latest version of the linker or you've changed something in the environment which affects the linker and/or the makefile). So the best thing to do might be to compile the object as part of the rule for building the executable, like this: blah.exe : whatever rm -f version.o $(CC) $(CFLAGS) -c version.c $(CC) $(CFLAGS) $(OBJFILES) version.o -o blah.exe or whatever (probably not .exe if you're using make, but you never know). Actually the error-handling there is a bit dodgy, since version.o won't be deleted if the last line fails. I'd also add that if you're going to release something to users (by which I mean basically anyone more than 10 feet from your desk), it might be an idea to build from scratch anyway rather than just run make to update, and ship it. It's pretty easy otherwise to screw up the makefile so that you miss a dependency, accidentally build a "mixed version", and have no way to reproduce what you shipped. I've jiggered makefiles before so that the version number was deliberately sabotaged (set to "0.0 private build") if it was built by a developer - only the build server set the option used to enable the proper version number. For that project, it just wasn't meaningful to put a number on something that wasn't checked out of source control by tags, and built from there.
320,618
320,627
How to resolve name collision when using c headers?
I am currently doing some socket programming using C/C++. To be able to use a somewhat cleaner interface, and a more OO structure, I decided to write a few simple wrapper classes around parts of the C socket API, but while doing so I stumbled upon a problem: Given the following code: // Global method int foo(int x) { return x; } // Class that calls the global method class FooBar { public: void foo() { return; }; void baz() { foo(1); } }; g++ gives the following error message: test.cpp: In member function ‘void FooBar::baz()’: test.cpp:10: error: no matching function for call to ‘FooBar::foo(int)’ test.cpp:9: note: candidates are: void FooBar::foo() Renaming the class method solves the problem. Why is it that there is some kind of naming conflict even though the method signatures are different? What is the best way to fix this? Thanks /Erik
The problem is that it first looks in the scope of your class, and finds a foo function. The lookup will stop then, and the compiler tries to match arguments. Since it only has the one foo function in that scope in your class, calling the function fails. You need to explicitly state that you want to call the free function: ::foo(1); Another solution is to declare the function within baz: void baz() { int foo(int); foo(1); } The scope that the foo function is assumed to be defined in is the surrounding namespace of your class.
320,677
320,688
How do I set the icon for my application in visual studio 2008?
How do I set the executable icon for my C++ application in visual studio 2008?
First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon. Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu. Then compile your project and see the effect. See: http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0
320,723
320,745
Visual C++ 'Force Includes' option
I have just come across a Visual C++ option that allows you to force file(s) to be included - this came about when I was looking at some code that was missing a #include "StdAfx.h" on each .cpp file, but was actually doing so via this option. The option can be found on the Advanced C/C++ Configuration Properties page and equates to the /FI compiler option. This option could prove really useful but before I rush off and start using it I thought I'd ask if there are any gotchas?
I would discourage from /FI (MSDN says it's called /FI . Not sure whether i looked at the right page though), simply because people or yourself reading the files don't notice a header is magically included anyway. You can be sure this will cause much debugging time for someone that wants to figure out where specific macros come from, even though there are no #include lines at the top of the file.
320,798
320,811
Adding types to the std namespace
Is it acceptable to add types to the std namespace. For example, I want a TCHAR-friendly string, so is the following acceptable? #include <string> namespace std { typedef basic_string<TCHAR> tstring; } Or should I use my own namespace?
No ... part of the point of a namespace is to prevent name collisions on upgrade. If you add things to the std namespace, then your code might break with the next release of the library if they decide to add something with the same name.
321,068
321,080
Returning multiple values from a C++ function
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters: void divide(int dividend, int divisor, int& quotient, int& remainder); A variation is to return one value and pass the other through a reference parameter: int divide(int dividend, int divisor, int& remainder); Another way would be to declare a struct to contain all of the results and return that: struct divide_result { int quotient; int remainder; }; divide_result divide(int dividend, int divisor); Is one of these ways generally preferred, or are there other suggestions? Edit: In the real-world code, there may be more than two results. They may also be of different types.
For returning two values I use a std::pair (usually typedef'd). You should look at boost::tuple (in C++11 and newer, there's std::tuple) for more than two return results. With introduction of structured binding in C++ 17, returning std::tuple should probably become accepted standard.
321,241
321,347
Dead code identification (C++)
I have a large legacy C++ project compiled under Visual Studio 2008. I know there is a reasonably amount of 'dead' code that is not accessed anywhere -- methods that are not called, whole classes that are not used. I'm looking for a tool that will identify this by static analysis. This question: Dead code detection in legacy C/C++ project suggests using code coverage tools. This isn't an option as the test coverage just isn't high enough. It also mentions a -Wunreachable-code. option to gcc. I'd like something similar for Visual Studio. We already use the linker's /OPT:REF option to remove redundant code, but this doesn't report the dead code at a useful level (when used with /VERBOSE there are over 100,000 lines, including a lot from libraries). Are there any better options that work well with a Visual Studio project?
You'll want something along the lines of QA-C++ (http://www.programmingresearch.com/QACPP_MAIN.html), also see http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis for similar products. You're looking for a static code analysis tool that detects unreachable code; many coding guidelines (such as MISRA-C++, if I'm not mistaken) require that no unreachable code exists. An analysis tool geared specifically to enforce such a guideline would be your best bet. And you'll like be able to find other uses for the tool as well.
321,298
408,331
FFMPEG Frame to DirectX Surface
Given a pointer to an AVFrame from FFMPEG's avcodec_decode_video() function how do I copy the image to a DirectX surface? (Assume I have a pointer to an appropriately sized DX X8R8G8B8 surface.) Thanks. John.
You can use FFMPEG's img_convert() function to simultaneously copy the image to your surface and convert it to RGB format. Here's a few lines of code pasted from a recent project of mine which did a similar thing (although I was using SDL instead of DirectX): AVFrame *frame; avcodec_decode_video(_ffcontext, frame, etc...); lockYourSurface(); uint8_t *buf = getPointerToYourSurfacePixels(); // Create an AVPicture structure which contains a pointer to the RGB surface. AVPicture pict; memset(&pict, 0, sizeof(pict)); avpicture_fill(&pict, buf, PIX_FMT_RGB32, _ffcontext->width, _ffcontext->height); // Convert the image into RGB and copy to the surface. img_convert(&pict, PIX_FMT_RGB32, (AVPicture *)frame, _context->pix_fmt, _context->width, _context->height); unlockYourSurface();
321,351
321,889
Initializing a union with a non-trivial constructor
I have a structure which I create a custom constructor to initialize the members to 0's. I've seen in older compilers that when in release mode, without doing a memset to 0, the values are not initialized. I now want to use this structure in a union, but get errors because it has a non-trivial constructor. So, question 1. Does the default compiler implemented constructor guarantee that all members of a structure will be null initialized? The non-trivial constructor just does a memset of all the members to '0' to ensure a clean structure. Question 2: If a constructor must be specified on the base structure, how can a union be implemented to contain that element and ensure a 0 initialized base element?
Question 1: Default constructors do initialize POD members to 0 according to the C++ standard. See the quoted text below. Question 2: If a constructor must be specified in a base class, then that class cannot be part of a union. Finally, you can provide a constructor for your union: union U { A a; B b; U() { memset( this, 0, sizeof( U ) ); } }; For Q1: From C++03, 12.1 Constructors, pg 190 The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list (12.6.2) and an empty function body. From C++03, 8.5 Initializers, pg 145 To default-initialize an object of type T means: if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); if T is an array type, each element is default-initialized; otherwise, the object is zero-initialized. To zero-initialize an object of type T means: if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T; if T is a non-union class type, each non static data member and each base-class subobject is zero-initialized; if T is a union type, the object’s first named data member is zero-initialized; if T is an array type, each element is zero-initialized; if T is a reference type, no initialization is performed. For Q2: From C++03, 12.1 Constructors, pg 190 A constructor is trivial if it is an implicitly-declared default constructor and if: its class has no virtual functions (10.3) and no virtual base classes (10.1), and all the direct base classes of its class have trivial constructors, and for all the nonstatic data members of its class that are of class type (or array thereof), each such class has a trivial constructor From C++03, 9.5 Unions, pg 162 A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class.An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects