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
2,824,442
2,824,490
Killing a thread while deleting an object
I have an application which does some socket communication with some hardwares. Assume for the particular hardware i have an object and this object initiates a thread which listens on a particular port number say 5001 infinitely until a connection is established. Now if i delete this obect is there anyway by which i can ensure that the thread that is listening on port number 5001 infinitely also gets destroyed. So the problem is whenever a new object for the same device is created the old thread does not get destroyed and hence there are thread leaks.
In Windows you could use WaitForSingleObject function to check whether thread exited (you can pass thread's handle to is as an argument). And you probably want to create event which will initiate thread's exit.
2,824,451
2,824,467
Convert string to GUID with sscanf
I'm trying to convert a string to GUID with sscanf: GUID guid; sscanf( "11111111-2222-3333-4455-667788995511", "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", &guid.Data1, &guid.Data2, &guid.Data3, &guid.Data4[0], &guid.Data4[1], &guid.Data4[2], &guid.Data4[3], &guid.Data4[4], &guid.Data4[5], &guid.Data4[6], &guid.Data4[7]); However, in runtime, it fails and exits with "Error: Command failed". Why? How to fix it? I do not want to compile with /clr so cannot use System.
Where does "Error: Command failed" come from? It's not a standard error message... You can use the UuidFromString function to do it in native C++.
2,824,508
2,826,347
What is so great about STL?
I am a Java developer trying to learn C++. I have many times read on the internet (including Stack Overflow) that STL is the best collections library that you can get in any language. (Sorry, I do not have any citations for that) However after studying some STL, I am really failing to see what makes STL so special. Would you please shed some light on what sets STL apart from the collection libraries of other languages and make it the best collection library?
What is so great about the STL ? The STL is great in that it was conceived very early and yet succeeded in using C++ generic programming paradigm quite efficiently. It separated efficiently the data structures: vector, map, ... and the algorithms to operate on them copy, transform, ... taking advantage of templates to do so. It neatly decoupled concerns and provided generic containers with hooks of customization (Comparator and Allocator template parameters). The result is very elegant (DRY principle) and very efficient thanks to compiler optimizations so that hand-generated algorithms for a given container are unlikely to do better. It also means that it is easily extensible: you can create your own container with the interface you wish, as long as it exposes STL-compliant iterators you'll be able to use the STL algorithms with it! And thanks to the use of traits, you can even apply the algorithms on C-array through plain pointers! Talk about backward compatibility! However, it could (perhaps) have been better... What is not so great about the STL ? It really pisses me off that one always have to use the iterators, I'd really stand for being able to write: std::foreach(myVector, [](int x) { return x+1;}); because face it, most of the times you want to iterate over the whole of the container... But what's worse is that because of that: set<int> mySet = /**/; set<int>::const_iterator it = std::find(mySet.begin(), mySet.end(), 1005); // [1] set<int>::const_iterator it = mySet.find(1005); // [2] [1] and [2] are carried out completely differently, resulting in [1] having O(n) complexity while [2] has O(log n) complexity! Here the problem is that the iterators abstract too much. I don't mean that iterators are not worthy, I just mean that providing an interface exclusively in terms of iterators was a poor choice. I much prefer myself the idea of views over containers, for example check out what has been done with Boost.MPL. With a view you manipulate your container with a (lazy) layer of transformation. It makes for very efficient structures that allows you to filter out some elements, transform others etc... Combining views and concept checking ideas would, I think, produce a much better interface for STL algorithms (and solve this find, lower_bound, upper_bound, equal_range issue). It would also avoid common mistakes of using ill-defined ranges of iterators and the undefined behavior that result of it...
2,824,510
2,824,535
C++ casted realloc causing memory leak
I'm using a function I found here to save a webpage to memory with cURL: struct WebpageData { char *pageData; size_t size; }; size_t storePage(void *input, size_t size, size_t nmemb, void *output) { size_t realsize = size * nmemb; struct WebpageData *page = (struct WebpageData *)output; page->pageData = (char *)realloc(page->pageData, page->size + realsize + 1); if(page->pageData) { memcpy(&(page->pageData[page->size]), input, realsize); page->size += realsize; page->pageData[page->size] = 0; } return realsize; } and find the line: page->pageData = (char *)realloc(page->pageData, page->size + realsize + 1); is causing a memory leak of a few hundred bytes per call. The only real change I've made from the original source is casting the line in question to a (char *), which my compiler (gcc, g++ specifically if it's a c/c++ issue, but gcc also wouldn't compile with the uncast statement) insisted upon, but I assume this is the source of the leak. Can anyone elucidate? Thanks
The code you have posted (as far as I can tell) is correct. If it's leaking, I suspect that you are forgetting to free() the memory block at some point. realloc is allowed to create an entire new memory block if it can't simply expand the existing one, and this is of interest to you. It is also of course allowed to allocate a larger block than needed, which might result in the phantom leaks. Now, since you are using C++, I have to ask: why aren't you using std::vector instead? struct WebpageData { std::vector<char> pageData; size_t size; }; size_t storePage(void *input, size_t size, size_t nmemb, void *output) { size_t realsize = size * nmemb; WebpageData *page = reinterpret_cast<WebpageData *>(output); page->pageData.resize(page->size + realsize + 1); memcpy(&(page->pageData[page->size]), input, realsize); page->size += realsize; page->pageData[page->size] = 0; return realsize; }
2,824,579
2,824,654
what if i keep my class members are public?
In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make my data to be public? what are the disadvantages of this approch? why it is a bad design?
You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism? Data, just like methods, should be public (named without a leading underscore) if they're part of your class's designed API which you intend to support going forward. In C++, or Java, that's unlikely to happen because if you want to change the data member into an accessor method, you're out of luck -- you'll have to break your API and every single client of the class will have to change. In Python, and other languages supporting a property-like construct, that's not the case -- you can always replace a data member with a property which calls accessor methods transparently, the API does not change, nor does client code. So, in Python and other languages with property-like constructs (I believe .NET languages are like that, at source-code level though not necessarily at bytecode level), you may as well leave your data public when it's part of the API and no accessors are currently needed (you can always add accessor methods to later implementation releases if need be, and not break the API). So it's not really a general OO issue, it's language specific: does a given language support a property-like construct. Python does.
2,824,952
2,832,498
Setting up separate ctags db's for C/C++ standard libs, boost, and third party libs
I want to set up separate ctags databases for various libraries in /usr/include/ for use with OmniCppComplete. The idea is to be able to pull in only the libraries needed for a particular project in the target language - C or C++. For example, I'd like to have one database for the standard C libraries, one for system libraries that might be used by either C or C++ programs ( sockets / networking comes to mind ) one for the standard C++ libs / STL / Boost, and then other databases for various third party libraries such as QT or glib. Then I could pull something in simply by typing set tags+= ~/.vim/somelib.tags in vim. I assume that everything related to the C++ stdlib and STL are in the /usr/include/c++ and that Boost is all in /usr/include/boost. Unfortunately it seems that the standard C libs and system libs are just kind of dumped directly into /usr/include/ with a variety of other stuff. How can I get a list of which files and directories belong to which libs? I'm on Ubuntu 8.04.
apt-file is your friend on Ubuntu. The following command will give you a list of all include files for Boost: apt-file list -x "^libboost" | grep '/include/' | cut -f2 -d: I'll leave the rest as an exercise for the reader! Update: For completeness, call apt-file update if you have never used apt-file before.
2,824,973
2,825,704
Read/Write file metadata using C/C++
Searched through net, could't find a way to read/write file metadata using C or C++, however, there are tools available for this, and also there are API's in C# and Java to do this. But I want to do it from scratch in C or C++. For example, read/write image metadata. Have found out that there are three formats in which metadata is written to files. EXIF, IPTC and XMP. Thanks.
Why would you want to do it from scratch? Anyway, you need documentation and you may also want to look at an existing library for helps, expecially if you have no experience in the field. Have you tried Exiv ? Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy read and write access to the Exif, IPTC and XMP metadata of images in various formats. Exiv2 is available as free software and with a commercial license, and is used in many projects.
2,825,165
2,825,208
how to use replace_regex_copy() from boost::algorithm library?
This is my code: #include <string> #include <boost/algorithm/string/regex.hpp> string f(const string& s) { using namespace boost::algorithm; return replace_regex_copy(s, "\\w", "?"); } This is what compiler says: no matching function for call to ‘replace_regex_copy(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::string, std::string) The link to the library: http://www.boost.org/doc/libs/1_43_0/doc/html/boost/algorithm/replace_regex_copy.html Could anyone please help? Thanks! ps. Boost library is in place, since other functions from it work fine.
replace_regex_copy takes a boost::regex as its second argument, not a std::string. There is an explicit conversion from std::string to boost::regex, but no implicit conversion exists, so you can fix your code by changing it to... string f(const string& s) { using namespace boost::algorithm; return replace_regex_copy(s, boost::regex("\\w"), "?"); }
2,825,424
2,825,479
Comparing objects and inheritance
In my program I have the following class hierarchy: class Base // Base is an abstract class { }; class A : public Base { }; class B : public Base { }; I would like to do the following: foo(const Base& one, const Base& two) { if (one == two) { // Do something } else { // Do something else } } I have issues regarding the operator==() here. Of course comparing an instance A and an instance of B makes no sense but comparing two instances of Base should be possible. (You can't compare a Dog and a Cat however you can compare two Animals) I would like the following results: A == B => false A == A => true or false, depending on the effective value of the two instances B == B => true or false, depending on the effective value of the two instances My question is: is this a good design/idea ? Is this even possible ? What functions should I write/overload ?
class Base // Base is an abstract class { virtual bool equals(const Base& b) = 0; }; class A : public Base { virtual bool equals(const Base& base) { if (const A* a = dynamic_cast<const A*>(&base)) { // Return true iff this and a are equal. } return false; } }; class B : public Base { virtual bool equals(const Base& base) { if (const B* b = dynamic_cast<const B*>(&base)) { // Return true iff this and b are equal. } return false; } };
2,825,464
3,883,032
Generating a reasonable ctags database for Boost
I'm running Ubuntu 8.04 and I ran the command: $ ctags -R --c++-kinds=+p --fields=+iaS --extra=+q -f ~/.vim/tags/stdlibcpp /usr/include/c++/4.2.4/ to generate a ctags database for the standard C++ library and STL ( libstdc++ ) on my system for use with the OmniCppComplete vim script. This gave me a very reasonable 4MB tags file which seems to work fairly well. However, when I ran the same command against the installed Boost headers: $ ctags -R --c++-kinds=+p --fields=+iaS --extra=+q -f ~/.vim/tags/boost /usr/include/boost/ I ended up with a 1.4 GB tags file! I haven't tried it yet, but that seems likes it's going to be too large to be useful. Is there a way to get a slimmer, more usable tags file for my installed Boost headers? Edit Just as a note, libstdc++ includes TR1, which has allot of Boost libs in it. So there must be something weird going on for libstdc++ to come out with a 4 MB tags file and Boost to end up with a 1.4 GB tags file. Just ran across this on the Boost mailing list: Boost-users Boost and autocompletion THE ANSWER Thanks to Neg_EV for figuring out what the problem was, but there's a much better way of solving the problem than what he suggested: Make sure apt-file is install, and run the following commands ( I keep my library tags in ~/.vim/tags/ ): $ sudo apt-file update $ apt-file list boost | grep -E -o '/usr/include/.*\.(h|hpp)' | grep -v '/usr/include/boost/typeof/' > ~/.vim/tags/boost-filelist $ ctags --sort=foldcase --c++-kinds=+p --fields=+iaS --extra=+q -f ~/.vim/tags/boost -L ~/.vim/tags/boost-filelist I've upgraded to Ubuntu 10.04 and Boost 1.40 and that's what I tested this solution on, but it should work with any Boost version as far as I can tell.
I know this post is a little old, but I just ran into the same problem. I looked into it a little further and it seems it is one folder in boost that is causing the problem: typeof. I am using boost 1.37 and my tags file was 1.5G, typeof was 1.4G of that. So I just created a tags file without that directory included and the resulting size was 70M. I was even able to sort it without running out of space :) I imagine in newer versions of boost they may be other projects that are too large however the general solution I found is this... Generate a tag file for each boost folder seperately, a simple bash for loop should be able to do this. Look at which ones are too large. Either create a new single tags file excluding those large directories or keep the tag files separated simply deleting the ones that are too large. This is the script I used (taken from comments): for i in $(find -maxdepth 1 -type d | grep -v '^\.$' | sed 's/\.\///' ); do echo $i; ctags -f ~/tmp_tags/$i.tags -R --c++-kinds=+p --fields=+iaS --extra=+q --languages=c++ --sort=foldcase $i; done Hope this helps.
2,825,824
2,826,401
What's the best replacement for timeGetTime to avoid wrap-around?
timeGetTime seems to be quite good to query for system time. However, its return value is 32-bit only, so it wraps around every 49 days approx. It's not too hard to detect the rollover in calling code, but it adds some complexity, and (worse) requires keeping a state. Is there some replacement for timeGetTime that would not have this wrap-around problem (probably by returning a 64-bit value), and have roughly the same precision and cost?
Nope, tracking roll-over requires state. It can be as simple as just incrementing your own 64-bit counter on each callback. It is pretty unusual to want to track time periods to a resolution as low as 1 millisecond for up to 49 days. You'd have to worry that the accuracy is still there after such a long period. The next step is to use the clock, GetTickCount(64), GetSystemTimeAsFileTime have a resolution of 15.625 milliseconds and are kept accurate with a time server.
2,825,847
2,825,889
Fast dot product for a very special case
Given a vector X of size L, where every scalar element of X is from a binary set {0,1}, it is to find a dot product z=dot(X,Y) if vector Y of size L consists of the integer-valued elements. I suggest, there must exist a very fast way to do it. Let's say we have L=4; X[L]={1, 0, 0, 1}; Y[L]={-4, 2, 1, 0} and we have to find z=X[0]*Y[0] + X[1]*Y[1] + X[2]*Y[2] + X[3]*Y[3] (which in this case will give us -4). It is obvious that X can be represented using binary digits, e.g. an integer type int32 for L=32. Then, all what we have to do is to find a dot product of this integer with an array of 32 integers. Do you have any idea or suggestions how to do it very fast?
This really would require profiling but an alternative you might want to consider: int result=0; int mask=1; for ( int i = 0; i < L; i++ ){ if ( X & mask ){ result+=Y[i]; } mask <<= 1; } Typically bit shifting and bitwise operations are faster than multiplication, however, the if statement might be slower than a multiplication, although with branch prediction and large L my guess is it might be faster. You would really have to profile it, though, to determine if it resulted in any speedup. As has been pointed out in the comments below, unrolling the loop either manually or via a compiler flag (such as "-funroll-loops" on GCC) could also speed this up (eliding the loop condition). Edit In the comments below, the following good tweak has been proposed: int result=0; for ( int i = 0; i < L; i++ ){ if ( X & 1 ){ result+=Y[i]; } X >>= 1; }
2,826,128
2,828,263
Variadic functions and arguments assignment in C/C++
I was wondering if in C/C++ language it is possible to pass arguments to function in key-value form. For example in python you can do: def some_function(arg0 = "default_value", arg1): # (...) value1 = "passed_value" some_function(arg1 = value1) So the alternative code in C could look like this: void some_function(char *arg0 = "default_value", char *arg1) { ; } int main() { char *value1 = "passed_value"; some_function(arg1 = value1); return(0); } So the arguments to use in some_function would be: arg0 = "default_value" arg1 = "passed_value" Any ideas?
Here's a C99 solution using compound literals and variadic macros: #include <stdio.h> #define some_func(...) some_func_((struct some_func_args_){ __VA_ARGS__ }) struct some_func_args_ { const char *arg1; const char *arg2; }; static void some_func_(struct some_func_args_ args) { if(!args.arg1) args.arg1 = "default"; printf("---\narg1 = %s\narg2 = %s\n", args.arg1, args.arg2); } int main(void) { some_func("foo", "bar"); some_func(.arg1 = "spam"); some_func(.arg2 = "eggs"); return 0; }
2,826,308
2,827,092
How to align C++ class member names in one column in emacs?
I would like to align all C++ class member names ( do not confuse with member types ) in one column. Lets look at the example of what we have at entrance: class Foo { public: void method1( ); int method2( ); const Bar * method3( ) const; protected: float m_member; }; and this is what we would like to have at the end: class Foo { public: void method1( ); int method2( ); const Bar * method3( ) const; protected: float m_member; }; So the longest member type declaration defines the column to which class member names will be aligned. How can i perform such transformation in emacs ?
Select the region with the method declarations M-x align-regexp Enter the string [^ ]+\((\|;\) and press Enter Edited to add the ; in the matching, which aligns the member variable as well.
2,826,431
2,826,448
STL Rope - when and where to use
I was wondering under what circumstances you would use a rope over another STL container?
Ropes are a scalable string implementation: they are designed for efficient operation that involve the string as a whole. Operations such as assignment, concatenation, and substring take time that is nearly independent of the length of the string. Unlike C strings, ropes are a reasonable representation for very long strings such as edit buffers or mail messages. Advantages: Much faster concatenation and substring operations involving long strings. Inserting a character in the middle of a 10 megabyte rope should take on the order of 10s of microseconds, even if a copy of the original is kept, e.g. as part of an edit history. In contrast, this would take on the order of a second for conventional "flat" string representation. The time required for concatenation can be viewed as constant for most applications. It is perfectly reasonable to use a rope as the representation of a file inside a text editor. Potentially much better space performance. Minor modifications of a rope can share memory with the original. Ropes are allocated in small chunks, significantly reducing memory fragmentation problems introduced by large blocks Assignment is simply a (possibly reference counted) pointer assignment. Unlike reference-counted copy-on-write implementations, this remains largely true even if one of the copies is subsequently slightly modified. It is very inexpensive to checkpoint old versions of a string, e.g. in an edit history. It is possible to view a function producing characters as a rope. Thus a piece of a rope may be a 100MByte file, which is read only when that section of the string is examined. Concatenating a string to the end of such a file does not involve reading the file. (Currently the implementation of this facility is incomplete.) https://wayback.archive.org/web/20130102093702/https://www.sgi.com/tech/stl/Rope.html
2,826,469
2,826,588
Correct use of boost lambda
Consider the following piece of C++0x code: a_signal.connect([](int i) { if(boost::any_cast<std::string>(_buffer[i]) == "foo") { base_class<>* an_object = new derived_class(); an_object->a_method(_buffer[i]); }}); How would it correctly look in Boost Lambda (since this C++0x feature can't be used in GCC 4.4 yet)?
I think this should work: a_signal.connect(if_then( bind((std::string(*)(any&))&any_cast, var(_buffer)[_1]) == "foo", bind(&base_class<>::a_method, ll_static_cast< base_class<>* >( new_ptr<derived_class>() ), var(_buffer)[_1] ) ) ); bind, if_then, ll_static_cast, new_ptr, _1, var (and, i think ref too) are members of boost::lambda. But honestly, i would refuse to work with such code, personally :)
2,826,589
2,826,757
empty base class optimization
Two quotes from the C++ standard, §1.8: An object is a region of storage. Base class subobjects may have zero size. I don't think a region of storage can be of size zero. That would mean that some base class subobjects aren't actually objects. How do these statements co-exist?
A philosophical argument over the definition of "region" is unnecessary. 1.8/5 says, "Unless it is a bit-field, a most derived object shall have a non-zero size ... Base class sub-objects may have zero size". So the standard is quite clear what objects (and hence what "regions of storage") can have zero size. If you disagree with the standard what "region" means in English that's one thing, you can fault the authors' (non-programming-related) literary skills. For that matter you can fault their poetic skills (14.7.3/7) But it's quite clear what the standard says here about the sizes of objects of class types. The pragmatic way to read standards is that given two plausible interpretations of a word, choose the one which doesn't directly contradict another sentence in the same section of the standard. Don't choose the one which matches more closely your personal preferred use of the word, or even the most common use.
2,827,299
2,827,353
C code compiled with C++: undefined reference
I have a small program that I can compile with GCC and ICC without any difficulties, but I would also like the code to work with G++ and ICPC. I tried to add this: #ifdef __cplusplus extern "C" { #endif at the beginning and this: #ifdef __cplusplus } #endif at the end of all the header files, but I still get several `undefined reference to "..."' errors.
I think you're getting it wrong... The extern C is for disabling the function mangling; so if you do it just for the header files, when you try to link your mangled object code, the declared function names won't match with the function names in the object file. Anyway, the extern C won't add any portability if the whole application is being compiled and linked with the same C++ compiler, it's intended for mixing C libraries with C++ code. If your code is in the common subset of C and C++, you should be already able to compile it with either compiler, but I cannot see the reason to do that (besides working on the principle of least surprise, as C++ is more strict with some things).
2,827,422
2,827,761
How to reduce compile time with C++ templates
I'm in the process of changing part of my C++ app from using an older C type array to a templated C++ container class. See this question for details. While the solution is working very well, each minor change I make to the templated code causes a very large amount of recompilation to take place, and hence drastically slows build time. Is there any way of getting template code out of the header and back into a cpp file, so that minor implementation changes don't cause major rebuilds?
I think the general rules apply. Try to reduce coupling between parts of the code. Break up too large template headers into smaller groups of functions used together, so the whole thing won't have to be included in each and every source file. Also, try to get the headers into a stable state fast, perhaps testing them out against a smaller test program, so they wouldn't need changing (too much) when integrated into a larger program. (As with any optimization, it might be less worth to optimize for the compiler's speed when dealing with templates, rather than finding an "algorithmic" optimization that reduces the work-load drastically in the first place.)
2,827,426
2,827,613
How to implement tail calls in a custom VM
How can I implement tail calls in a custom virtual machine? I know that I need to pop off the original function's local stack, then it's arguments, then push on the new arguments. But, if I pop off the function's local stack, how am I supposed to push on the new arguments? They've just been popped off the stack.
I take it for granted that we're discussing a traditional "stack-based" virtual machine here. You pop off the current function's local stack preserving the still-relevant parts in non-stack "registers" (where the "relevant parts" are, clearly, the argument for the forthcoming recursive tail call), then (once all of the function's local stack and arguments are cleaned up) you push the arguments for the recursive call. E.g., suppose the function you're optimizing is something like: def aux(n, tot): if n <= 1: return tot return aux(n-1, tot * n) which without optimization might produce byte-code symbolically like: AUX: LOAD_VAR N LOAD_CONST 1 COMPARE JUMPIF_GT LAB LOAD_VAR TOT RETURN_VAL LAB: LOAD_VAR N LOAD_CONST 1 SUBTRACT LOAD_VAR TOT LOAD_VAR N MULTIPLY CALL_FUN2 AUX RETURN_VAL the CALL_FUN2 means "call a function with two arguments". With the optimization, it could become sometime like: POP_KEEP 2 POP_DISCARD 2 PUSH_KEPT 2 JUMP AUX Of course I'm making up my symbolic bytecodes as I go along, but I hope the intent is clear: POP_DISCARD n is the normal pop that just discards the top n entries from the stack, but POP_KEEP n is a variant that keeps them "somewhere" (e.g. in an auxiliary stack not directly accessible to the application but only to the VM's own machinery -- storage with such a character is sometimes called "a register" when discussing VM implementation) and a matching PUSH_KEPT n which empties the "registers" back into the VM's normal stack.
2,827,511
2,827,854
Is there an equivalent of Mac OS X "open" command that can be called from C++/Objective-C code?
On Mac OS X there is a very useful "open" command which launches an application suitable for opened file type. Is there some C++/Objective-C function on Mac which does the same? Note: I know I could launch an "open" process. I'm just not sure if it's the best option.
That is done by NSWorkspace. See -[NSWorkspace openFile:]. All you have to do is [[NSWorkspace sharedWorkspace] openFile:@"file.txt"] If you want more fine-grained control (e.g. getting all applications which can open a given file,) you use Launch Services. See the document and the reference.
2,827,553
2,828,794
Creating a new window that stays on top even when in full screen mode (Qt on Linux)
I'm using Qt 4.6.3, and ubuntu linux on an embedded target. I call dlg->setWindowState(Qt::WindowFullScreen); on my windows in my application (so I don't loose any real-estate on the touch screen to task bar and status panel on the top and bottom of the screen. This all works fine and as expected. The issue comes in when I want to popup the on screen keyboard to allow the user to input some data. I use m_keyProc= new QProcess(); m_keyProc->start("onboard -s 640x120"); This pops up the keyboard but it is behind the full screen window. The onbaord keyboards preferences are set such that it is always on top, but that seems to actually mean "except for full screen windows". I guess that makes sense and probably meets most use cases, but I need it to be really on top. Can I either A) Not be full screen mode (so the keyboard works) and programmatically hide the task bars? or B) Force the keyboard to be on top despite my full screen status? Note: On windows we call m_keyProc->start("C:\\Windows\\system32\\osk.exe"); and the osk keyboard is on top despite the full screen status. So, I'm guessing this is a difference in window mangers on the different operating systems. So do I need to set some flag on the window with the linux window manager?
Qt doesn't seem to have a way to bring other, non-Qt process in front. You may need to get the native, platform process ID from QProcess by calling QProcess::pid() and call the underlying OS API to do it.
2,827,688
2,827,703
error C2440: '=' : cannot convert from 'const char [2]' to 'char'
I am learning c++, and I am having issues doing some newbie things. I am trying to create a very small application that takes the users input and stores it into a char array. I then parse through that array and remove all parenthesis and dases and display it. like the following (325)858-7455 to 3258587455 But I am getting errors error C2440: '=' : cannot convert from 'const char [2]' to 'char' Below is my simple code that can easily be thrown in a compiler and ran. #include "stdafx.h" #include<iostream> #include<conio.h> using namespace std; /* This is a template Project */ int main() { char phoneNum[25]; for(int i = 0; i < (sizeof(phoneNum) / sizeof(char)); i++) { phoneNum[i] = "i"; } cout<< "Enter a phone Number" <<endl; cin>>phoneNum; if(phoneNum[0] != '(' || phoneNum[4] != ')' || phoneNum[8] != '-') { cout<<"error"; } else { for(int i = 0; i < (sizeof(phoneNum) / sizeof(char));i++) { if(phoneNum[i] != '(' || phoneNum[i] != ')' || phoneNum[i] != '-') { cout<<phoneNum[i]; } } } cin>>phoneNum; getchar(); return 0; } It is not completely finished so if anyone has any pointers on the best way to remove strings characters from a string. that would be great.
The problem is here, I believe: phoneNum[i] = "i"; You want to assign a single character, so you need to use single quotes for your literal: phoneNum[i] = 'i'; There may well be other problems - I've only tried to fix the one mentioned in the title :)
2,827,964
2,828,021
Dizzy-like game level representation (format)
How would you store game level for a Dizzy-like adventure game? How would you specify walkable areas and graphics? Is it tile-based, pixel-based or walkable surfaces can be described by vectors?
Very old adventure games (like Sierra's quests from the 80s) used to actually maintain a separate bitmap of the entire screen that represented z-depth and materials to determine where your character could go and where it would be hidden. They would use pixel sampling to check where their small sprites would go. Though current machines are faster, long side scrolling levels make this sort of approach impractical, IMHO. You have to go with more sparse representations. One option is to "reduce" your game into invisible tiles, which are easier to represent. The main problem with this is that it can constrain your design (e.g., difficult to do diagonal platforms), and it can make the animations very shoddy (e.g., your characters' feet not actually touching the platform). This option can work IMHO for zelda-like adventure games, but not for action games. A second option is to represent the game world via some vector representation and implement some collision detection. I would personally go with the second solution, especially if you can be smart about how you organize your data structures to minimize access time (e.g., have faster access to a subset of world elements close to your characters current position). I wouldn't be surprised if there are available 2D game engines that provide this sort of capability, as there are definitely 3D engines that do it. In fact, you may find it easier to use an existing 3D game engine and use it to render 2D.
2,828,280
2,828,320
'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?
In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is printed. Here's what I tried to do: ostream & Score::operator<< (ostream & os, Score right) { os << right.getPoints() << " " << right.scoreGetName(); return os; } Here are the errors returned: score.h(30) : error C2804: binary 'operator <<' has too many parameters (This error appears 4 times, actually) I managed to get it working by declaring the overload as a friend function: friend ostream & operator<< (ostream & os, Score right); And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member). Why does this work, yet the former piece of code doesn't? Thanks for your time! EDIT I deleted all mentions to the overload on the header file... yet I get the following (and only) error. binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion) How come my test, in main(), can't find the appropriate overload? (it's not the includes, I checked) Below is the full score.h #ifndef SCORE_H_ #define SCORE_H_ #include <string> #include <iostream> #include <iostream> using std::string; using std::ostream; class Score { public: Score(string name); Score(); virtual ~Score(); void addPoints(int n); string scoreGetName() const; int getPoints() const; void scoreSetName(string name); bool operator>(const Score right) const; private: string _name; int _points; }; #endif
Note: You might want to look at the operator overloading FAQ. Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. The canonical way to implement operator<< for any type is this: std::ostream& operator<<(std::ostream& os, const T& obj) { // stream obj's data into os return os; } Note that it is not a member function. Also note that it takes the object to stream per const reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either. Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming class T { public: void stream_to(std::ostream&) const {os << obj.data_;} private: int data_; }; and call that from the operator: inline std::ostream& operator<<(std::ostream& os, const T& obj) { obj.stream_to(os); return os; } or make the operator a friend class T { public: friend std::ostream& operator<<(std::ostream&, const T&); private: int data_; }; so that it can access the class' private parts: inline std::ostream& operator<<(std::ostream& os, const T& obj) { os << obj.data_; return os; }
2,828,637
2,828,673
C++: How do I correctly register and unregister file type associations for our application (programatically)
Time was when you set file associations in: HEY_CLASSES_ROOT\<.ext> However, that seems to be possible, but an incomplete solution anymore. There are additional associations throughout the registry. For example: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\KindMap HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\Extensions And all of the above, but by HKEY_USERS\ And Microsoft added their Set Default Associations control panel applet, which controls... what? I'm looking for a white paper, or discussions on: "How is a modern, Windows XP-Windows 7 compatible application written in C/C++ supposed to register and manipulate its file associations without interfering with Explorer, User-Settings, or the Default Associations cpl" EDIT: I'm trying to further this investigation with more questions here: How to delete ProgIDs from other user accounts when uninstalling from Windows?
Alas, this documentation still seems current, and it's all about the registry: MSDN Maybe someone's created a nice wrapper for this? Time to hit Google...
2,828,765
2,828,790
Getting the compiler to perceive << as defined for a specific class
I edited a post of mine with this question, yet got no answers. I overloaded << for a class, Score (defined in score.h), in score.cpp. ostream& operator<< (ostream & os, const Score & right) { os << right.getPoints() << " " << right.scoreGetName(); return os; } (getPoints fetches an int attribute, getName a string one) I get this compiling error for a test in main(), contained in main.cpp binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion) How come the compiler doesn't 'recognize' that overload as valid? (includes are proper) Thanks for your time. EDIT: As requested, code causing the error: cout << ":::::\n" << jogador.getScore() << endl; jogador is a Player object, which contains a Score one. getScore returns that attribute.
Perhaps you didn't declare your operator<< in score.h? It should normally contain something like: ostream& operator<< (ostream & os, const Score & right); Edit: More accurately, that should be: std::ostream &operator<<(std::ostream &os, const Score &right); You definitely should not have a using namespace std; in a header, so you need the std:: for it to work correctly.
2,828,877
2,828,926
Boost Multithreading
Can anyone tell what's going on here? When I try debug the code and when the control is in thread() function at Line 15, it skips over the Line 16 move to Line 17 and goes back Line 16. Why wouldn't it move Line by Line? 1. #include <boost/thread.hpp> 2. #include <iostream> 3. 4. void wait(int seconds) 5. { 6. boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 7. } 8. 9. boost::mutex mutex; 10. 11. void thread() 12. { 13. for (int i = 0; i < 5; ++i) 14. { 15. wait(1); 16. mutex.lock(); 17. std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 18. mutex.unlock(); 19. } 20. } 21. 22. int main() 23. { 24. boost::thread t1(thread); 25. boost::thread t2(thread); 26. t1.join(); 27. t2.join(); 28. }
Possibly your debugger is actually stepping several threads in parallel which is why it appears to jump back and forth. Try printing the thread ID from your debugger and you'll probably see different numbers at each stop. Another reason for weird jumping in debug is if the code is optimized. If so, the source code order doesn't neccessairy match the compiled code
2,828,992
2,829,118
Can anybody explain to the meaning of this expression?
void* GetData() { return reinterpret_cast<unsigned char*>(this); } Is there a case of automatic type coercion happening in this case ??? How could I convert the object of my class to an unsigned char* ??
I agree with the other posts: this is almost certainly not what you intend to do. However, IIRC, you are guaranteed by the C++ standard to be able to convert a pointer of any type (not including function or member pointers) to an unsigned char * or a void * and back without entering the realm of undefined behavior. Additionally, you may access any object through an lvalue of type char * or unsigned char * (see ISO 14882:2003 section 3.10.15). I have made use of this before in order to inspect the internal representation of arbitrary object types. This results, if my reading of the standard is correct, in "implementation-defined behavior" (obviously, the internal representation of types depends upon the implementation). For example, template<class T> std::vector<unsigned char> to_bytes (const T& t) { const unsigned char *p = reinterpret_cast<const unsigned char *>(&t); return std::vector<unsigned char>(p, p + sizeof(T)); } is a template function that will yield a std::vector<unsigned_char> which is a copy of the object's internal representation. However, the fact that you cast to void * when you return makes me suspect you are doing something perhaps more unsavory and more undefined.
2,829,123
2,829,182
Help with enum values in registry c++
DWORD type = REG_NONE; int i = 0; size = sizeof(ValueName); size2 = sizeof(ValueData); BOOL bContinue = TRUE; do { lRet = RegEnumValue(Hkey , i , ValueName , &size , 0 , &type , ValueData , &size2); switch(lRet) { case ERROR_SUCCESS: print_values(ValueName , type , ValueData , size2); i++; size = sizeof(ValueName); size2 = sizeof(ValueData); break; case ERROR_MORE_DATA: size2 = sizeof(ValueData); if(NULL != ValueData) delete [] ValueData; ValueData = new BYTE[size2]; break; case ERROR_NO_MORE_ITEMS: bContinue = false; break; default: cout << "Unexpected error: " << GetLastError() << endl; bContinue = false; break; } }while(bContinue); it always goes to ERROR_NO_MORE_DATA ,why is that ? :-/ EDIT: sorry,i ment : ERROR_MORE_DATA:) i changed something,still doesnt work class Registry { public: Registry(); ~Registry(); bool open_key_ex(HKEY hkey, const char * key, HKEY & hkey_out); void querry_info_key(HKEY); void enum_key(HKEY , DWORD); void enum_value(HKEY); void print_values(LPCSTR , DWORD , LPBYTE , DWORD); void run(); private: HKEY hkey; long lRet; FILETIME filetime; DWORD sub_keys; TCHAR* ValueName; DWORD size; LPBYTE ValueData; DWORD size2; HKEY a; DWORD MaxValueLen; DWORD MaxDataLen; }; Registry::Registry() { ValueName = new TCHAR[MAX_PATH]; ValueData = NULL; MaxValueLen = MAX_PATH + 1; MaxDataLen = 0; } Registry::~Registry() { delete [] ValueName; } void Registry::enum_value(HKEY Hkey) { DWORD type = REG_NONE; int i = 0; size2 = MaxDataLen; BOOL bContinue = TRUE; do { lRet = RegEnumValue(Hkey , i , ValueName , &size , 0 , &type , ValueData , &size2); size = MaxValueLen; switch(lRet) { case ERROR_SUCCESS: print_values(ValueName , type , ValueData , size2); size2 = MaxDataLen; i++; break; case ERROR_MORE_DATA: MaxDataLen = size2; if(NULL != ValueData) delete [] ValueData; ValueData = new BYTE[MaxDataLen]; break; case ERROR_NO_MORE_ITEMS: bContinue = false; break; default: cout << "Unexpected error: " << GetLastError() << endl; bContinue = false; break; } }while(bContinue); }
I suspect it's related to this: size2 = sizeof(ValueData); Although I don't see a declaration for ValueData, it's apparent that it is a pointer, not an array. Therefore, sizeof will give you the size of a pointer rather than the size of the buffer it points to. You'll need to keep track of the size yourself. The same might be true of ValueName, but I can't tell. From http://msdn.microsoft.com/en-us/library/ms724865%28VS.85%29.aspx: If the buffer specified by lpData is not large enough to hold the data, the function returns ERROR_MORE_DATA and stores the required buffer size in the variable pointed to by lpcbData. In this case, the contents of lpData are undefined.
2,829,157
2,829,257
Why only random-access-iterator implements operator+ in C++?
I'd like get far next value for STL list iterator but it doesn't implement operator+, vector has it though. Why and how can I get the value where I want? I think I can do that if I call operator++ several times, but isn't that a little bit dirty? What I want to do is the following: list<int> l; ...omitted... list<int>::iterator itr = l.begin() + 3; // but, list iterator does not have // operator+ What is the best solution for what I want?
You can also use std::next (and prev) or the equivalents provided by Boost if you don't have access to C++11. list<int>::iterator itr = std::next(l.begin(), 3); Rationale: std::advance is awkward to use (it works by side-effect, not by returning a copy).
2,829,523
2,829,629
upgrading boost version
I'm using RHEL 5.3, shipped with gcc 4.1.2 and boost 1.33. So, there's no boost::unorded_map, no make_shared() factory function to create boost::shared_ptr and other features available in newer releases of boost. Is there're a newer version of boost compatible with the version of gcc? If yes, how the upgrade is performed?
Download the latest version (1.43.0) of the Boost libraries from the Boost website and follow the steps in the getting started guide, which explains how to build Boost on a number of platforms, including Linux.
2,829,563
2,829,609
inheriting from a class declarations in c++
When you want to inherit from a class in C++, is it illegal to have std declared in the first line below? #ifndef HWEXCEPTION_H #define HWEXCEPTION_H #include <stdexcept> class HWException : public std::run_time_error { void testException(int num); }; #endif vs using std::run_time_error class MyClass : public run_time_error This is assuming you have #include at the top. I get compile errors for having std::run_time_error, but do not seem to by doing it the second way and was wondering why. error C2039: 'run_time_error' : is not a member of 'std' 'run_time_error' : base class undefined 1>main.cpp error C2039: 'run_time_error' : is not a member of 'std' error C2504: 'run_time_error' : base class undefined
Both are legal. But assuming this is in a header file, you should not use the using directive version, as it places the name in the global namespace, which may cause problems for users of your header. Edit: Just noticed that you have the class name wrong: #include <stdexcept> class MyClass : public std::runtime_error { }; is what you need.
2,829,637
2,829,712
SOCKS in C/C++ or another language?
How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks
You could try Boost.Asio library. It contains an example with SOCKS4 protocol implementation.
2,829,966
2,830,580
error C2109: subscript requires array or pointer type
I am trying to debug some homework but I am having trouble with these lines of code #include "stdafx.h" #include<conio.h> #include<iostream> #include<string> using namespace std; int main() { char word; cout << "Enter a word and I will tell you whether it is" << endl << "in the first or last half of the alphabet." << endl << "Please begin the word with a lowercase letter. --> "; cin >> word; if(word[0] >= 'm') cout << word << " is in the first half of the alphabet" << endl; else cout << word << " is in the last half of the alphabet" << endl; return 0; } I get the following error and I have no clue what its sayings error C2109: subscript requires array or pointer type
Another suggestion: declare output text as one entity, then block write. This may make your programs easier to debug, read and understand. int main(void) { static const char prompt[] = "Enter a word and I will tell you whether it is\n" "in the first or last half of the alphabet.\n" "Please begin the word with a lowercase letter. --> "; string word; cout.write(prompt, sizeof(prompt) - sizeof('\0')); getline(cin, word); cout << word; cout << "is in the "; if(word[0] >= 'm') cout "first"; else cout << "last"; cout << " half of the alphabet\n"; return 0; } For Your Information (FYI): stdafx.h is not a standard header and not required for small projects. conio.h is not a standard header and not required for simple console I/O. Prefer string for text rather than char *.
2,829,972
2,830,140
Help configuring the log4cplus configuration file (properties file)
I created a new Logger object like this: log4cplus::Logger m_WebAccessLogger; //a class member Then in the constructor initialization list I do: m_WebAccessLogger(log4cplus::Logger::getInstance("WebAccess") This works fine, it logs as expected. What I'm having trouble with is, I want to configure the log4cplus.properties file so that everything for "WebAccess" will go to a separate log file (right now it goes to the default log file where everything else goes). I can't seem to find the documentation for how to configure these properties files, so I need help please! Here's my current log properties, how can I tell it to have "WebAccess" go to a different file? log4cplus.rootLogger=DEBUG, ROLLING log4cplus.appender.STDOUT=log4cplus::ConsoleAppender log4cplus.appender.STDOUT.layout=log4cplus::PatternLayout log4cplus.appender.STDOUT.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n log4cplus.appender.STDOUT.layout.ConversionPattern=%d{%H:%M:%S} [%t] - %m%n log4cplus.appender.ROLLING=log4cplus::RollingFileAppender log4cplus.appender.ROLLING.MaxFileSize=5MB log4cplus.appender.ROLLING.MaxBackupIndex=5 #log4cplus.appender.ROLLING.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n log4cplus.appender.ROLLING.layout=log4cplus::TTCCLayout log4cplus.appender.ROLLING.File=c:\projects\ArchiveService\IArchive.log Something like: WebAccess.File=c:\projects\ArchiveService\webaccess.log or log4cplus.WebAccess.File=webaccess.log I know log4cplus is simular to log4j, that why I put that as a Tag for this one.
I figured it out by guessing. log4cplus.rootLogger=DEBUG, ROLLING log4cplus.appender.STDOUT=log4cplus::ConsoleAppender log4cplus.appender.STDOUT.layout=log4cplus::PatternLayout log4cplus.appender.STDOUT.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n log4cplus.appender.STDOUT.layout.ConversionPattern=%d{%H:%M:%S} [%t] - %m%n log4cplus.appender.ROLLING=log4cplus::RollingFileAppender log4cplus.appender.ROLLING.MaxFileSize=5MB log4cplus.appender.ROLLING.MaxBackupIndex=5 #log4cplus.appender.ROLLING.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n log4cplus.appender.ROLLING.layout=log4cplus::TTCCLayout log4cplus.appender.ROLLING.File=c:\projects\ArchiveService\Debug\ImageArchive.log log4cplus.logger.WebAccess=DEBUG, R2 log4cplus.appender.R2=log4cplus::RollingFileAppender log4cplus.appender.R2.File=c:\projects\ArchiveService\Debug\webaccess.log log4cplus.appender.R2.MaxFileSize=5MB log4cplus.appender.R2.MaxBackupIndex=5 #log4cplus.appender.R2.layout=log4cplus::TTCCLayout
2,830,015
2,830,075
not able to use g++ from Fedora
$ yum list | grep gcc arm-gp2x-linux-gcc.i686 4.1.2-11.fc12 @fedora arm-gp2x-linux-gcc-c++.i686 4.1.2-11.fc12 @fedora gcc.i686 4.4.3-4.fc12 @updates libgcc.i686 4.4.3-4.fc12 @updates avr-gcc.i686 4.4.2-2.fc12 updates avr-gcc-c++.i686 4.4.2-2.fc12 updates compat-gcc-34.i686 3.4.6-18 fedora compat-gcc-34-c++.i686 3.4.6-18 fedora compat-gcc-34-g77.i686 3.4.6-18 fedora compat-libgcc-296.i686 2.96-143 fedora gcc-c++.i686 4.4.3-4.fc12 updates gcc-gfortran.i686 4.4.3-4.fc12 updates gcc-gnat.i686 4.4.3-4.fc12 updates gcc-java.i686 4.4.3-4.fc12 updates gcc-objc.i686 4.4.3-4.fc12 updates gcc-objc++.i686 4.4.3-4.fc12 updates mingw32-gcc.i686 4.4.1-3.fc12 fedora mingw32-gcc-c++.i686 4.4.1-3.fc12 fedora mingw32-gcc-gfortran.i686 4.4.1-3.fc12 fedora mingw32-gcc-objc.i686 4.4.1-3.fc12 fedora mingw32-gcc-objc++.i686 4.4.1-3.fc12 fedora msp430-gcc.i686 3.2.3-3.20090210cvs.fc12 $ gcc works fine on .c files but fails on .cpp files saying: $ gcc: error trying to exec 'cc1plus': execvp: No such file or directory g++ fails saying: $ g++: Command not found. What should I do to be able to compile C++ files?
gcc-c++ is not installed. The yum list command shows all packages, not just the installed packages. The packages that are installed are prefixed with an ampersand or "@" sign. The packages that are not installed (but are available to be installed) lack the ampersand. To see what is installed try the command rpm -qa. Or in your example rpm -qa | grep gcc Oddly enough, if you didn't just grep for gcc, you would have been able to see the "Installed packages" and "Available packages" output lines between the two sets.
2,830,149
2,830,360
How to track the memory usage in C++
I have a C++ program running under linux. Is it possible to track its memory usage from the code? I am allocating new objects and running out of memory, so I want to keep track of how quickly I am using memory. Thanks
Valgrinds module massif is exactly what you are looking for. http://valgrind.org/docs/manual/ms-manual.html
2,830,272
2,830,600
Critique my heap debugger
I wrote the following heap debugger in order to demonstrate memory leaks, double deletes and wrong forms of deletes (i.e. trying to delete an array with delete p instead of delete[] p) to beginning programmers. I would love to get some feedback on that from strong C++ programmers because I have never done this before and I'm sure I've done some stupid mistakes. Thanks! #include <cstdlib> #include <iostream> #include <new> namespace { const int ALIGNMENT = 16; const char* const ERR = "*** ERROR: "; int counter = 0; struct heap_debugger { heap_debugger() { std::cerr << "*** heap debugger started\n"; } ~heap_debugger() { std::cerr << "*** heap debugger shutting down\n"; if (counter > 0) { std::cerr << ERR << "failed to release memory " << counter << " times\n"; } else if (counter < 0) { std::cerr << ERR << (-counter) << " double deletes detected\n"; } } } instance; void* allocate(size_t size, const char* kind_of_memory, size_t token) throw (std::bad_alloc) { void* raw = malloc(size + ALIGNMENT); if (raw == 0) throw std::bad_alloc(); *static_cast<size_t*>(raw) = token; void* payload = static_cast<char*>(raw) + ALIGNMENT; ++counter; std::cerr << "*** allocated " << kind_of_memory << " at " << payload << " (" << size << " bytes)\n"; return payload; } void release(void* payload, const char* kind_of_memory, size_t correct_token, size_t wrong_token) throw () { if (payload == 0) return; std::cerr << "*** releasing " << kind_of_memory << " at " << payload << '\n'; --counter; void* raw = static_cast<char*>(payload) - ALIGNMENT; size_t* token = static_cast<size_t*>(raw); if (*token == correct_token) { *token = 0xDEADBEEF; free(raw); } else if (*token == wrong_token) { *token = 0x177E6A7; std::cerr << ERR << "wrong form of delete\n"; } else { std::cerr << ERR << "double delete\n"; } } } void* operator new(size_t size) throw (std::bad_alloc) { return allocate(size, "non-array memory", 0x5AFE6A8D); } void* operator new[](size_t size) throw (std::bad_alloc) { return allocate(size, " array memory", 0x5AFE6A8E); } void operator delete(void* payload) throw () { release(payload, "non-array memory", 0x5AFE6A8D, 0x5AFE6A8E); } void operator delete[](void* payload) throw () { release(payload, " array memory", 0x5AFE6A8E, 0x5AFE6A8D); }
Instead of doing intrusive note-keeping you could keep a list of all allocations made. Then you can free the memory without destroying your own data, and keep track of how many times a particular address is "deleted", and also find places where the program tries to delete a non-matching address (i.e. not in the list).
2,830,468
2,830,508
Need help with map (c++, STL)
Actually I'm new to C++. I tried something out (actually the map container) but it doesn't work the way I assumed it will... Before posting my code, I will explain it shortly. I created 3 classes: ClassA ClassDerivedA ClassAnotherDerivedA The two last ones are derived from "ClassA". Further I created a map: map<string,ClassA> test_map; I put some objects (from Type ClassDerivedA and ClassAnotherDerivedA) into the map. Keep in mind: the mapped value is from type "ClassA". This will only work because of Polymorphism. Finally I created an iterator which runs over my map and compares the user input with my keys in the map. If they match, it will call a specific method called "printOutput". And there is the Problem: Although i declared "printOutput" as "virtual" the only method called is the one from my base class, but why? and here is the code: #include <iostream> #include <map> using namespace std; class ClassA { public: virtual void printOutput() { cout << "ClassA" << endl; } }; class ClassDerivedA : public ClassA { public: void printOutput() { cout << "ClassDerivedA" << endl; } }; class ClassAnotherDerivedA: public ClassA { public: void printOutput() { cout << "ClassAnotherDerivedA" << endl; } }; int main() { ClassDerivedA class_derived_a; ClassAnotherDerivedA class_another_a; map<string,ClassA> test_map; test_map.insert(pair<string,ClassA>("deriveda", class_derived_a)); test_map.insert(pair<string,ClassA>("anothera", class_another_a)); string s; while( cin >> s ) { if( s != "quit" ) { map<string,ClassA>::iterator it = test_map.find(s); if(it != test_map.end()) it->second.printOutput(); } else break; } }
The problem is slicing. You are storing ClassA values in your map. When you store derived class instances into the map, the get sliced into ClassA objects. You'll need to store pointers in your map instead of values. See this for more info on slicing: What is object slicing?
2,830,587
2,830,606
Vector of pointers to base class, odd behaviour calling virtual functions
I have the following code #include <iostream> #include <vector> class Entity { public: virtual void func() = 0; }; class Monster : public Entity { public: void func(); }; void Monster::func() { std::cout << "I AM A MONSTER" << std::endl; } class Buddha : public Entity { public: void func(); }; void Buddha::func() { std::cout << "OHMM" << std::endl; } int main() { const int num = 5; // How many of each to make std::vector<Entity*> t; for(int i = 0; i < num; i++) { Monster m; Entity * e; e = &m; t.push_back(e); } for(int i = 0; i < num; i++) { Buddha b; Entity * e; e = &b; t.push_back(e); } for(int i = 0; i < t.size(); i++) { t[i]->func(); } return 0; } However, when I run it, instead of each class printing out its own message, they all print the "Buddha" message. I want each object to print its own message: Monsters print the monster message, Buddhas print the Buddha message. What have I done wrong?
You need to allocate the objects from the heap with 'new'. What's happening here is that you're creating temporary objects, taking the pointer to those objects, and then those objects are being destroyed. Yes, this is differerent from many other languages. :) Instead, try: int main() { const int num = 5; // How many of each to make std::vector<Entity*> t; for(int i = 0; i < num; i++) { Monster* m = new Monster; t.push_back(m); } for(int i = 0; i < num; i++) { Buddha* b = new Buddha; t.push_back(b); } for(int i = 0; i < t.size(); i++) { t[i]->func(); } // This is very important! for(int i = 0; i < t.size(); i++) { delete t[i]; } return 0; } When you see weird behavior like this, check to see the contents of the actual vector. You'd find that all of your slots had the same value, which is the spot on the stack that was holding the temporary monster then the temporary buddha.
2,830,622
2,836,732
How can I create a Base64-Encoded string from a GDI+ Image in C++?
I asked a question recently, How can I create an Image in GDI+ from a Base64-Encoded string in C++?, which got a response that led me to the answer. Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward. The crux of the issue is that an Image in GDI+ can save out its data to either a file or an IStream*. I don't want to save to a file, so I need to use the resulting stream. Problem is, this is where my knowledge breaks down. This first part is what I figured out in the other question // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); // I have this decode function from elsewhere std::string decodedImage = base64_decode(Base64EncodedImage); // Allocate the space for the stream DWORD imageSize = decodedImage.length(); HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize); LPVOID pImage = ::GlobalLock(hMem); memcpy(pImage, decodedImage.c_str(), imageSize); // Create the stream IStream* pStream = NULL; ::CreateStreamOnHGlobal(hMem, FALSE, &pStream); // Create the image from the stream Image image(pStream); // Cleanup pStream->Release(); GlobalUnlock(hMem); GlobalFree(hMem); (Base64 code) And now I'm going to perform an operation on the resulting image, in this case rotating it, and now I want the Base64-equivalent string when I'm done. // Perform operation (rotate) image.RotateFlip(Gdiplus::Rotate180FlipNone); IStream* oStream = NULL; CLSID tiffClsid; GetEncoderClsid(L"image/tiff", &tiffClsid); // Function defined elsewhere image.Save(oStream, &tiffClsid); // And here's where I'm stumped. (GetEncoderClsid) So what I wind up with at the end is an IStream* object. But here's where both my knowledge and Google break down for me. IStream shouldn't be an object itself, it's an interface for other types of streams. I'd go down the road from getting string->Image in reverse, but I don't know how to determine the size of the stream, which appears to be key to that route. How can I go from an IStream* to a string (which I will then Base64-Encode)? Or is there a much better way to go from a GDI+ Image to a string?
Got it std::string RotateImage(const std::string &Base64EncodedImage) { // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); std::string decodedImage = base64_decode(Base64EncodedImage); DWORD imageSize = decodedImage.length(); HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize); LPVOID pImage = ::GlobalLock(hMem); memcpy(pImage, decodedImage.c_str(), imageSize); IStream* pStream = NULL; ::CreateStreamOnHGlobal(hMem, FALSE, &pStream); Image image(pStream); image.RotateFlip(Gdiplus::Rotate180FlipNone); pStream->Release(); GlobalUnlock(hMem); GlobalFree(hMem); IStream* oStream = NULL; CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*)&oStream); CLSID tiffClsid; GetEncoderClsid(L"image/tiff", &tiffClsid); image.Save(oStream, &tiffClsid); ULARGE_INTEGER ulnSize; LARGE_INTEGER lnOffset; lnOffset.QuadPart = 0; oStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize); oStream->Seek(lnOffset, STREAM_SEEK_SET, NULL); char *pBuff = new char[(unsigned int)ulnSize.QuadPart]; ULONG ulBytesRead; oStream->Read(pBuff, (ULONG)ulnSize.QuadPart, &ulBytesRead); std::string rotated_string = base64_encode((const unsigned char*)pBuff, ulnSize.QuadPart); return rotated_string; } The trick, as inspired by what I got from this article, is knowing the method to finding out the size of the stream, and having it read it into a character array. Then I can feed that array to the base64_encode function and voilà.
2,830,698
2,830,756
Will the template argument's destructor to a templated class be called on deletion?
If you have a templated base class as in the following example: class A{ public: A(); virtual ~A(); }; template <class T> class B : public T { public: B(); virtual ~B(); }; typedef B<A> C; class D : public C { public: D(); virtual ~D(); }; When you delete an instance of D, will the destructor of A be called? I'll probably create a test program to find out what happens, but just thinking about it, I wasn't sure what should happen.
When you delete an instance of D, will the destructor of A be called? Yes. Nothing special here (except you have private access on everything, which means it probably won't compile).
2,830,708
2,830,723
Java Equivalent of C++ .dll?
So, I've been programming for a while now, but since I haven't worked on many larger, modular projects, I haven't come across this issue before. I know what a .dll is in C++, and how they are used. But every time I've seen similar things in Java, they've always been packaged with source code. For instance, what would I do if I wanted to give a Java library to someone else, but not expose the source code? Instead of the source, I would just give a library as well as a Javadoc, or something along those lines, with the public methods/functions, to another programmer who could then implement them in their own Java code. For instance, if I wanted to create a SAX parser that could be "borrowed" by another programmer, but (for some reason--can't think of one in this specific example lol) I don't want to expose my source. Maybe there's a login involved that I don't want exploited--I don't know. But what would be the Java way of doing this? With C++, .dll files make it much easier, but I have never run into a Java equivalent so far. (I'm pretty new to Java, and a pretty new "real-world" programmer, in general as well)
Java .jar library is the Java equivalent of .dll, and it also has "Jar hell", which is the Java version of "dll hell" http://en.wikipedia.org/wiki/JAR_(file_format)
2,830,941
2,830,992
Speed comparison - Template specialization vs. Virtual Function vs. If-Statement
Just to get it out of the way... Premature optimization is the root of all evil Make use of OOP etc. I understand. Just looking for some advice regarding the speed of certain operations that I can store in my grey matter for future reference. Say you have an Animation class. An animation can be looped (plays over and over) or not looped (plays once), it may have unique frame times or not, etc. Let's say there are 3 of these "either or" attributes. Note that any method of the Animation class will at most check for one of these (i.e. this isn't a case of a giant branch of if-elseif). Here are some options. 1) Give it boolean members for the attributes given above, and use an if statement to check against them when playing the animation to perform the appropriate action. Problem: Conditional checked every single time the animation is played. 2) Make a base animation class, and derive other animations classes such as LoopedAnimation and AnimationUniqueFrames, etc. Problem: Vtable check upon every call to play the animation given that you have something like a vector<Animation>. Also, making a separate class for all of the possible combinations seems code bloaty. 3) Use template specialization, and specialize those functions that depend on those attributes. Like template<bool looped, bool uniqueFrameTimes> class Animation. Problem: The problem with this is that you couldn't just have a vector<Animation> for something's animations. Could also be bloaty. I'm wondering what kind of speed each of these options offer? I'm particularly interested in the 1st and 2nd option because the 3rd doesn't allow one to iterate through a general container of Animations. In short, what is faster - a vtable fetch or a conditional?
(1) Not that the size of the generated assembly matters anymore these days, but this is what it generates (approximately, assuming MSVC on x86): mov eax, [ecx+12] ; 'this' pointer stored in ecx, eax is scratch cmp eax, 0 ; test for 0 jz .somewhereElse ; jump if the bool isn't set The optimizing compiler will intersperse other instructions there, making it more pipeline-friendly. The contents of your class will most likely be in your cache anyway, and if it's not, it will be needed a few cycles later anyway. So, in retrospect, that's maybe a few cycles, and for something that will be called at most a few times per frame, that's nothing. (2) This is approximately the assembly that will be generated every time your play() method is called: mov eax, [ebp+4] ; pointer to your Animation* somewhere on the stack, eax is scratch mov eax, [eax+12] ; dereference the vtable call eax ; call it Then, you'll have some duplicate code or another function call inside your specialized play() function, since there'll definetely be some common stuff, so that incurs some overhead (in code size and/or execution speed). So, this is definetely slower. Also, this makes it alot harder to load generic animations. Your graphics department won't be happy. (3) To use this effectively, you'll end up making a base class for your templated version anyway, with virtual functions (in that case, see (2)), OR you'll do it manually by checking types in places where you call your animation thing, in which case also see (2). This also makes it MUCH harder to load generic animations. Your graphics department will be even less happy. (4) What you need to worry about is not some microoptimization for tiny things done at most a few times a frame. From reading your post, i actually identified another problem that's commonly overlooked. You're mentioning std::vector<Animation>. Nothing against the STL, but that's bad voodoo. A single memory allocation will cost you more cycles than all the boolean checks in your play() or update() methods for probably the entire time your application is running. Putting Animations in and out of std::vectors (especially if you're putting in instances and not pointers (smart or dumb) to instances) will cost you way more. You need to look at different places to optimize. This is such a ridiculous microoptimization that will bring you no benefit except make it harder to generalize and make your graphics department happy. What will matter, however, is worrying about memory allocation, and THEN, when you're done programming that part, starting a profiler and looking where the hot spots are. If keeping your animations is actually becoming a bottleneck, the std::vector (nice as it is) is where you might want to look. Have you looked at, say, an intrusive linked list? That will actually be more benefit than worrying about this.
2,830,954
2,831,047
Boost thread synchronization in release build
when I try to run the following code in debug and release mode in VS2005. Each time I see different output in console and It doesn't seem like the multithreading is achieved in release mode. 1. #include <boost/thread.hpp> 2. #include <iostream> 3. 4. void wait(int seconds) 5. { 6. boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 7. } 8. 9. boost::mutex mutex; 10. 11. void thread() 12. { 13. for (int i = 0; i < 5; ++i) 14. { 15. //wait(1); 16. mutex.lock(); 17. std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 18. mutex.unlock(); 19. } 20. } 21. 22. int main() 23. { 24. boost::thread t1(thread); 25. boost::thread t2(thread); 26. t1.join(); 27. t2.join(); 28. } Debug Mode Thread 00153E60: 0 Thread 00153E90: 0 Thread 00153E60: 1 Thread 00153E90: 1 Thread 00153E90: 2 Thread 00153E60: 2 Thread 00153E90: 3 Thread 00153E60: 3 Thread 00153E60: 4 Thread 00153E90: 4 Press any key to continue . . . Release Mode Thread 00153D28: 0 Thread 00153D28: 1 Thread 00153D28: 2 Thread 00153D28: 3 Thread 00153D28: 4 Thread 00153D58: 0 Thread 00153D58: 1 Thread 00153D58: 2 Thread 00153D58: 3 Thread 00153D58: 4 Press any key to continue . . .
If you uncomment the call to wait(), it is evident that both threads are running at the same time. Likewise, if you increase the number of times the loop is run to 1,000, you can see the threads are interleaved (well, 1,000 on my computer; it might take more or less). Remember that a release build is optimized, so tasks almost always take less time and threads may end up scheduled differently in a release build than in a debug build.
2,831,039
2,831,061
Visual Studio 2008 awful performance
I have ported a piece of C++ code, that works out of core, from Linux(Ubuntu) to Windows(Vista) and I realized that it works about 50times slower on VS2008! I removed all the out of core parts and now I just have a piece of code that has nothing to do with the hard disk. I set compiler parameters to O2 in Project Properties but still get about 10times slower than g++ in linux! Does anybody have an idea why it is this much slower under VS? I really appreciate any kind of hint! Thanks,
Do you use a lot of the standard C++ library? If so, you might want to turn off the "checked iterators" feature that is on by default in Visual C++ (even in Release mode). Put this before including any standard headers: #define _SECURE_SCL 0 More info here.
2,831,247
2,831,354
C++ using typedefs in non-inline functions
I have a class like this template< typename T > class vector { public: typedef T & reference; typedef T const & const_reference; typedef size_t size_type; const_reference at( size_t ) const; reference at( size_t ); and later in the same file template< typename T > typename vector<T>::const_reference // Line X vector<T>::at( size_type i ) const { rangecheck(); return elems_[ i ]; } template< typename T > reference // Line Y vector<T>::at( size_type i ) { rangecheck(); return elems_[ i ]; } Line X compiles fine but Line Y does not compile. The error message from g++ (version 4.4.1) is: foo.h:Y: error: expected initializer before 'vector' From this I gather that, if I want to have non-inline functions then I have to fully qualify the typedef name as in Line X. (Note that, there is no problem for size_type.) However, at least to me, Line X looks clumsy. Is there any alternative approach?
Yes, in out-of-class member function definition you have to use a fully-qualified name for the nested return type. This, BTW, has nothing to do with templates. It is that way with non-template classes as well. In your case it is a template class and, as a consequence of that, since you are using a qualified name to refer to a nested type in a dependent template class, you have to prepend it with keyword typename. However, you only need to qualify the return type. Parameter types don't need to be qualified template< typename T > typename vector<T>::const_reference vector<T>::some_method( const_reference r ) const { // ... } You can choose to use a qualified name for the parameter type as well, but in that case you will have to do the same thing as with the return type (for the very same reason): prepend it with typename keyword template< typename T > typename vector<T>::const_reference vector<T>::some_method( typename vector<T>::const_reference r ) const { // ... }
2,831,253
2,831,302
Using boost::asio::async_read with stdin?
short question: I have a realtime-simulation which is running as a backround process and is connected with pipes to the calling pogramm. I want to send commands to that process using stdin to get certain information from it via stdout. Now because it is a real-time process, it has to be a non blocking input. Is boost::asio::async_read in conjunction with iostream::cin a good idea for this task? how would I use that function if it is feasible? Any more suggestions?
Look at boost::asio::posix::stream_descriptor http://www.boost.org/doc/libs/release/doc/html/boost_asio/example/cpp03/chat/posix_chat_client.cpp
2,831,257
2,831,570
Why would the assignment operator ever do something different than its matching constructor?
I was reading some boost code, and came across this: inline sparse_vector &assign_temporary(sparse_vector &v) { swap(v); return *this; } template<class AE> inline sparse_vector &operator=(const sparse_vector<AE> &ae) { self_type temporary(ae); return assign_temporary(temporary); } It seems to be mapping all of the constructors to assignment operators. Great. But why did C++ ever opt to make them do different things? All I can think of is scoped_ptr?
why did C++ ever opt to make them do different things? Because assignment works on a fully constructed object. In resource managing classes, this means that every member pointer already points to a resource. Contrast this to a constructor, where the members don't have any meaning prior to executing it. By the way, in the very early days of C++, T a(b); was actually defined as T a; a = b;, but this proved to be inefficient, hence the introduction of the copy constructor.
2,831,280
2,831,307
Only compiles as an array of pointers, not array of arrays
Suppose I define two arrays, each of which have 2 elements (for theoretical purposes): char const *arr1[] = { "i", "j" }; char const *arr2[] = { "m", "n" }; Is there a way to define a multidimensional array that contains these two arrays as elements? I was thinking of something like the following, but my compiler displays warnings about incompatible types: char const *combine[][2] = { arr1, arr2 }; The only way it would compile was to make the compiler treat the arrays as pointers: char const *const *combine[] = { arr1, arr2 }; Is that really the only way to do it or can I preserve the type somehow (in C++, the runtime type information would know it is an array) and treat combine as a multidimensional array? I realise it works because an array name is a const pointer, but I'm just wondering if there is a way to do what I'm asking in standard C/C++ rather than relying on compiler extensions. Perhaps I've gotten a bit too used to Python's lists where I could just throw anything in them...
No. First, this char const *combine[][2] = { arr1, arr2 }; cannot work, because arr1 and arr2 cannot be used to initialize an array. But this: char const *arr1[] = { "i", "j" }; char const *arr2[] = { "m", "n" }; char const *(*combine[])[2] = { &arr1, &arr2 }; works as well as this char const *arr1[] = { "i", "j" }; char const *arr2[] = { "m", "n" }; char const *combine[][2] = { {"i", "j"}, {"m", "n"} };
2,831,323
2,831,366
STL list - how to find a list element by its object fields
I have a list: list<Unit *> UnitCollection; containing Unit objects, which has an accessor like: bool Unit::isUnit(string uCode) { if(this->unitCode == uCode) return true; else return false; } How do I search my UnitCollection list by uCode and return the corresponding element (preferably and iterator). In pseudo code it would look something like this: for every item in my UnitCollection: if the unit.isUnit(someUnitIpass) do something else next unit I have looked at the find() method, but i'm not sure you can pass a boolean method in instead of a searched item parameter if that makes sense.
You could have a look at find_if as jpalecek suggests, and then use distance to find the distance between the iterator returned from find_if and UnitCollection.begin(), and that distance should be the index of the element in the list. And as for the predicate, you could write a function object like this: struct predicate { predicate( const std::string &uCode ) : uCode_(uCode) {} bool operator() ( Unit *u ) { return u->isUnit( uCode_ ) } private: std::string uCode_; }; And then use it like this: predicate pred("uCode"); std::list<Unit*>::iterator i; i = std::find_if( UnitCollection.begin(), UnitCollection.end(), pred ); Or at least I think that would be a way to do it.
2,831,438
2,831,452
Using mem_fun_ref with boost::shared_ptr
Following the advice of this page, I'm trying to get shared_ptr to call IUnknown::Release() instead of delete: IDirectDrawSurface* dds; ... //Allocate dds return shared_ptr<IDirectDrawSurface>(dds, mem_fun_ref(&IUnknown::Release)); error C2784: 'std::const_mem_fun1_ref_t<_Result,_Ty,_Arg> std::mem_fun_ref(_Result (__thiscall _Ty::* )(_Arg) const)' : could not deduce template argument for '_Result (__thiscall _Ty::* )(_Arg) const' from 'ULONG (__cdecl IUnknown::* )(void)' error C2784: 'std::const_mem_fun_ref_t<_Result,_Ty> std::mem_fun_ref(_Result (__thiscall _Ty::* )(void) const)' : could not deduce template argument for '_Result (__thiscall _Ty::* )(void) const' from 'ULONG (__cdecl IUnknown::* )(void)' error C2784: 'std::mem_fun1_ref_t<_Result,_Ty,_Arg> std::mem_fun_ref(_Result (__thiscall _Ty::* )(_Arg))' : could not deduce template argument for '_Result (__thiscall _Ty::* )(_Arg)' from 'ULONG (__cdecl IUnknown::* )(void)' error C2784: 'std::mem_fun_ref_t<_Result,_Ty> std::mem_fun_ref(_Result (__thiscall _Ty::* )(void))' : could not deduce template argument for '_Result (__thiscall _Ty::* )(void)' from 'ULONG (__cdecl IUnknown::* )(void)' error C2661: 'boost::shared_ptr::shared_ptr' : no overloaded function takes 2 arguments I have no idea what to make of this. My limited template/functor knowledge led me to try typedef ULONG (IUnknown::*releaseSignature)(void); shared_ptr<IDirectDrawSurface>(dds, mem_fun_ref(static_cast<releaseSignature>(&IUnknown::Release))); But to no avail. Any ideas?
Isn't the calling convention specifier a problem? Would this be OK? void iUnk_delete(IUnknown* u) { u->Release(); } return shared_ptr<IDirectDrawSurface>(dds, iUnk_delete);
2,831,465
2,831,533
Can two separate pointers reference the same address? If so, can I change the value at that address with either pointer?
So, I have this code fragment: int * iPtr ; int * jPtr ; int i = 5, k = 7; iPtr = &i; jPtr = iPtr ; I have just started learning about pointers, and need to get some doubts cleared. is jPtr now essentially also pointing at i? I know I can change the value of i by using *iPtr, but how can I change the value of the object being pointed to by jPtr? How will changing the object being pointed to by jPtr affect the value of the object pointed to by iPtr, and i ?
1000 1001 1002 1004 --> address location ( note: just indicative) ---------------------------- | 5 | 7 | 1000 | 1000 | | i | j | iPtr | jPtr | ----------------------------- ^^ | | ||________| | |_________________| iPtr=&i; --> iPtr points to i ==> address of i is stored in iPtr ==> *iPtr contents of i jPtr=iPtr; ->jPtr points to i
2,831,505
2,831,753
Swapping values using pointers
I have this code fragment int i = 5; int k = 7; int * iPtr; int * jPtr; int * kPtr; iPtr = &i; kPtr = &k; I am required to swap i and k using the pointers. This is how I'm doing it: *jPtr = *kPtr ; *kPtr = *iPtr ; *iPtr = *jPtr ; Is this the best way to do it, or is there a better way?
The best way to do that in C++, in my opinion, is with std::iter_swap(): #include<algorithm> // ... int *iPtr = &i, *kPtr = &k; std::iter_swap(iPtr, kPtr); You may think that's an overkill, but I'd disagree if you include <algorithm> anyway. Of course, in the case of a homework this answer only holds if the instructor's intent is to familiarize you with the STL. If the intent is to introduce you to pointers then the best solution is to introduce a temporary variable, j: int j; int *iPtr = &i, *kPtr = &k, *jPtr = &j; *jPtr = *kPtr; *kPtr = *iPtr; *iPtr = *jPtr;
2,831,841
2,831,868
How to get the time in milliseconds in C++
In Java you can do this: long now = (new Date()).getTime(); How can I do the same but in C++?
There is no such method in standard C++ (in standard C++, there is only second-accuracy, not millisecond). You can do it in non-portable ways, but since you didn't specify I will assume that you want a portable solution. Your best bet, I would say, is the boost function microsec_clock::local_time().
2,831,978
2,832,880
Performing full screen grab in windows
I am working on an idea that involves getting a full capture of the screen including windows and apps, analyzing it, and then drawing items back onto the screen, as an overlay. I want to learn image processing techniques and I could get lots of data to work with if I can directly access the Windows screen. I could use this to build automation tools the likes of which have never been seen before. More on that later. I have full screen capture working for the most part. HWND hwind = GetDesktopWindow(); HDC hdc = GetDC(hwind); int resx = GetSystemMetrics(SM_CXSCREEN); int resy = GetSystemMetrics(SM_CYSCREEN); int BitsPerPixel = GetDeviceCaps(hdc,BITSPIXEL); HDC hdc2 = CreateCompatibleDC(hdc); BITMAPINFO info; info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); info.bmiHeader.biWidth = resx; info.bmiHeader.biHeight = resy; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = BitsPerPixel; info.bmiHeader.biCompression = BI_RGB; void *data; hbitmap = CreateDIBSection(hdc2,&info,DIB_RGB_COLORS,(void**)&data,0,0); SelectObject(hdc2,hbitmap); Once this is done, I can call this repeatedly: BitBlt(hdc2,0,0,resx,resy,hdc,0,0,SRCCOPY); The cleanup code (I have no idea if this is correct): DeleteObject(hbitmap); ReleaseDC(hwind,hdc); if (hdc2) { DeleteDC(hdc2); } Every time BitBlt is called it grabs the screen and saves it in memory I can access thru data. Performance is somewhat satisfactory. BitBlt executes in 50 milliseconds (sometimes as low as 33ms) at 1920x1200x32. What surprises me is that when I switch display mode to 16 bit, 1920x1200x16, either through my graphics settings beforehand, or by using ChangeDisplaySettings, I get a massively improved screen grab time between 1ms and 2ms, which cannot be explained by the factor of two reduction in bit-depth. Using CreateDIBSection (as above) offers a significant speed up when in 16-bit mode, compared to if I set up with CreateCompatibleBitmap (6-7ms/f). Does anybody know why dropping to 16bit causes such a speed increase? Is there any hope for me to grab 32bit at such speeds? if not for the color depth, but for not forcing a change of screen buffer modes and the awful flickering.
I solved my original question about the incredible speed up of switching to 16 bit color mode. Turns out it was causing the Aero theme to be disabled, which accounts for most of it. With Aero off in 32bit it is just about as fast. Link to other topic with a good answer.
2,832,018
2,832,025
Multiple inclusion of header file c++
I have a problem regarding multiple inclusion of header file in C++ code. Say for example, I have three classes X, Y, Z. X and Y are derived from base class Z. And I want to create an instance of X in Y. The code will go like this. class Z { …some code… }; class X: public Z { …some code… }; //here #include header of class Z added class Y: public Z //here #include header of class Z added as well as of X class { private: X* mX; //instance of X …some code… }; So in this multiple definition of all methods of base class arises. How can I cope with this problem?
Using "include guards" (Wikipedia link) #ifndef MYHEADER_H #define MYHEADER_H // header file contents go here... #endif // MYHEADER_H This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change MYHEADER_H to something specific to you, for example if the header defines a class named CustomerAccount, you can call the guard CUSTOMERACCOUNT_H. In your specific case, have a separate header/source file for each class. The header file for the Z class will have an include guard: #ifndef Z_H #define Z_H // Code of Z class #endif Z_H Now, the headers of both X and Y can include z.h safely - it will only really be included once in a .cpp file that includes both x.h and y.h and no duplication will occur. Always keep in mind that in C and C++ what's really gets compiled are the source (.c or .cpp) files, not the header files. The header files are just "copy-pasted" by the preprocessor into the sources files that include them.
2,832,023
2,832,511
C++ map performance - Linux (30 sec) vs Windows (30 mins) !
I need to process a list of files. The processing action should not be repeated for the same file. The code I am using for this is - using namespace std; vector<File*> gInputFileList; //Can contain duplicates, File has member sFilename map<string, File*> gProcessedFileList; //Using map to avoid linear search costs void processFile(File* pFile) { File* pProcessedFile = gProcessedFileList[pFile->sFilename]; if(pProcessedFile != NULL) return; //Already processed foo(pFile); //foo() is the action to do for each file gProcessedFileList[pFile->sFilename] = pFile; } void main() { size_t n= gInputFileList.size(); //Using array syntax (iterator syntax also gives identical performance) for(size_t i=0; i<n; i++){ processFile(gInputFileList[i]); } } The code works correctly, but... My problem is that when the input size is 1000, it takes 30 minutes - HALF AN HOUR - on Windows/Visual Studio 2008 Express. For the same input, it takes only 40 seconds to run on Linux/gcc! What could be the problem? The action foo() takes only a very short time to execute, when used separately. Should I be using something like vector::reserve for the map? EDIT, EXTRA INFORMATION What foo() does is: 1. it opens the file 2. reads it into memory 3. closes the file 4. the contents of the file in memory is parsed 5. it builds a list of tokens; I'm using a vector for that. Whenever I break the program (while running the program with the 1000+ files input set): the call-stack shows that the program is in the middle of a std::vector add.
In the Microsoft Visual Studio, there's a global lock when accessing the Standard C++ Library to protect from multi threading issue in Debug builds. This can cause big performance hits. For instance, our full test code runs on Linux/gcc in 50 minutes, whereas it needs 5 hours on Windows VC++2008. Note that this performance hit does not exist when compiling in Release mode, using the non-debug Visual C++ runtime.
2,832,088
2,832,119
how to call operator () in c++
in c++ i have following code class Foobar{ public: Foobar * operator()(){ return new Foobar; }; My quesion is how to call the (); if i do Foobar foo() the constructor gets called i am confused about behaviour of () can some explain me
While GMan's answer is factually correct, you should never overload an operator to do something unexpected - this goes against all good-practice programming rules. When a user reads code he expects operators to behave in some way, and making them behave differently is good only for obfuscating coding competitions. The () operator in C++ can be used to make an object represent a function. This actually has a name - it's called functor, and is used extensively in the STL to provide generic algorithms. Google for stl functor to learn about a good usage of the technique.
2,832,263
2,832,282
In game programming are global variables bad?
I know my gut reaction to global variables is "badd!" but in the two game development courses I've taken at my college globals were used extensively, and now in the DirectX 9 game programming tutorial I am using (www.directxtutorial.com) I'm being told globals are okay in game programming ...? The site also recommends using only structs if you can when doing game programming to help keep things simple. I'm really confused on this issue, and all the research I've been trying to do is very confusing. I realize there are issues when using global variables (threading issues, they make code harder to maintain, the state of them is hard to track etc) but also there is a cost associated with not using globals, I'd have to pass a loooot of information around very often which can be confusing and I imagine time-costing, although I guess pointers would speed the process up (this is my first time writing a game in C++.) Anyway, I realize there is probably no "right" or "wrong" answer here since both ways work, but I want my code to be as proper as I can so any input would be good, thank you very much!
The trouble with games and globals is that games (nowadays) are threaded at engine level. Game developers using an engine use the engine's abstractions rather than directly programming concurrency (IIRC). In many of the highlevel languages such as C++, threads sharing state is complex. When many concurrent processes share a common resource they have to make sure they don't tread on eachother's toes. To get around this, you use concurrency control such as mutex and various locks. This in effect makes asynchronous critical sections of code access shared state in a synchronous manner for writing. The topic of concurrency control is too much to explain fully here. Suffice to say, if threads run with global variables, it makes debugging very hard, as concurrency bugs are a nightmare (think, "which thread wrote that? Who holds that lock?"). There are exceptions in games programming API such as OpenGL and DX. If your shared data/globals are pointers to DX or OpenGL graphics contexts then typically this maps down to GPU operations which don't suffer so much from the same trouble. Just be careful. Keeping objects representing 'player' or 'zombie' or whatever, and sharing them between threads can be tricky. Spawn 'player' threads and 'zombie group' threads instead and have a robust concurrency abstraction between them based on message passing rather than accessing those object's state across the thread/critical section boundary. Saying all that, I do agree with the "Say no to globals" point made below. For more on the complexities of threads and shared state see: 1 POSIX Threads API - I know it is POSIX, but provides a good idea that translates to other API 2 Wikipedia's excellent range of articles on concurrency control mechanisms 3 The Dining Philosopher's problem (and many others) 4 ThreadMentor tutorials and articles on threading 5 Another Intel article, but more of a marketing thing. 6 An ACM article on building multi-threaded game engines
2,832,485
2,837,660
zlib gzgets extremely slow?
I'm doing stuff related to parsing huge globs of textfiles, and was testing what input method to use. There is not much of a difference using c++ std::ifstreams vs c FILE, According to the documentation of zlib, it supports uncompressed files, and will read the file without decompression. I'm seeing a difference from 12 seconds using non zlib to more than 4 minutes using zlib.h This I've tested doing multiple runs, so its not a disk cache issue. Am I using zlib in some wrong way? thanks #include <zlib.h> #include <cstdio> #include <cstdlib> #include <fstream> #define LENS 1000000 size_t fg(const char *fname){ fprintf(stderr,"\t-> using fgets\n"); FILE *fp =fopen(fname,"r"); size_t nLines =0; char *buffer = new char[LENS]; while(NULL!=fgets(buffer,LENS,fp)) nLines++; fprintf(stderr,"%lu\n",nLines); return nLines; } size_t is(const char *fname){ fprintf(stderr,"\t-> using ifstream\n"); std::ifstream is(fname,std::ios::in); size_t nLines =0; char *buffer = new char[LENS]; while(is. getline(buffer,LENS)) nLines++; fprintf(stderr,"%lu\n",nLines); return nLines; } size_t iz(const char *fname){ fprintf(stderr,"\t-> using zlib\n"); gzFile fp =gzopen(fname,"r"); size_t nLines =0; char *buffer = new char[LENS]; while(0!=gzgets(fp,buffer,LENS)) nLines++; fprintf(stderr,"%lu\n",nLines); return nLines; } int main(int argc,char**argv){ if(atoi(argv[2])==0) fg(argv[1]); if(atoi(argv[2])==1) is(argv[1]); if(atoi(argv[2])==2) iz(argv[1]); }
I guess you are using zlib-1.2.3. In this version, gzgets() is virtually calling gzread() for each byte. Calling gzread() in this way has a big overhead. You can compare the CPU time of calling gzread(gzfp, buffer, 4096) once and of calling gzread(gzfp, buffer, 1) for 4096 times. The result is the same, but the CPU time is hugely different. What you should do is to implement buffered I/O for zlib, reading ~4KB data in a chunk with one gzread() call (like what fread() does for read()). The latest zlib-1.2.5 is said to be significantly improved on gzread/gzgetc/.... You may try that as well. As it is released very recently, I have not tried personally. EDIT: I have tried zlib-1.2.5 just now. gzgetc and gzgets in 1.2.5 are much faster than those in 1.2.3.
2,832,714
2,832,754
Header files inclusion / Forward declaration
In my C++ project when do I have to use inclusion (#include "myclass.h") of header files? And when do I have to use forward declaration of the class (class CMyClass;)?
As a rule try the forward declaration first. This will reduce compile times etc. If that doesn't compile go for the #include. You have to go for the #include if you need to do any of the following: Access a member or function of the class. Use pointer arithmetic. Use sizeof. Any RTTI information. new/delete, copy etc. Use it by value. Inherit from it. Have it as a member. Instance in a function. (6,7,8,9 from @Mooing Duck) They're are probably more but I haven't got my language law hat on today.
2,832,818
2,833,651
Class destructor memory handling in C++
What potential memory leaks won't an implicit destructor handle? I know that if you have anything stored on the heap it won't handle it, and if you have a connection to a file or a database, that needs to be handled manually. Is there anything else? What about, say, non-base data types like vectors? Also, in an explicit destructor, need you destroy non-heap variables which would have been destroyed by the implicit, or are they handled automatically? Thanks
What potential memory leaks won't an implicit destructor handle? I know that if you have anything stored on the heap it won't handle it, and if you have a connection to a file or a database, that needs to be handled manually. Is there anything else? What about, say, non-base data types like vectors? To put it simply, you are correct. The only thing not handled by the implicit destructor is memory allocated in the form of a pointer or another type of resource that needs to be released explicitly. With regard to vectors or any other class type objects; all classes have a destructor which takes care of releasing their data. The destructor of an object of this type is called when it goes out of scope. All basic data types like: int, float, double, short, bool etc are released in similar fashion. Also, in an explicit destructor, need you destroy non-heap variables which would have been destroyed by the implicit, or are they handled automatically? The answer to this is that they are handled automatically, in fact you should never ever try to explicitly call the destructor of an object. In an implicit destructor the following occurs: Each of the member variables of the class have their destructors called in turn. In an explicit destructor the following occurs: The body of the explicit destructor is executed Each of the member variables of the class have their destructors called in turn. So you can see that an explicit destructor is much the same as an implicit one, except that you can take any necessary manual intervention. Now as a bit of advice with regard to managing memory allocated objects you should pretty much always use RAII (resource acquisition is initialisation). The crux of this is smart pointers, these are pointers that are deleted correctly when they go out of scope just like non heap allocated objects. Ownership becomes an issue once you start using them but that's a story for another day. A good place to start with smart pointers is boost::shared_ptr. (btw if you haven't got on board with boost yet and you write c++ code do yourself a favour...)
2,832,932
2,834,122
how to rebuilt a specific dependent library with /MD mode in c++ VS2005?
One of my specific dependent library is built with /ML. How to rebuil it with /MD? Thanks in advance!
Rebuild it: You need the source code and Visual C++ projects/solution used to build the library, and change the setting in the project settings. If you don't have the VC++ projects, you can create them and configure them by hand. More work. The worst is the case when you don't have the source code of that library... that would be a problem, because you don't have what to rebuild. Later edit Go to project properties/C++/Code Generation and select the option from there (Runtime library).
2,833,011
2,833,071
How to check number?
Could anyone please tell me how to check what number I've got from a * b? Which is I would like to know every part of this number so for example if the result from this expression would be 25 I would like to know that first digit is two and second digit is five.
perhaps a little overkill... but even works with doubles #include <sstream> #include <iostream> int main() { double a = 5.2; double b = 7; double z = a*b; std::stringstream s; s << z; for (int i = 0; i < s.str().length(); i++) std::cout << i << ": " << s.str()[i] << std::endl; return 0; }
2,833,039
2,833,078
Can't Display Bitmap of Higher Resolution than CDC area
Hi there dear gurus and expert coders. i am not gonna start with im a newbie and don't know much about image programming but unfortunately those are the facts :( I am trying to display an image from a bitmap pointer *ImageData which is of resolution 1392x1032. I am trying to draw that at an area of resolution or size 627x474. However, repeated trying doesnt seem to work. It works when I change the bitmap image I created from *ImageData width and height to resolution or size of around 627x474 I really do not know how to solve this after trying all possible solutions from various forums and google. pDC is a CDC* and memDC is a CDC initialized in an earlier method Anything uninitialized here was initialized in other methods. Here is my code dear humble gurus. Do provide me with guidance Yoda and Obi-Wan provided to Luke Skywalker. void DemoControl::ShowImage( void *ImageData ) { int Width; //Width of Image From Camera int Height; //Height of Image From Camera int m_DisplayWidth = 627 ;//width of rectangle area to display int m_DisplayHeight = 474;//height of rectangle area to display GetImageSize( &Width, &Height ) ; //this will return Width = 1392, Height 1032 CBitmap bitmap; bitmap.CreateBitmap(Width,Height,32,1,ImageData); CBitmap* pOldBitmap = memDC.SelectObject((CBitmap*)&bitmap); pDC->BitBlt(22, 24, 627, 474, &memDC, 0, 0, SRCCOPY); memDC.SelectObject((CBitmap*)pOldBitmap); ReleaseDC(pDC); } Ok heres some additional parts I think i should explain how the flow goes. (a) A class (lets say DemoTestingDlg class) will pass the CDC as below to another class (lets say DemoControl class) m_Demo = new DemoControl ; m_Demo->Initialisation( this, this->GetDC() ) ; (b) At the DemoControl class bool DemoControl::Initialisation( CDemoTestingDlg m_FormControl, CDC m_StaticDisplay ) { pDC = m_StaticDisplay ; memDC.CreateCompatibleDC(pDC); } pDC and memDC is as such in the header: CDC* pDC ; CDC memDC; (c) If lets say an image is captured, the image pointer is passed to the DemoTestingDlg class which will subsequently call a showImage method in the Demo Control Class which is the method I wrote in the question. Am i doing it right? Note: It did show an image if lets say they are of the same size (by they i mean the CDC and bitmap) so i was under the impression that my CDC pointer was passed correctly
StretchBlt is your friend :) Edit: OK how do you get pDC? When is your function called? Form OnPaint or DrawItem? This is a StretchBlt I do from a DrawItem call in an overriden CStatic. HDC hBitmapDC = CreateCompatibleDC( pDrawItemStruct->hDC ); HBITMAP hBitmap = GetBitmap(); HGDIOBJ hOld = SelectObject( hBitmapDC, (HGDIOBJ)hBitmap ); StretchBlt( pDrawItemStruct->hDC, pDrawItemStruct->rcItem.left, pDrawItemStruct->rcItem.top, pDrawItemStruct->rcItem.right, pDrawItemStruct->rcItem.bottom, hBitmapDC, 0, 0, 4, 4, SRCCOPY ); SelectObject( hBitmapDC, hOld ); DeleteObject( hBitmapDC ); Its not using the MFC classes to stretch a 4x4 bitmap into a larger space but works perfectly. My guess is that you aren't doing it in response to a WM_PAINT/WM_DRAWITEM and/or are using the wrong DC. Edit re your edit: Do you then call DrawImage from inside an OnPaint or DrawItem call? I would have thought you are better off not cacheing that CDC and passing the CDC in each time you wish to draw it.
2,833,153
2,834,135
Floating point comparison in STL, BOOST
Is there in the STL or in Boost a set of generic simple comparison functions? The one I found are always requiring template parameters, and/or instantiation of a struct template. I'm looking for something with a syntax like : if ( is_equal(x,y) ) { ... } Which could be implemented as : template <typename T> bool is_equal(const T& x, const T& y) { return ( fabs(x - y) < Precision<T>::eps ); } EDIT: I changed the operator to equal. (see comments below)
I don't know of any library that does it, perhaps because it is as simple as a one-liner or perhaps because it was forgotten... As generality goes though, are you sure you'd like to set up the epsilon for one given type at a given value... throughout the application ? Personally I'd like to customize it depending on the operations I am doing (even though a default would be nice). As for your operators, why not devising them yourself ? template <class T> bool rough_eq(T lhs, T rhs, T epsilon = Precision<T>::epsilon) // operator== { return fabs(lhs - rhs) < epsilon; } template <class T> bool rough_lt(T lhs, T rhs, T epsilon = Precision<T>::epsilon) // operator< { return rhs - lhs >= epsilon; // tricky >= because if the difference is equal to epsilon // then they are not equal per the rough_eq method } template <class T> bool rough_lte(T lhs, T rhs, T epsilon = Precision<T>::epsilon) // operator<= { return rhs - lhs > -epsilon; } The inequality and greater than methods can be trivially derived from this. The additional parameter means that you may wish to specify another value for a given set of computations... an application-wide setting is too strict.
2,833,257
2,833,268
How to call a method via a vector?
How do I call a method of an object which is stored within a vector? The following code fails... ClassA* class_derived_a = new ClassDerivedA; ClassA* class_another_a = new ClassAnotherDerivedA; vector<ClassA*> test_vector; test_vector.push_back(class_derived_a); test_vector.push_back(class_another_a); for (vector<ClassA*>::iterator it = test_vector.begin(); it != test_vector.end(); it++) it->printOutput(); The code retrieves the following error: test3.cpp:47: error: request for member ‘printOutput’ in ‘* it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> with _Iterator = ClassA**, _Container = std::vector >’, which is of non-class type ‘ClassA*’ The problem seems to be it->printOutput(); but at the moment I don't know how to call the method properly, does anyone know? regards mikey
The things in the vector are pointers. You need: (*it)->printOutput(); which dereferences the iterator to get the pointer from the vector, then uses -> on the pointer to call the function. The syntax you show in your question would work if the vector contained objects rather than pointers, in which case the iterator acts like a pointer to one of those objects.
2,833,682
2,833,747
Contents changed(cleared?) when access the pointer returned by std::string::c_str()
I have to maintain some legacy codes,parts of it look like the following: /* this class reads a ini file which looks like this: key = value */ class Config{ // .. public: string conf(const char* key) { vector<string> v; //.. v = func(); //this function returns a vector<string> return v[1]; } }; void test() { // a globla Config object cfg is initialized outside const char* p = cfg.conf("key1").c_str(); // the string object will be alive as a auto var // so the pointer should be valid till the end of this function,right? // ... lots of steps, but none of them would access the pointer p some_call(cfg.conf("key2").c_str()); some_call(cfg.conf("key3").c_str()); some_call(cfg.conf("key4").c_str()); // the above calls never fail // but when try to access p here, SOMETIMES the contents would change ... Why? /* the platform is solaris 64 bit compiler is sun workshop 12 my code is compiled as ELF 32-bit MSB relocatable SPARC32PLUS Version 1, V8+ Required but need to link with some shared lib which are ELF 32-bit MSB dynamic lib SPARC Version 1, dynamically linked, stripped */ } The original code has been running for several years and never failed(pure luck?).Recently we decided to migrate it to a newer platform and the problem described in the comments starts popping up. Neil Butterworth and aJ have pointed out the temp string obj in this sentence: const char* p = cfg.conf("key1").c_str(); will die immediately when ; is reached.Although in my test the access to key2,key3,key4 never failed,I guess they are actually not safe too,right?
the string object will be alive as a auto var so the pointer should be valid till the end of this function,right? Wrong. The temporary returned by the conf() function call lives as long as the full expression it is part of, not for the length of the function containing the call.
2,833,730
2,833,761
Calling template function without <>; type inference
If I have a function template with typename T, where the compiler can set the type by itself, I do not have to write the type explicitly when I call the function like: template < typename T > T min( T v1, T v2 ) { return ( v1 < v2 ) ? v1: v2; } int i1 = 1, i2 = 2; int i3 = min( i1, i2 ); //no explicit <type> But if I have a function template with two different typenames like: template < typename TOut, typename TIn > TOut round( TIn v ) { return (TOut)( v + 0.5 ); } double d = 1.54; int i = round<int>(d); //explicit <int> Is it true that I always have to specify at least 1 typename? I assume the reason is because C++ can not distinguish functions between different return types. But if I use a void function and handover a reference, again I must not explicitly specify the return typename: template < typename TOut, typename TIn > void round( TOut & vret, TIn vin ) { vret = (TOut)(vin + 0.5); } double d = 1.54; int i; round(i, d); //no explicit <int> Should the conclusion be to avoid functions with return and more prefer void functions that return via a reference when writing templates? Or is there a possibility to avoid explicitly writing the return type? Something like "type inference" for templates. Is "type inference" possible in C++0x?
Overload resolution is done only based on function arguments; the return value is not used at all. If the return type cannot be determined based on the arguments, you will have to specify it explicitly. I would not go down the path of "returning" a value through a reference parameter; that makes the calling code unclear. For example, I'd prefer this: double x = round<double>(y); over this: double x; round(x, y); because in the latter case, it's easy to confuse input and output, and it's not at all clear that x is being modified. In the particular case of round, you probably need only one or two types for TOut anyway, so you could just leave that template argument out: template<typename TIn> int roundToInt(TIn v) { return (int)(v + 0.5); } I find roundToInt(x) a little clearer than round<int>(x) because it's clear what the int type is used for.
2,834,131
2,834,152
Automatic creation of method definitions from declarations
Is there a tool, macro or plugin that can generate a method or function body automatically from a declaration in a header file? I have tried Intellisense and Refactor! 3.0.5 which both only seem to work with C#.
You could use Visual Assist. But it is a commercial tool.
2,834,139
2,834,157
Declaring a data type dynamically in C++
I want to be able to do the following: I have an array of strings that contain data types: string DataTypeValues[20] = {"char", "unsigned char", "short", "int"}; Then later, I would like to create a variable of one of the data types at runtime. I won't know at compile time what the correct data type should be. So for example, if at runtime I determined a variable x needed to be of type int: DataTypeValues[3] x = 100; Obviously this won't work, so how could I do something like this?
The simple answer is that you can't - types need to be known at compile time in C++. You can do something like it using things like boost::any or unions, but it won't be pretty.
2,834,362
2,834,394
C++ STL map.find() not finding my stuff
I have constructed a map and loaded it with data. If I iterate over all the elements I see they are all valid. However, the find method doesn't find my item. I'm sure it's something stupid I am doing. Here is snippet: // definitions // I am inserting a person class and using the firstname as the key typedef std::map<char*,Person *> mapType; mapType _myMap; mapType::iterator _mapIter; ... Person *pers = new Person(FirstName, LastName, Address, Phone); _myMap.insert(make_pair(pers->firstName, pers); ... ...later.... _mapIter = _myMap.find(firstName); // returns map.end _mapIter = _myMap.find("joe"); // returns map.end and I have no idea why :(
Since the key is char*, they will be compared by address, not by value, e.g. char* a = "123"; char* b = new char[4]; memcpy(b, a, 4); assert(a != b); You should use a std::string, which has an overloaded < for comparison by value. typedef std::map<std::string, Person*> mapType; ... (And probably you want to use a Person or shared_ptr<Person> as the value to avoid memory leak.)
2,834,414
2,834,451
Is private member hacking defined behaviour?
I have the following class: class BritneySpears { public: int getValue() { return m_value; }; private: int m_value; }; Which is an external library (that I can't change). I obviously can't change the value of m_value, only read it. Even deriving from BritneySpears won't work. What if I define the following class: class AshtonKutcher { public: int getValue() { return m_value; }; public: int m_value; }; And then do: BritneySpears b; // Here comes the ugly hack AshtonKutcher* a = reinterpret_cast<AshtonKutcher*>(&b); a->m_value = 17; // Print out the value std::cout << b.getValue() << std::endl; I know this is bad practice. But just out of curiosity: is this guaranteed to work? Is it defined behaviour? Bonus question: Have you ever had to use such an ugly hack? Edit: Just to scare fewer people: I don't intend to actually do this in real code. I'm just wondering ;)
This is undefined behaviour. The members within each access-qualifier section are guaranteed to be laid out in the order they appear, but there is no such guarantee between acccess qualifiers. For instance, if the compiler chooses to place all private members before all public members, the above two classes will have a different layout. Edit: Revisiting this old answer, I realized that I missed a rather obvious point: the struct definitions have exactly one data member each. The order of member functions is irrelevant, since they don't contribute to the class's layout. You might well find that both data members are guaranteed to be in the same place, though I don't know the standard well enough to say for sure. But! You cannot dereference the result of reinterpret_casting between unrelated types. It's still UB. At least, that's my reading of http://en.cppreference.com/w/cpp/language/reinterpret_cast, which is a gnarly read indeed.
2,834,491
2,834,532
destroying object in vector when new object added
When push_back method of vector is called the previous object in the vector is getting destroyed what might be the reason for this. template<typename type> void SomeList<type>::AddElement(type &inObject) { pList.push_back(inObject);// pList is member of my class Vector SomeList }
The vector doesn't destroy the object. It replaces it. For example: vector< A> myVector; // Do some initialization, etc. A myNewObject; myVector[0] = myNewObject; // Replace the object. That means the assignment operator (A& A::operator=( const A&)) will be called for myVector[0]. There is no destruction there. The destruction is done when the vector itself is destructed, or when the memory is reallocated (in this case, the copy constructor is also used, to copy the objects from the old location to the new location, before destroying the old ones). Later edit In push_back case, the destruction must be determined by a reallocation.
2,834,566
2,834,631
Beginner C++ - Opening a text file for reading if it exists, if it doesn't, create it empty
I am writing a high-score sub-routine for a text-based game. Here's what I have so far. void Game::loadHiScores(string filename) { fstream hiscores(filename.c_str()); // what flags are needed? int score; string name; Score temp; if (hiscores.is_open()) { for (size_t i = 0; i < TOTAL_HISCORES && !(hiscores.eof()); ++i) { cin >> score >> name; temp.addPoints(score); temp.scoreSetName(name); hiScores.push_back(temp); } } else { //what should go here? } hiscores.close(); } How can I make it so that: IF the file exists, it shall be open for reading ELSE the file shall be created Thanks for your time
Wrong logic I would say. I think you want: Try to open an ifstream (not an fstream) containing scores if it opened read high scores into array close stream else set array to zero endif Play Game - adjust high scores in array, then on exit Try to open scores ofstream (not an fstream) for writing if it opened write high scores close stream else report an error end if If you use ifstreams and ofstreams, there is no need for special flags, or for possibly having to seek within the file - you just rewrite the whole thing.
2,834,737
2,834,927
Creating new folders if they don't exist for fopen
I have a C++ program that takes user input for fopen in order to initiate a file write. Could someone help me find a function which will return a FILE* and use the Windows specific version of mkdir in order to create the folder structure for fopen to never fail to open a new file in the specified location because one of the folders does not exist. Thanks a bunch!
there's a method MakeSureDirectoryPathExists in the windows API, declared in dbghelp.h. It recursively creates directories, so I guess that's what you are after. However, there is NO way of making sure this 'never fails' as you ask, as it also depends on privileges etc if you have write access to a certain directory. edit: here's some dummy sample code; it uses GetProcAddress though, as I couldn't find the dbghelp header when I wrote it. typedef BOOL (WINAPI * CreateDirFun ) ( __in PCSTR DirPath ); HMODULE h = LoadLibrary( "dbghelp.dll" ); CreateDirFun pFun = (CreateDirFun) GetProcAddress( h, "MakeSureDirectoryPathExists" ); (*m_pFun)( psPath ) ) CreateDirectory( psPath ); FreeLibrary( h );
2,834,922
2,834,943
template function roundTo int, float -> truncation
according to this question: Calling template function without <>; type inference the round function I will use in the future now looks like: template < typename TOut, typename TIn > TOut roundTo( TIn value ) { return static_cast<TOut>( value + 0.5 ); } double d = 1.54; int i = rountTo<int>(d); However it makes sense only if it will be used to round to integral datatypes like char, short, int, long, long long int, and it's unsigned counterparts. If it ever will be used with a TOut As float or long double it will deliver s***. double d = 1.54; float f = roundTo<float>(d); // aarrrgh now float is 2.04; I was thinking of a specified overload of the function but ... that's not possible... How would you solve this problem? many thanks in advance Oops
Assuming you want the closest integer value, cast to TOut, static_cast<TOut>( static_cast<long long>(value + 0.5) ); floor should also work as an alternative to the inner cast. The point is not to rely on the cast to an unknown type to perform any truncation -- ensure the truncation explicitly, with a floor or a cast to a well-known integral type, then perform the further casting you need to return the specified type.
2,835,030
2,835,049
Representing a 16 byte variable
I have to represent a 16 byte field as part of a data structure: struct Data_Entry { uint8 CUI_Type; uint8 CUI_Size; uint16 Src_Refresh_Period; uint16 Src_Buffer_Size; uint16 Src_CUI_Offset; uint32 Src_BCW_Address; uint32 Src_Previous_Timestamp; /* The field below should be a 16 byte field */ uint32 Data; }; How would I represent the "Data" field as a 16 byte field instead of the 4 byte field it currently is? Thanks, Bobby
Anything wrong with uint8 Data[16];?
2,835,092
2,835,322
C++ Beginner - Best way to read 3 consecutive values from the command line?
I am writing a text-based Scrabble implementation for a college project. The specification states that the user's position input must be read from single line, like this: Coordinates of the word's first letter and orientation (<A – P> <1 – 15> <H ou V>): G 5 H G 5 H is the user's input for that particular example. The order, as shown, must be char int char. What is the best way to read the user's input? cin >> row >> column >> orientation will cause crashes if the user screws up. A getline and a subsequent string parser are a valid solution, but represent a bit of work. Is there another, better, way to do this, that I am missing? Thanks for your time!
getline and parsing doesn't necessarily have to add much work. Since you already know how to read (correct) data from a stream, just read a line with getline, then create an istringstream from the line and read from there. The one thing I'd add would be that it might very well make sense to create a class to hold the data for a particular move, and overload operator>> for that class to read data for a move. A rough sketch would be something like this: class move { char row; int column; char orientation; public: friend std::istream &operator>>(std::istream &is, move &m); }; std::istream &operator>>(std::istream &is, move &m) { std::string temp; std::getline(is, temp); std::istringstream buffer(temp); // Now we can parse data from buffer just like we could from another stream. return is; } At least for the moment, I haven't included any error handling code. Depending on how picky you want to be, this can get a little tricky (e.g., if input from the stringstream fails, setting the fail bit in the original input stream).
2,835,094
2,835,228
Calculating free disk space
What is the best method for calculating free disk space using C++ only. My target platform is WinCE but most of the file operations are the same as normal Windows.
You mean usage as in how much space is left? then try GetDiskFreeSpace() Or do you mean, number of reads/writes/current files open, speed etc?
2,835,626
2,835,645
C++0x lambda capture by value always const?
Is there any way to capture by value, and make the captured value non-const? I have a library functor that I would like to capture & call a method that is non-const but should be. The following doesn't compile but making foo::operator() const fixes it. struct foo { bool operator () ( const bool & a ) { return a; } }; int _tmain(int argc, _TCHAR* argv[]) { foo afoo; auto bar = [=] () -> bool { afoo(true); }; return 0; }
Use mutable. auto bar = [=] () mutable -> bool .... Without mutable you are declaring the operator () of the lambda object const.
2,835,716
2,838,044
How do I call functions inside C++ DLL from Lua?
I have a DLL written in C++ that is legacy code and cannot modify the source code. I want to be able to call some of the functions inside of the DLL from Lua. For example, I'd like to do something like this: -- My Lua File include(myCppDll.dll) function callCppFunctionFromDll() local result = myCppFunctionFromDll(arg1, arg2) --Do something with result here end Is something like this possible?
If Alien doesn't meet your needs, and it might not be easy to use if the DLL has a strongly object oriented interface where you need to get at the members and methods of objects as well as just call exported functions, then you should look at generating a wrapper DLL that interfaces the legacy API from the DLL to Lua. This can be done with a wrapper generator such as Swig which will write wrappers for Lua as well as many other scripting languages based on declarations of classes and functions, often simply taking little more than the existing .h files as input. Lua is also simple enough code for that it might be simpler to write your own wrapper by hand in C. To do this, start from the standard recipe for creating a Lua callable module in C, and implement functions that transfer arguments from the Lua stack into a form suitable for each API call, call into the DLL, and push any results back on the Lua stack. This is also the place to take advantage of Lua's ability to return more than one result for those functions that in the DLL had to use output pointers to deal with a second (or more) return value. A discussion of the issues and some sample code is available at the Lua User's Wiki. There is also a page devoted to binding Lua to other languages at the Lua User's Wiki.
2,835,746
2,835,761
How do you specify a 64 bit unsigned int const 0x8000000000000000 in VS2008?
I read about the Microsoft specific suffix "i64" for integer constants. I want to do an UNsigned shift to a ULONGLONG. ULONGLONG bigNum64 = 0x800000000000000i64 >> myval; In normal C, I would use the suffix "U", e.g. the similar 32 bit operation would be ULONG bigNum32 = 0x80000000U >> myval; I do NOT want the 2's complement sign extension to propogate through the high bits. I want an UNSIGNED shift on a 64 bit const number. I think my first statement is going to do a SIGNED shift right. I tried 0x800000000000000i64U and 0x800000000000000u64 but got compiler errors.
You can use the suffix ull, which is the standard (C99 and C++0x) way to specify an unsigned long long integer literal, and a long long is at least 64 bits.
2,835,847
2,835,875
C++ stack for multiple data types (RPN vector calculator)
I have designed a quick and basic vector arithmetic library in C++. I call the program from the command line when I need a rapid cross product, or angle between vectors. I don't use Matlab or Octave or related, because the startup time is larger than the computation time. Again, this is for very basic operations. I am extending this program, and I will make it work as an RPN calculator, for operations of the type: 1 2 3 4 5 6 x out: -3 6 -3 (give one vector, another vector, and the "cross" operator; spit out the cross product) The stack must accept 3d vectors or scalars, for operations like: 1 2 3 2 * out: 2 4 6 The lexer and parser for this mini-calculator are trivial, but I cannot seem to think of a good way for creating the internal stack. How would you create a stack of for containing vectors or doubles (I rolled up my own very simple vector class - less than one hundred lines and it does everything I need). How can I create a simple stack which accepts elements of class Vector or type double? Thank you.
The simplest way would be just to create an Operand struct that contains a double for the scalar and a Vector object for the vector: struct Operand { double scalar_; Vector vector_; bool isVector_; }; (you can set isVector_ to true if it is a vector operand, and false if it is a scalar operand) For the actual stack, you can just use std::stack<Operand>. Other options include inheritance (creating scalar and vector types derived from an operand base type) or something like boost::variant, but for something simple like this, a composition struct like the Operand shown above is probably the easiest way to do it.
2,835,910
2,835,937
C++ - How to efficiently find out if any string in a vector can be assembled from a set of letters
I am implementing a text-based version of Scrabble for a college project. I have a vector containing around 400K strings (my dictionary), and, at some point in every turn, I'm going to have to check if there's still a word in the dictionary which can be formed with the pieces in the player's hand. I'm checking if the player has any move left... If not, it's game over for the player in question... My only solution to this is iterating through the string, one by one, and using a sub-routine I have to check if the string in question can be formed from the player's pieces. I'll implement a quickfail checking if the user has any vowels, but it'll still be woefully inefficient. The text-file containing the dictionary is already alphabetically ordered, so the vector is sorted. Any suggestions? A problem was presented in the comments below: Any suggestion on how do I take the letters already on the board into account?
Without giving you any specific code (since this is homework after all), one general approach to consider is to map from the sorted letters in the word to the actual legal words. That is to say, if your dictionary file had only the words ape, gum, and mug, your data structure would look like: aep -> ape gmu -> gum, mug Then you can simply go through permutations of the player's letters, and quickly identify if that key exists in the map. You pay a little bit of processing time setting up the dictionary at startup, but then you only have to perform a few quick lookups rather than iterating through the whole list every time.
2,836,033
2,839,053
Suggestion for chkstk.asm stackoverflow exception in C++ with Visual Studio
I am working with an implementation of merge sort. I am trying with C++ Visual Studio 2010 (msvc). But when I took a array of 300000 integers for timing, it is showing an unhandled stackoverflow exception and taking me to a readonly file named "chkstk.asm". I reduced the size to 200000 and it worked. Again the same code worked with C-free 4 editor (mingw 2.95) without any problem while the size was 400000. Do you have any suggestion to get the code working in Visual Studio? May be the recursion in the mergesort is causing the problem.
Problem solved. Thanks to Kotti for supplying the code. I got the problem while comparing with that code. The problem was not about too much recursion. Actually I was working with a normal C++ array which was being stored on stack. Thus the problem ran out of stack space. I just changed it to a dynamically allocated array with the new/delete statements and it worked.
2,836,396
2,836,724
How to simulate inner exception in C++
Basically I want to simulate .NET Exception.InnerException in C++. I want to catch exception from bottom layer and wrap it with another exception and throw again to upper layer. The problem here is I don't know how to wrap the catched exception inside another exception. struct base_exception : public std::exception { std::exception& InnerException; base_exception() : InnerException(???) { } // <---- what to initialize with base_exception(std::exception& innerException) : InnerException(innerException) { } }; struct func1_exception : public base_exception { const char* what() const throw() { return "func1 exception"; } }; struct func2_exception : public base_exception { const char* what() const throw() { return "func2 exception"; } }; void func2() { throw func2_exception(); } void func1() { try { func2(); } catch(std::exception& e) { throw func2_exception(e); // <--- is this correct? will the temporary object will be alive? } } int main(void) { try { func1(); } catch(base_exception& e) { std::cout << "Got exception" << std::endl; std::cout << e.what(); std::cout << "InnerException" << std::endl; std::cout << e.InnerException.what(); // <---- how to make sure it has inner exception ? } } In the above code listing I am not sure how to initialize the "InnerException" member when there is no inner exception. Also I am not sure whether the temporary object that is thrown from func1 will survive even after func2 throw?
You should also take a look at boost exception for an alternative solution to wrapping.
2,836,473
2,836,499
Developing Android applications with Visual Studio 2008
I've recently obtained an HTC Desire and I'm interested in porting my 3D engine to the device. I have a slight annoyance however. I'd love to be able to do development under Visual Studio 2008. Am I to assume I'm going to need to re-process my SLN files to do GCC builds? Its not a vast issue as I already have an application that processes SLN and VCProj files through GCC and then links them together at the other end. I'll just need to set up the right libraries with it. Are there any other gotchas I need to think about? Or, indeed, is there an easier way? Any info would be much appreciated! Cheers :)
You will need to use your own or the NDK supplied build system. I believe Visual Studio can be set up to call external commands to build. You can of course use Visual Studio as the code editor, and call the NDK supplied make on the Makefile to build your application. You can't use Visual Studio as a debugger.
2,836,743
2,836,764
C++, class as parameter to a method, not template
So, I came across an interesting method signature that I don't quite understand, it went along the lines of: void Initialize(std::vector< std::string > & param1, class SomeClassName * p); what I don't understand is the "class" keyword being used as the parameter, why is it there? Is it necessary to specify or it is purely superficial?
It is a forward declaration of the class. It is the effectively the same as class SomeClassName; void Initialize(std::vector< std::string > & param1, SomeClassName * p); There are many situations in which a forward declaration is useful; there's a whole list of things that you can and can't do with a forward declaration in this answer to another question).
2,836,863
2,836,891
Is there long long defined?
Where to check if type long long is defined? I wanna do something like this: #ifdef LONGLONG #define long_long long long #else #define long_long long #endif
LLONG_MAX gives the maximum value representable by a long long; if your implementation doesn't support long long, it shouldn't define LLONG_MAX. #include <limits.h> #ifdef LLONG_MAX #define long_long long long #else #define long_long long #endif This isn't a perfect solution. long long isn't standard in C++03, and long long has been around longer than C99, so it's possible (and likely) that a compiler could support long long but not define LLONG_MAX. If you want an integer type with a specific size, you should use <stdint.h> if your implementation supports it. If your implementation doesn't support it, Boost has an implementation of it.
2,836,939
2,836,985
Purpose of Explicit Default Constructors
I recently noticed a class in C++0x that calls for an explicit default constructor. However, I'm failing to come up with a scenario in which a default constructor can be called implicitly. It seems like a rather pointless specifier. I thought maybe it would disallow Class c; in favor of Class c = Class(); but that does not appear to be the case. Some relevant quotes from the C++0x FCD, since it is easier for me to navigate [similar text exists in C++03, if not in the same places] 12.3.1.3 [class.conv.ctor] A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization (8.5). It goes on to provide an example of an explicit default constructor, but it simply mimics the example I provided above. 8.5.6 [decl.init] To default-initialize an object of type T means: — if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); 8.5.7 [decl.init] To value-initialize an object of type T means: — if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); In both cases, the standard calls for the default constructor to be called. But that is what would happen if the default constructor were non-explicit. For completeness sake: 8.5.11 [decl.init] If no initializer is specified for an object, the object is default-initialized; From what I can tell, this just leaves conversion from no data. Which doesn't make sense. The best I can come up with would be the following: void function(Class c); int main() { function(); //implicitly convert from no parameter to a single parameter } But obviously that isn't the way C++ handles default arguments. What else is there that would make explicit Class(); behave differently from Class();? The specific example that generated this question was std::function [20.8.14.2 func.wrap.func]. It requires several converting constructors, none of which are marked explicit, but the default constructor is.
This declares an explicit default constructor: struct A { explicit A(int a1 = 0); }; A a = 0; /* not allowed */ A b; /* allowed */ A c(0); /* allowed */ In case there is no parameter, like in the following example, the explicit is redundant. struct A { /* explicit is redundant. */ explicit A(); }; In some C++0x draft (I believe it was n3035), it made a difference in the following way: A a = {}; /* error! */ A b{}; /* alright */ void function(A a); void f() { function({}); /* error! */ } But in the FCD, they changed this (though, I suspect that they didn't have this particular reason in mind) in that all three cases value-initialize the respective object. Value-initialization doesn't do the overload-resolution dance and thus won't fail on explicit constructors.
2,836,956
2,836,973
how to templatize partial template specializations?
I'm not even sure what title to give this question; hopefully the code will demonstrate what I'm trying to do: #include <string> #include <list> using namespace std; template<typename A> class Alpha { public: A m_alpha_a; }; template<typename B> class Bravo { public: B m_bravo_b; }; template<> class Alpha<string> { public: string m_alpha_string; }; template<typename B> template<> class Alpha<Bravo<B> > { public: Bravo<B> m_bravo_class; // Line A }; int main() { Alpha<int> alpha_int; alpha_int.m_alpha_a= 4; Alpha<string> alpha_string; alpha_string.m_alpha_string = "hi"; Alpha<Bravo<int> > alpha_bravo_int; alpha_bravo_int.m_bravo_class.m_bravo_b = 9; }; I want to write a specialization for Alpha<A> when A is of any type Bravo<B>, but the compiler says invalid explicit specialization before ‘>’ token enclosing class templates are not explicitly specialized (Referring to // Line A.) What's the correct syntax to do what I want?
Just replace template<typename B> template<> class Alpha<Bravo<B> > with template<typename B> class Alpha<Bravo<B> > i.e. remove template<> here.
2,836,978
2,837,113
GCC, -O2, and bitfields - is this a bug or a feature?
Today I discovered alarming behavior when experimenting with bit fields. For the sake of discussion and simplicity, here's an example program: #include <stdio.h> struct Node { int a:16 __attribute__ ((packed)); int b:16 __attribute__ ((packed)); unsigned int c:27 __attribute__ ((packed)); unsigned int d:3 __attribute__ ((packed)); unsigned int e:2 __attribute__ ((packed)); }; int main (int argc, char *argv[]) { Node n; n.a = 12345; n.b = -23456; n.c = 0x7ffffff; n.d = 0x7; n.e = 0x3; printf("3-bit field cast to int: %d\n",(int)n.d); n.d++; printf("3-bit field cast to int: %d\n",(int)n.d); } The program is purposely causing the 3-bit bit-field to overflow. Here's the (correct) output when compiled using "g++ -O0": 3-bit field cast to int: 7 3-bit field cast to int: 0 Here's the output when compiled using "g++ -O2" (and -O3): 3-bit field cast to int: 7 3-bit field cast to int: 8 Checking the assembly of the latter example, I found this: movl $7, %esi movl $.LC1, %edi xorl %eax, %eax call printf movl $8, %esi movl $.LC1, %edi xorl %eax, %eax call printf xorl %eax, %eax addq $8, %rsp The optimizations have just inserted "8", assuming 7+1=8 when in fact the number overflows and is zero. Fortunately the code I care about doesn't overflow as far as I know, but this situation scares me - is this a known bug, a feature, or is this expected behavior? When can I expect gcc to be right about this? Edit (re: signed/unsigned) : It's being treated as unsigned because it's declared as unsigned. Declaring it as int you get the output (with O0): 3-bit field cast to int: -1 3-bit field cast to int: 0 An even funnier thing happens with -O2 in this case: 3-bit field cast to int: 7 3-bit field cast to int: 8 I admit that attribute is a fishy thing to use; in this case it's a difference in optimization settings I'm concerned about.
If you want to get technical, the minute you used __attribute__ (an identifier containing two consecutive underscores) your code has/had undefined behavior. If you get the same behavior with those removed, it looks to me like a compiler bug. The fact that a 3-bit field is being treated as 7 means that it's being treated as an unsigned, so when you overflow it should do like any other unsigned, and give you modulo arithmetic. It would also be legitimate for it to treat the bit-field as signed. In this case the first result would be -1, -3 or -0 (which might print as just 0), and the second undefined (since overflow of a signed integer gives undefined behavior). In theory, other values might be possible under C89 or the current C++ standard since they don't limit the representations of signed integers. In C99 or C++0x, it can only be those three (C99 limits signed integers to one's complement, two's complement or sign-magnitude and C++0x is based on C99 instead of C90). Oops: I didn't pay close enough attention -- since it's defined as unsigned, it has to be treated as unsigned, leaving little wiggle room for getting out of its being a compiler bug.
2,837,222
10,542,678
Is Perforce's C++ P4API thread-safe?
Simple question - is the C++ API provided by Perforce thread-safe? There is no mention of it in the documentation. By "thread-safe" I mean for server requests from the client. Obviously there will be issues if I have multiple threads trying to set client names and such on the same connection. But given a single connection object, can I have multiple threads fetching changelists, getting status, translating files through a p4 map, etc.?
Late answer, but... From the release notes themselves: Known Limitations The Perforce client-server protocol is not designed to support multiple concurrent queries over the same connection. For this reason, multi-threaded applications using the C++ API or the derived APIs (P4API.NET, P4Perl, etc.) should ensure that a separate connection is used for each thread or that only one thread may use a shared connection at a time. It does not look like the client object has thread affinity, so in order to share a connection between threads, one just has to use a mutex to serialize the calls.
2,837,241
2,837,277
C++ Returning Pointers/References
I have a fairly good understanding of the dereferencing operator, the address of operator, and pointers in general. I however get confused when I see stuff such as this: int* returnA() { int *j = &a; return j; } int* returnB() { return &b; } int& returnC() { return c; } int& returnC2() { int *d = &c; return *d; } In returnA() I'm asking to return a pointer; just to clarify this works because j is a pointer? In returnB() I'm asking to return a pointer; since a pointer points to an address, the reason why returnB() works is because I'm returning &b? In returnC() I'm asking for an address of int to be returned. When I return c is the & operator automatically "appended" c? In returnC2() I'm asking again for an address of int to be returned. Does *d work because pointers point to an address? Assume a, b, c are initialized as integers as Global. Can someone validate if I am correct with all four of my questions?
In returnA() I'm asking to return a pointer; just to clarify this works because j is a pointer? Yes, int *j = &a initializes j to point to a. Then you return the value of j, that is the address of a. In returnB() I'm asking to return a pointer; since a pointer points to an address, the reason why returnB() works is because I'm returning &b? Yes. Here the same thing happens as above, just in a single step. &b gives the address of b. In returnC() I'm asking for an address of int to be returned. When I return c is the & operator automatically appended? No, it is a reference to an int which is returned. A reference is not an address the same way as a pointer is - it is just an alternative name for a variable. Therefore you don't need to apply the & operator to get a reference of a variable. In returnC2() I'm asking again for an address of int to be returned. Does *d work because pointers point to an address? Again, it is a reference to an int which is returned. *d refers to the original variable c (whatever that may be), pointed to by c. And this can implicitly be turned into a reference, just as in returnC. Pointers do not in general point to an address (although they can - e.g. int** is a pointer to pointer to int). Pointers are an address of something. When you declare the pointer like something*, that something is the thing your pointer points to. So in my above example, int** declares a pointer to an int*, which happens to be a pointer itself.
2,837,346
2,837,361
Variable Scoping in a method and its persistence in C++
Consider the following public method that adds an integer variable to a vector of ints(private member) in a class in C++. KoolMethod() { int x; x = 10; KoolList.Add(x); } Vector<int>KoolList; But is this a valid addition to a vector ??? Upon calling the method, it creates a local variable. The scope of this local variable ends the moment the execution control leaves the method. And since this local variable is allocated on a stack(on the method call), any member of KoolList points to an invalid memory location in deallocated stack which may or may not contain the expected value of x. Is this an accurate description of above mechanism ?? Is there a need for creating an int in heap storage using "new" operator everytime a value needs to be added to the vector like described below ????: KoolMethod() { int *x = new int(); *x = 10; KoolList.Add(x); } Vector<int*>KoolList;
But is this a valid addition to a vector? Yes, a (standard library) vector stores copies. Is there a need for creating an int in heap storage using "new" operator If you don't want the objects to be copied or to work with polymorphic objects (see object slicing) you'd use pointers. In that case you should preferably avoid dealing with deallocation manually and use wrappers (smart pointers or pointer containers) though to get exception safety back.
2,837,469
2,837,499
C++ Preprocessor string literal concatenation
I found this regarding how the C preprocessor should handle string literal concatenation (phase 6). However, I can not find anything regarding how this is handled in C++ (does C++ use the C preprocessor?). The reason I ask is that I have the following: const char * Foo::encoding = "\0" "1234567890\0abcdefg"; where encoding is a static member of class Foo. Without the availability of concatenation I wouldnt be able to write that sequence of characters like that. const char * Foo::encoding = "\01234567890\0abcdefg"; Is something entirely different due to the way \012 is interpreted. I dont have access to multiple platforms and I'm curious how confident I should be that the above is always handled correctly - i.e. I will always get { 0, '1', '2', '3', ... }
The language (C as well as C++) has no "preprocessor". "Preprocessor", as a separate functional unit, is an implementation detail. The way the source file(s) is handled if defined by so called phases of translation. One of the phases in C, as well as in C++ involves concatenating string literals. In C++ language standard it is described in 2.1. For C++ (C++03) it is phase 6 6 Adjacent ordinary string literal tokens are concatenated. Adjacent wide string literal tokens are concatenated.
2,837,584
2,876,466
Rakefile rule output generation problem
i have a Rakefile with a rule like this : rule '.so' => '.cc' do |t| puts "@ Compiling #{t.source}" output = t.source.ext("so") output['stdlib'] = 'build' sh "mkdir -p #{File.dirname(output)}" sh "#{CXX} #{t.source} -o#{output} #{STDLIB_CFLAGS} #{STDLIB_LFLAGS}" end As you can see, it generates many .so libraries from the 'stdlib' directory (which contains the sources) to the 'build' directory where the binaries are stored. Now the problem is, due to this "directory exchange", rake seems to not recognize the .so files as files it has generated, causing the recompilation of each .so module each time o run the rake command, even if nothing is changed. Is there any way to solve this? Thanks
You can either use the pathmap syntax or an explicit proc to change the output filename/path into the input filename/path. The pathmap syntax will look something like this (untested): rule '.so' => '%{build,stdlib}X.cc' do |t| puts "@ Compiling #{t.source}" sh "mkdir -p #{File.dirname(t.name)}" sh "#{CXX} #{t.source} -o#{t.name} #{STDLIB_CFLAGS} #{STDLIB_LFLAGS}" end The proc method will look something like this (also untested): rule '.so' => [proc { |f| f.sub(/build/, 'stdlib').ext('.cc') }] do |t| puts "@ Compiling #{t.source}" sh "mkdir -p #{File.dirname(t.name)}" sh "#{CXX} #{t.source} -o#{t.name} #{STDLIB_CFLAGS} #{STDLIB_LFLAGS}" end Note that you can get rid of the explicit 'mkdir' in your action and use a 'directory' task instead (if you know in advance the possible destination directories) possible_dest_dirs.each { |d| directory d } rule '.so' => [proc { |f| f.sub(/build/, 'stdlib').ext('.cc') }, proc { |f| File.dirname(f) }] do |t| puts "@ Compiling #{t.source}" sh "#{CXX} #{t.source} -o#{t.name} #{STDLIB_CFLAGS} #{STDLIB_LFLAGS}" end