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
1,081,519
1,081,530
Why does C++ use pointers?
Why does C++ need and use pointers? I know they add power to the language but they make it a lot harder to understand for beginners. Languages like F#, Java, Ruby, Python, Lua, etc. get by just fine without them, and they're quite powerful.
All other languages you mention (and you forgot, at least, Java!!!), while each very useful and usable, don't let you get anywhere as close to the machine as C++ (and C) allow: simply put, all of those languages impose on you a higher level of abstraction... which may mostly be fine but will occasionally get in your way. C++ is a bigger and more complicated language because it allows programming at really low levels of abstraction (very close to the machine) AND at pretty high levels (close to many of the languages you mention) within the same language, indeed within the same source files. Beginners are well advised to stay FAR away from this amount of power and (inevitably) complication -- but not every programmer is a beginner, and not every bit of code needs (or, actually, can at all stand!-) being within an environment that has "let's protect the poor shmucks from themselves" as a major design goal!-)
1,081,764
1,082,515
tips to avoid synchronisation issues in multiplayer and replays using MVC pattern
just wondering what tips people have for avoiding game synchronisation issues in multiplayer games and replays recorded off of game logic using the model in a model view controller pattern so far im aware that its not a good idea to give non const access to the model anywhere outside of it, but apart from that im a little stuck and still have a number of sync issues thanks
To achieve distributed synchronisation, you need a designated single master model, ideally on a separate game server. Control events go to that, get timestamped, the interactions of everything going on gets calculated, and timestamped update events get sent out. Replays can be done just by storing and replaying the update events. As the model is running on a separate server, you can't even give the view const (synchronous) access to it. General purpose MVC isn't really the right approach, it is more: model -> event stream -> local model -> view ^ | | v selector <- action stream <- controller Where the two streams are definitely asynchronous and probably UDP, so lossy. Avoid multithreading, if you have any it should be entirely localised within one of the above components (for example thread pooling within the selector, one thread per zone in the model). For a lot of games, for performance reasons you will need to break that model and have the controller update some parts of the local model directly (e.g the way you can walk around in Wow with your internet connection unplugged). This will definitely lead to sync problems, but probably can't be avoided for a realtime game on a network with ping time > human reaction time.
1,081,811
1,081,821
c++ * vs & in function declaration
Possible Duplicate: Difference between pointer variable and reference variable in C++ When should I declare my variables as pointers vs objects passed-by-reference? They compile to the same thing in assembly (at least run-time asymptotically) so when should I use which? void foo(obj* param) void foo(obj& param)
My rule is simple: use * when you want to show that value is optional and thus can be 0. Excluding from the rule: all the _obj_s around are stored in containers and you don't want to make your code look ugly by using everywhere foo(*value); instead of foo(value); So then to show that value can't be 0 put assert(value); at the function begin.
1,081,831
1,105,925
Windows std::ifstream::open() problem
I know there's been a handful of questions regarding std::ifstream::open(), but the answers didn't solve my problem. Most of them were specific to Win32, and I'm using SDL, not touching any OS-specific functionality (...that's not wrapped up into SDL). The problem is: std::ifstream::open() doesn't seem to work anymore since I've switched from Dev-C++ to Code::Blocks (I've been using the same MinGW-GCC back-end with both), and from Windows XP to Vista. (It also works perfectly with OS X / xcode (GCC back-end).) My project links against a static library which #includes <string>, <iostream>, <fstream> and <cassert>, then a call is made to functionality defined in the static library, which in turn calls std::ifstream::open() (this time, directly). Following this, the stream evaluates to false (with both the implicit bool conversion operator and the good() method). Code: #include "myStaticLibrary.hpp" int main(int argc, char **argv) { std::string filename("D:/My projects/Test/test.cfg"); std::cout << "opening '" << filename << "'..." << std::endl; bool success(false); // call to functionality in the static library { std::ifstream infile(filename.c_str()); success = infile.good(); // ... } // success == false; // ... return 0; } stdcout.txt says: opening 'D:/My projects/Test/test.cfg'... When I open stdcout.txt, and copy-paste the path with the filename into Start menu / Run, the file is opened as should be (I'm not entirely sure how much of diagnostic value this is though; also, the address is converted to the following format: file:///D:/My%20projects/test/test.cfg). I've also tried substituting '/'s with the double backslash escape sequence (again, slashes worked fine before), but the result was the same. It is a debug version, but I'm using the whole, absolute path taken from main()'s argv[0]. Where am I going wrong and what do I need to do to fix it?
I have overseen the importance of the fact that the function in question has close()d the stream without checking if it is_open(). The fact that it will set the stream's fail_bit (causing it to evaluate to false) was entirely new to me (it's not that it's an excuse), and I still don't understand why did this code work before. Anyway, the c++ reference is quite clear on it; the problem is now solved.
1,081,840
1,082,171
Handling COR dump issue with purify
I an instrumenting a C++application using IBM purify and I get the issue COR dump and my program aborts although when run from terminal it runs fine. Can anyone tell me what is this COR dump and how to handle with it? Platform: RHEL 64bit Thanx,
If the software you are using is licensed, please contact IBM.
1,081,843
1,082,416
Most beautiful open source software written in c++
I was told that to be a good developer, you should read a lot of other peoples source code. I think that sounds reasonable. So I ask you, what is the most beautifully written piece of open source software that is written in c++ out there? (Apply any definition of beautiful you like.)
You could look at the source code of MySQL GUI Tools. Its written using gtkmm, and the code does some interesting difficult-to-implement GUI things.
1,081,979
1,082,993
How to select an item in a listview which allows only 1 selected item at a time
I've been trying to select an item on an external listview but it seems to only work with listviews that accept multiple selected items: HANDLE process=OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, 0xC30); LVITEM lvi; LVITEM* _lvi=(LVITEM*)VirtualAllocEx(process, NULL, sizeof(LVITEM), MEM_COMMIT, PAGE_READWRITE); lvi.state = LVIS_FOCUSED | LVIS_SELECTED; lvi.stateMask = LVIS_FOCUSED | LVIS_SELECTED; lvi.mask = LVIF_STATE; WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL); int abc = ::SendMessage((HWND)0x00080D6A, LVM_SETITEMSTATE, (WPARAM)0, (LPARAM)_lvi); VirtualFreeEx(process, _lvi, 0, MEM_RELEASE);
Your code looks valid, and should work, I've tested it internally within my own GUI application itself, so perhaps the issue is in your attempt to access from outside of the actual process. I notice that you have hard coded the HWND for the ListView. Also I would be careful with the fact that you immediately release the virtual memory after sending the message. Remember that the sent message is going to be posted (assuming the HWND is correct) to the ListView message pump. It may not be taken care of immediately and by the time it is, there is a decent chance you've already released the memory of the LVITEM. Try it internally within the GUI, make sure you have that working, then I would suggest going back to this approach and setting appropriate debug points (within the GUI, if this is someone else's, make your own simple dialog with a listView) to make sure that the message is being received appropriately, and that the memory is valid.
1,082,064
1,082,093
In C/C++ can anybody provide some thumb rules for writing small function using inline or macro?
Discussing with people, asking in interviews, or being asked in interviews, I do not know if I know exactly when to write a function as inline or write it as a macro. Apart from compile-time and run-time consideration, is there any suggestion from coding standard point of view. I think this is one of those question where it comes to the programmer's preference, or one may say bias towards the usage. I might be a good idea, if members can quote anecdotes, experiences or situations where they have chosen one over the other.
Macros should be used sparingly, in circumstances where a function will simply not do the job. An example, is error reporting. I use this macro for that purpose: #define ATHROW( msg ) \ { \ std::ostringstream os; \ os << msg; \ throw ALib::Exception( os.str(), __LINE__, __FILE__ ); \ } \ This has to be a macro in order to get the correct file & line number using the standard __FILE__ and __LINE__ macros , and also to provide the error formatting so I can say things like: ATHROW( "Value " << x << " is out of range" );
1,082,083
1,082,107
Are free functions implicitly inlined if defined without a previous declaration in C++?
Is the following free function implicitly inlined in C++, similar to how member functions are implicitly inlined if defined in the class definition? void func() { ... } Do template functions behave the same way?
No, it's not implicitly inlined. The compiler has no way of knowing if another module will use this function, so it has to generate code for it. This means, for instance, that if you define the function like that in a header and include the header twice, you will get linker errors about multiple definitions. Explicit inline fixes that. Of course, the compiler may still inline the function if it thinks that will be efficient, but it's not the same as an explicit inlining. Template functions are implicitly inlined in the sense that they don't require an inline to prevent multiple definition errors. I don't think the compiler is forced to inline those either, but I'm not sure.
1,082,192
1,082,211
How to generate random variable names in C++ using macros?
I'm creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the value of the first variable. For instance: #define MY_MACRO int my_variable_[random-number-here] = getCurrentTime(); The other motivation to use that is to avoid selecting certain name to the variable so that it be the same as a name eventually chosen by the developer using the macro. Is there a way to generate random variable names inside a macro in C++? -- Edit -- I mean unique but also random once I can use my macro twice in a block and in this case it will generate something like: int unique_variable_name; ... int unique_variable_name; In this case, to be unique both variable names have to be random generated.
Add M4 to your build flow? This macro language has some stateful capabilities, and can successfully be intermingled with CPP macros. This is probably not a standard way to generate unique names in a C environment, though I've been able to sucessfully use it in such a manner. You probably do not not want random, BTW, based on the way you posed your question. You want unique. You could use __FILE__ and __LINE__ in the macro expansion to get you the uniqueness you seem to be going for... those metavariables get defined within the source file context, so be careful to make sure you get what you are looking for (e.g., perils of more than one macro on the same line).
1,082,378
1,082,398
what is the basic use of aligned_storage?
What is the basic usage of std::tr1::aligned_storage ? Can it be used as auto memory for a data type Foo like the one below? struct Foo{...}; std::tr1::aligned_storage<sizeof(Foo) ,std::tr1::alignment_of<Foo>::value >::type buf; Foo* f = new (reinterpret_cast<void*>(&buf)) Foo(); f->~Foo(); If so, what about storing multiple Foo in the buf like, std::tr1::aligned_storage<5*sizeof(Foo) ,std::tr1::alignment_of<Foo>::value >::type buf; Foo* p = reinterpret_cast<Foo*>(&buf); for(int i = 0; i!= 5; ++i,++p) { Foo* f = new (p) Foo(); } Are they valid programs? Is there any other use case for it ? Google search only yields the documentation about aligned_storage, but very little about the usage of it.
Well, apart from your use of reinterpret_cast, it looks ok to me. (I'm not 100% sure on the second one). The problem with reinterpret_cast is that it makes no guarantees about the result of the cast, only that if you cast the result back to the original type, you get the original value. So there is no guarantee that the result of the cast will contain the same bit pattern, or point to the same address. As far as I know, a portable solution for casting a pointer x to a type T* is static_cast<T*>(static_cast<void*>(x)), since static_cast to and from void* is guaranteed to turn a pointer to the same address. But that's only tangentially related to your question. :)
1,082,489
1,082,490
Passing data types from C++ to Java/Java to C++
What data types can be passed between c++ and java/java to c++? Also, are the data types equivalent in terms of size?
Using Java Native Interface you can pass just about anything between C++ and Java.
1,082,527
1,082,534
to insert() or to make new
I'm writing some code that has a lot of substitution. There's a list<char> productions which has a bunch of characters in it. I repeatedly need to replace every character in productions with the rules corresponding to it in a map<char,char*> productionRules. So every character in productions might be replaced by zero or more characters as indicated by productionRules. I'm thinking there's 2 ways to do it: iterate over productions and .insert() all replacement characters in productions before .erase()'ing each element Create a NEW list<char> newProductions then reassign productions to refer to newProductions. Which is better? To .insert() and .erase() a whole lot or to just create a new one?
It depends on how likely it is that each character would be replaced by zero or >2 characters. If it's unlikely that any such replacement will take place, then you'll probably win by iterating over it. But if it's likely that you will often perform that operation you should almost certainly just create a new list. You can have your algorithm try to iterate over the list, and if you find you have to do a zero or >2 replacement, then create a new list. Whether or not this wins or not again depends on how likely you are to run into a case where you have to do such a replacement.
1,082,552
1,082,563
A function pointer that points to a function that takes an object of a template class with said function pointer as template argument. Possible?
x__x I want to do something like this: typedef long (* fp)(BaseWindow< fp > & wnd, HWND hwnd, long wparam, long lparam); But I get a compile error: error C2065: 'fp' : undeclared identifier Is it possible to implement this somehow?
No it isn't, because the type of the template parameter would include itself. This would yield to an endless recursion in the type. If instead of the class template specialization, you accept a base-class of it, that's very possible struct TemplateBase { }; typedef long (*fpType)(TemplateBase&, HWND, long, long); template<fpType FP> struct BaseWindow : TemplateBase { }; long sampleFunc(TemplateBase &b, HWND hwnd, long wparam, long lparam) { ... } int main() { BaseWindow<sampleFunc> bw; sampleFunc(bw, ...); } What do you want to do with this?
1,082,655
1,082,682
Conditional operator differences between C and C++
I read somewhere that the ?: operator in C is slightly different in C++, that there's some source code that works differently in both languages. Unfortunately, I can't find the text anywhere. Does anyone know what this difference is?
The conditional operator in C++ can return an lvalue, whereas C does not allow for similar functionality. Hence, the following is legal in C++: (true ? a : b) = 1; To replicate this in C, you would have to resort to if/else, or deal with references directly: *(true ? &a : &b) = 1; Also in C++, ?: and = operators have equal precedence and group right-to-left, such that: (true ? a = 1 : b = 2); is valid C++ code, but will throw an error in C without parentheses around the last expression: (true ? a = 1 : (b = 2));
1,082,867
1,082,941
is there a functor that derefences a (smart) pointer, upcasts it, and then calls a method on it?
I have class A: public B { ...} vector<A*> v; I want to do for_each(v.begin(), v.end(), mem_fun_deref(B::blah())); (Actually I have: vector<unique_ptr<A>> but it shouldn't matter) I need to upcast and call the member function.
boost::lambda can do it vector<A*> v; ... using boost::lambda::_1; using boost::lambda::bind; for_each(v.begin(), v.end(), bind(&B::blah, *_1)); No need to upcast. A member pointer to a base-class member can be applied to a derived class too. #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp>
1,082,901
1,082,935
Reading input from file prints strange symbols
I'm attempting to solve the Project Euler Problem 8 with C++, and the problem is to find the greatest product of 5 consecutive numbers in a 1000 digit number. So I'm trying to figure out how to use file io to read the numbers into a char array that I will later convert to integers. The read works except for the last third of the last line I get weird lines, a green lantern symbol, and a heart. #include "stdafx.h" #include <iostream> #include <fstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const int maxNum = 1000; char buffer[maxNum]; char *bufferPointer = buffer; ifstream infile; infile.open("numberlist.txt"); if (!infile) { cerr << "Error: Open file failure" << endl; return -1; } infile.read(bufferPointer, streamsize(maxNum)); infile.close(); cout << buffer << endl; return 0; } This is what the txt file contains: 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 EDIT: Right after I posted this problem I just realized the problem might be the fact that read is reading the new lines and thus the array isn't big enough to hold it all.
Two problems with your code. First, it looks like you're not accounting for newlines in your maxNum buffer size, so it stops reading either 19 or 38 characters before the end of the text file (depending on if you're using Unix-style or Windows-style line breaks). Either increase the value of maxNum accordingly, or remove the line breaks from your text file. Second, since you're using a char array instead of a std::string to hold the buffer, it needs to be null-terminated to display properly if you use the stream operator. Add the following line after you read the buffer in (you'll also need to increase your buffer size by one to account for the extra character). buffer[maxNum-1] = '\0'; Alternatively, you can use cout.write() to display a known-length buffer that's not null-terminated, as follows: cout.write(buffer, maxNum);
1,083,252
1,083,309
CA2W gave me a "'AtlThrowLastWin32': identifier not found" error
I got a strange compilation error when I followed the MSDN document to use CA2W to convert big5 strings to unicode strings in Visual Studio 2005. This is the code I wrote: #include <string> #include <atldef.h> #include <atlconv.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string chineseInBig5 = "\xA4\xA4\xA4\xE5"; ATL::CA2W(chineseInBig5.c_str()); return 0; } The compilation error: error C3861: 'AtlThrowLastWin32': identifier not found I don't know how this could happen. The document of AtlThrowLastWin32 shows that atldef.h is required, but I couldn't find the declaration of AtlThrowLastWin32 in atldef.h.
I finally solved this problem by adding 2 include headers: #include <atlbase.h> #include <atlstr.h> I don't know why the MSDN document doesn't mention that.
1,083,304
1,083,319
C/C++ counting the number of decimals?
Lets say that input from the user is a decimal number, ex. 5.2155 (having 4 decimal digits). It can be stored freely (int,double) etc. Is there any clever (or very simple) way to find out how many decimals the number has? (kinda like the question how do you find that a number is even or odd by masking last bit).
Two ways I know of, neither very clever unfortunately but this is more a limitation of the environment rather than me :-) The first is to sprintf the number to a big buffer with a "%.50f" format string, strip off the trailing zeros then count the characters after the decimal point. This will be limited by the printf family itself. Or you could use the string as input by the user (rather than sprintfing a floating point value), so as to avoid floating point problems altogether. The second is to subtract the integer portion then iteratively multiply by 10 and again subtract the integer portion until you get zero. This is limited by the limits of computer representation of floating point numbers - at each stage you may get the problem of a number that cannot be represented exactly (so .2155 may actually be .215499999998). Something like the following (untested, except in my head, which is about on par with a COMX-35): count = 0 num = abs(num) num = num - int(num) while num != 0: num = num * 10 count = count + 1 num = num - int(num) If you know the sort of numbers you'll get (e.g., they'll all be 0 to 4 digits after the decimal point), you can use standard floating point "tricks" to do it properly. For example, instead of: while num != 0: use while abs(num) >= 0.0000001:
1,083,959
1,083,980
Purpose of struct, typedef struct, in C++
In C++ it is possible to create a struct: struct MyStruct { ... } And also possible to do the following: typedef struct { ... } MyStruct; And yet as far as I can tell, no discernable difference between the two. Which is preferable? Why do both ways exist if there is no difference? Is one better than the other in style or readability?
The typedef version is a special case of typedef foo bar; which defines a new "type" bar as an alias for foo. In your case, foo happens to be a struct. In C, this was the only way to introduce new "types" (in quotes, because they are not really equivalent to int, float and co). In C++, this is not so useful, because C++ was designed to make definition of new types easier and more complete than C (at least at the beginnings of C++), and the typedef is not even necessary to refer to a previously declared struct (or class).
1,084,039
1,084,041
C/C++ add input to stdin from the program?
Is that even possible ? Lets say that the code has a lot of scanf lines. Instead of manually running and adding values by hand when debugging, is it possible to "feed" stdin with data so that when the scanf starts reading, it will read the inputted data without any need to interact with the terminal.
Put the test lines into a file, and run the program like this: myprogram < mytestlines.txt Better than hacking your program to somehow do that itself. When you're debugging the code, you can set up the debugger to run it with that command line.
1,084,251
1,084,338
What are some effective methods for handling user keyboard input
I've been learning C++ for about a month now, and as I've written programs I've noticed that enabling the user to cancel their input (during a cin loop) is a pain. For example, a program that takes user input and stores it in a vector would have a cin loop like this. vector<int>reftest; int number; cout << "Input numbers for your vector.\n"; while(cin >> number) reftest.push_back(number); The ideal would be for the user to simply press enter, and for the program to exit the loop, but since whitespace isn't read I'm not sure how this would be handled. Instead, something ugly usually ends up being the case like telling the user to input a certain character to cancel their input. Are there any certain methods that any of you use to handle user input?
There are several ways to approach your problem. The easiest is probably to move out of a direct cin/cout loop and to use std::getline instead. Specifically, you could write something like: #include <iostream> #include <vector> #include <sstream> using namespace std; int main( int argc, char **argv ) { vector<int> reftest; while ( true ) { string input; getline( cin, input ); // You can do whatever processing you need to do // including checking for special values or whatever // right here. if ( input.size() == 0 ) // empty input string { cout << "Assuming you're bored with the Entering Numbers game." << endl; break; } else { int value; // Instead of using the input stream to get integers, we // used the input stream to get strings, which we turn // into integers like this: istringstream iss ( input ); while ( iss >> value ) { reftest.push_back( value ); cout << "Inserting value: " << value << endl; } } } } Other approaches include cin.getline() (which I'm not a big fan of because it works on char* instead of strings), using the cin.fail() bit to figure out whether or not the incoming value was any good, etc. And depending on your environment, there are probably many richer ways of getting user input than through iostreams. But this should point you towards the information you need.
1,084,844
1,084,849
Will reading a file be faster with a FILE* or an std::ifstream?
I was thinking about this when I ran into a problem using std::ofstream. My thinking is that since std::ifstream, it wouldn't support random access. Rather, it would just start at the beginning and stream by until you get to the part you want. Is this just quick so we don't notice? And I'm pretty sure FILE* supports random access so this would be fast as well?
ifstream supports random access with seekg. FILE* might be faster but you should measure it.
1,084,935
1,084,958
C++ or Python as a starting point into GUI programming?
I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use with Qt). In my school we learned the basics with Turbo Pascal, VB and a voluntary C course, though right now i only know a hint of all the things i learned back then. Can you recommend me a way and a site or book (or two) that would bring me on that path (a perfect one would be one that teaches the language with help of the toolkit)? Thank you in advance.
Being an expert in both C++ and Python, my mantra has long been "Python where I can, C++ where I must": Python is faster (in term of programmer productivity and development cycle) and easier, C++ can give that extra bit of power when I have to get close to the hardware or be extremely careful about every byte or machine cycle I spend. In your situation, I would recommend Python (and the many excellent books and URLs already recommended in other answers).
1,084,960
1,085,033
Is it possible to treat macro's arguments as regular expressions?
Suppose I have a C++ macro CATCH to replace the catch statement and that macro receive as parameter a variable-declaration regular expression, like <type_name> [*] <var_name> or something like that. Is there a way to recognize those "fields" and use them in the macro definition? For instance: #define CATCH(var_declaration) <var_type> <var_name> = (<var_type>) exception_object; Would work just like: #define CATCH(var_type, var_name) var_type var_name = (var_type) exception_object; As questioned, I'm using g++.
You can't do it with just macros, but you can be clever with some helper code. template<typename ExceptionObjectType> struct ExceptionObjectWrapper { ExceptionObjectType& m_unwrapped; ExceptionObjectWrapper(ExceptionObjectType& unwrapped) : m_unwrapped(unwrapped) {} template<typename CastType> operator CastType() { return (CastType)m_wrapped; } }; template<typename T> ExceptionObjectWrapper<T> make_execption_obj_wrapper(T& eobj) { return ExceptionObjectWrapper<T>(eobj); } #define CATCH(var_decl) var_decl = make_exception_obj_wrapper(exception_object); With these definitions, CATCH(Foo ex); should work. I will admit to laziness in not testing this (in my defence, I don't have your exception object test with). If exception_object can only be one type, you can get rid of the ExceptionObjectType template parameter. Further more, if you can define the cast operators on the exception_object itself you can remove the wrappers altogether. I'm guessing exception_object is actually a void* or something though and your casting pointers.
1,084,982
1,085,920
Building Boost without filename decorations?
The default naming convention for the Boost C++ libraries is: libboost_regex-vc71-mt-d-1_34.lib where all libraries are built into the same directory. I'd like to modify the build process so that the filename does not contain the target architecture or build type (versions are okay). I want the file to end up in a different directory depending on the architecture being built for: vc71/debug/libboost-1_34.lib vc71/release/libboost-1_34.lib Any idea on how to do this?
You can remove all decoration from the library filenames by passing "--layout=system". Your example above shows "vc71/release" paths -- there's no out-of-box way to get this layout. You can do that with a bit of hackign. In Jamroot, find the 'stage-proper' target, which specifies the location as: <location>$(stage-locate)/lib You can modify that to specify different locations depending on properties, e.g: <variant>release:<location>$(stage-locate)/lib/release <variant>debug:<location>$(stage-locate)/lib/debug Please see Boost.Build website for more documentation
1,085,489
1,085,544
STL List to hold structure pointers
I have a structure called vertex and I created some pointers to them. What I want to do is add those pointers to a list. My code below, when it tries to insert the pointer into the list, creates a segmentation fault. Can someone please explain what is going on? #include <iostream> #include <list> #define NUM_VERTICES 8 using namespace std; enum { WHITE, GRAY, BLACK }; struct vertex { int color; int distance; char parent; }; int main() { //create the vertices vertex r = {WHITE, NULL, NULL}; //create pointer to the vertex structures vertex *pr = &r; //create a list to hold the vertices list<vertex*> *r_list = new list<vertex*>; list<vertex*>::iterator it; r_list->insert(it, pr); }
There are several things wrong here. First off, you aren't initializing the iterator, like other's have said: list<vertex*>::iterator it = r_list->begin(); Do this and your code will be fine. But your code is done in a bad manner. Why are you allocating the list from the heap? Look at your code: you have a memory leak. You aren't calling delete r_list anywhere. This is why you should use smart pointers (std::unique_ptr, std::shared_ptr if you have C++11, boost equivalents otherwise : boost::scoped_ptr and boost::shared_ptr) But better yet, just do it on the stack: //create a list to hold the vertices list<vertex*> r_list; list<vertex*>::iterator it = r_list->begin(); r_list.insert(it, pr); In addition, using the iterator to insert is going about things the long way. Just use push front() or push back(): //create a list to hold the vertices list<vertex*> r_list; r_list.push_back(pr); Another thing: if your list outlives the vertex you've constructed, it will be pointing to something invalid. For example: // global list<vertex*> r_list; void some_function(void) { //create the vertices vertex r = {WHITE, NULL, NULL}; //create pointer to the vertex structures vertex *pr = &r; r_list.push_back(pr); } // right here, vertex r stops existing: the list now contains an // invalid pointer. One solution is to store pointers to heap-allocated vertices: // global list<vertex*> r_list; void some_function(void) { //create the vertices vertex *r = new vertex; r->color = WHITE; r->distance = 0; r->parent = 0; r_list.push_back(r); } Now even after the function the list is pointing to a valid heap-allocated vertex. This now has the problem that when you're done using the list, you need to go through the lsit and call delete on each element. This problem is assisted by using the Boost Pointer Container Library. The best way, though, is to just store vertices themselves (rather than pointers to them): //create a list to hold the vertices list<vertex> r_list; //create the vertices vertex r = {WHITE, NULL, NULL}; r_list.push_back(r); If you give vertex a constructor, you can even just construct them in-place: struct vertex { int color; int distance; char parent; vertex(int _color, int _distance, char _parent) : color(_color), distance(_distance), parent(_parent) { } }; //create a list to hold the vertices list<vertex> r_list; r_list.push_back(vertex(WHITE, NULL, NULL)); (these are now outside your problem) Firstly, NULL is generally only used when dealing with pointers. Since distance and parent are not pointers, use 0 to initialize them, rather than NULL: //create the vertices vertex r = {WHITE, 0, 0}; Secondly, use constants rather than #define: #define NUM_VERTICES 8 // <- bad const int NumberVertices = 8; // <- good Lastly, give your enum a name, or place it in a namespace: enum Color { WHITE, GRAY, BLACK }; Hope these help!
1,085,490
1,085,547
How do C/C++ compilers work?
After over a decade of C/C++ coding, I've noticed the following pattern - very good programmers tend to have detailed knowledge of the innards of the compiler. I'm a reasonably good programmer, and I have an ad-hoc collection of compiler "superstitions", so I'd like to reboot my knowledge and start from the basics. Can anyone recommend links to online resources or favorite books? I'm particularly interested in C/C++ compiling, optimization, GCC and LLVM.
Start with the dragon book....(stress more on code optimization and code generation) Go onto write a toy compiler for an educational programming language like Decaf or Cool.., you may use parser generators (lex and yacc) for your front end(to make life easier and focus on more imp stuff).... Then read gcc internals book along with browsing gcc source code.
1,085,617
1,085,755
How does the centripetal Catmull–Rom spline work?
From this site, which seems to have the most detailed information about Catmull-Rom splines, it seems that four points are needed to create the spline. However, it does not mention how the points p0 and p3 affect the values between p1 and p2. Another question I have is how would you create continuous splines? Would it be as easy as defining the points p1, p2 to be continuous with p4, p5 by making p4 = p2 (that is, assuming we have p0, p1, p2, p3, p4, p5, p6, ..., pN). A more general question is how would one calculate tangents on Catmull-Rom splines? Would it have to involve taking two points on the spline (say at 0.01, 0.011) and getting the tangent based on Pythagoras, given the position coordinates those input values give?
Take a look at equation 2 -- it describes how the control points affect the line. You can see points P0 and P3 go into the equation for plotting points along the curve from P1 to P2. You'll also see that the equation gives P1 when t == 0 and P2 when t == 1. This example equation can be generalized. If you have points R0, R1, … RN then you can plot the points between RK and RK + 1 by using equation 2 with P0 = RK - 1, P1 = RK, P2 = RK + 1 and P3 = RK + 2. You can't plot from R0 to R1 or from RN - 1 to RN unless you add extra control points to stand in for R - 1 and RN + 1. The general idea is that you can pick whatever points you want to add to the head and tail of a sequence to give yourself all the parameters to calculate the spline. You can join two splines together by dropping one of the control points between them. Say you have R0, R1, …, RN and S0, S1, … SM they can be joined into R0, R1, …, RN - 1, S1, S2, … SM. To compute the tangent at any point just take the derivative of equation 2.
1,085,873
1,086,115
DLL memory manager mixup
I wrote an application which allows people to contribute plugins to extend the functionality. Such plugins are deployed as DLL files, which the framework picks up during runtime. Each plugin features a factory function which is called multiple times during the lifetime of the application to create objects. So far, in order to handle the ownership issue with these objects, I used a simple counting shared pointer on the returned objects so that they are destroyed whenever the last reference is removed. However, this tends to trigger crashes on Windows since it's not unlikely to happen that the object is new'ed in the plugin DLL but later (due to a deref() call on the shared pointer) deleted in the main application - and AFAIK this malloc/free mixup is a no-no on Windows. My current solution to this is to let deref() not call 'delete this;' directly but rather a 'release();' function which must be implemented by the plugins and calls 'delete this;'. However, it's quite annoying that each and every plugin has to implement this trivial function - I worked around this so far by providing a convenience macro plugin authors have to use. Does anybody have alternative ideas maybe? So far, my approach is that all objects contributed by plugins is allocated in the plugins and also released there - of course, an alternative might be to let all memory be allocated in the main application (by providing a pointer to a malloc-like function to the plugins which they can then call as needed) and released there as well. The issue with this is that it's not as convenient for the plugin authors, I think. I'd be interested in any other perspectives on this issue. UPDATE: I just realized that I could reimplement operator new and operator delete on the baseclass of the objects returned by the plugins, so that new'ing them and delete'ing them will always result in function calls into the same module (so that either all allocations and free's are done in the plugin, or in the framework).
There are two solutions. Solution one is "share more" - you can move new/delete across DLL boundaries if both sides use the same CRT DLL (/MD or /MDd in MSVC). Solution two is "share less" - let each DLL have its own C++ heap, and do not split new/delete across DLL boundaries.
1,086,179
1,086,216
Tiny C++ cross-platform GUI toolkit
Which C++ cross-platform GUI toolkit gives smallest footprint with both static and dynamic builds? I don't need a very sophisticated GUI, just basic controls & widgets.
the smallest one I've heard of is fltk
1,086,254
1,086,268
Read data directly from file to RAM in C++
Is there a way to directly read a binary file into RAM? What I mean is, is there a way to tell the compiler, here's the file, here's the block of RAM, please put the file contents in the RAM, off you go, quickly as you can please. Currently I'm stepping through the file with ifstream loading it into RAM (an array) 64bit block by 64 bit block. But I'm thinking that this must slow it down as it's like (here comes an analogy) using a thimble to bail the water out of a cup (the file) into a jug (the RAM) rather than just picking up the cup and tipping the entire contents into the jug in one go. As a relative newcomer to this I may have completely the wrong idea about this - any guidence would be a great help. I'm just after the quickest way to get a big file into RAM. Thanks
What prevents you from reading the file in one pass? Is it too big to fit in memory? You can also use mapped file, UNIX : mmap, Windows : CreateFileMapping
1,086,550
1,087,371
What are the concepts a vc++ developer should be familiar with?
I am a vc++ developer but I spend most of my time learning c++.What are all the things I should know as a vc developer.
I don't understand why people here post things about WinAPI, .NET, MFC and ATL. You really must know the language. Another benefit would be the cross platform libraries. C++ is not about GUI or Win32 programming. You can write Multi-Platform application with libraries like boost, QT, wxWidgets (may be some XML parser libs). Visual C++ is a great IDE to develop C++ application and Microsoft is trying hard to make Visual C++ more standard conform. Learning standard language without dialects (MS dialect as well) will give you an advantage of Rapid Development Environment combined with multi-platform portability. There are many abstraction libraries out there, which work equally on Windows, Linux, Unix or Mac OS. Debugger is a great app in VC++ but not the first thing to start with. Try to write unit tests for your application. They will ensure on next modifications that you did not broke other part of tested (or may be debugged:) code. Do not try to learn MFC or ATL from scratch, try to understand STL. MFC is old, and new version are more or less wrapper around ATL. ATL is some strange lib, which tries to marry STL-idioms (and sometimes STL itself) and WinAPI. But using ATL concepts without knowing what is behind, will make you unproductive as well. Some ATL idioms are very questionable and might be replaced by some better from boost or libs alike. The most important things to learn are the language philosophy and concepts. I suggest you to dive into the language and read some serious books: Design & Evolution of C++ by B. Stroustrup Inside the C++ Object Model by S. Lippman Design Patterns: Elements of Reusable Object-Oriented Software by GoF C++ Gotchas: Avoiding Common Problems in Coding and Design by S. Dewhurst Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions by. H. Sutter More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions by H. Sutter Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems, and Solutions by H. Sutter When here you will be a very advanced C++ developer Next books will make guru out of you: Modern C++ Design: Generic Programming and Design Patterns Applied by A. Alexandrescu C++ Templates: The Complete Guide by by D. Vandevoorde, N. Josuttis C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond by D. Abrahams, A. Gurtovoy Large-Scale C++ Software Design by J. Lakos Remember one important rule: If you have a question, try to find an answer to it in ISO C++ Standard (i.e. Standard document) first. Doing so you will come along many other similar things, which will make you think about the language design. Hope that book list helps you. Concepts from these books you will see in all well designed modern C++ frameworks. With Kind Regards, Ovanes
1,086,632
1,086,687
PostMessage params from 32-bit C# to 64-bit C++
I am having problem with the contents of a pointer passed as the wParam from a 32-bit C# application is changing along the way to a 64-bit C++ process. There are two processes 32.exe (in C#) and 64.exe (in C++). 64.exe is started as a child process of 32.exe. 32.exe post window message for 64.exe, one of which has a wParam that is a pointer to an array of RECT structures. Both 64.exe and 32.exe have a common DLL (written in C++, but compiled for different platforms, of course), called 32.dll and 64.dll. A function expecting a RECT* in 32.dll is called directly from 32.exe with the same RECT* that is later posted, and this works well. Afterwards it posts a message to 64.exe, which calls the same function and casts the wParam to RECT*: else if (WM_SetDisabledAreas == message) { SetDisabledAreas((RECT*)wParam, (UINT)lParam); } The message is posted as follows: if (Is64Bit() && SubProcess64 != null) { Win32.PostMessage(SubProcess64.MainWindowHandle, WindowMessages.SetDisabledAreas, (uint)pointer.ToInt32(), length); } MessageBox.Show(pointer.ToString()); DLL32.SetDisabledAreas(pointer, length); By debugging I've validated that the message is received, however the wParam address is not the same as it was before. This is not unexpected, but the contents of the memory it now points to is undefined (and I get an access violation when attempting to see what is there). What is happening here?
Each of the two processes has an own address space, so that the pointer from process 32.exe is not valid in 64.exe. However, this has nothing to do with 32bit vs 64bit at all. You just have to use an interprocess communication technique of your choice to transfer the data between the two processes. For example, you could use CreateFileMapping to create a named section of shared memory.
1,086,786
1,087,344
C++ Dependencies manager
We have here a pretty big application that is taking a lot of time to compile and I am looking for a way to reduce this compile time. I thought a good way to do this would be to reduce the dependency between the include files. Do you know any good dependency/Includes manager that would be pretty cheap? Something that would draw me a good graphic and show me where are the "dependencies bottleneck". Thank you.
You could use Source Navigator to analyze the source. Look at the section: Using the Include Browser in here. Or a better option would be to use cinclude2dot
1,086,798
1,088,080
Differences between different flavours of shared_ptr
Are there any differences between boost::shared_ptr, std::tr1::shared_ptr and the upcoming (in C++0x) std::shared_ptr? Will porting from one to another have any overhead or are they basically the same?
According to the Boost website, the boost::shared_ptr... ...conforms to the TR1 specification, with the only exception that it resides in namespace boost instead of std::tr1. According to the Wikipedia C++0x page The TR1 implementation lacked certain pointer features such as aliasing and pointer arithmetic, but the C++0x version will add these. If your code works with the TR1/Boost version, it should work with the C++0x version (but not necessarily vice versa).
1,087,042
1,087,066
C++ new int[0] -- will it allocate memory?
A simple test app: cout << new int[0] << endl; outputs: 0x876c0b8 So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?
From 5.3.4/7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. From 3.7.3.1/2 The effect of dereferencing a pointer returned as a request for zero size is undefined. Also Even if the size of the space requested [by new] is zero, the request can fail. That means you can do it, but you can not legally (in a well defined manner across all platforms) dereference the memory that you get - you can only pass it to array delete - and you should delete it. Here is an interesting foot-note (i.e not a normative part of the standard, but included for expository purposes) attached to the sentence from 3.7.3.1/2 [32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.]
1,087,088
1,087,106
Single quote issues with C++ find and replace function
Here is my code for finding a sequence in a string and replacing it with another: std::string find_and_replace( string &source, string find, string replace ) { size_t j; for ( ; (j = source.find( find )) != string::npos ; ) { source.replace( j, find.length(), replace ); } return source; } Everything works fine when I call something like: find_and_replace(test, "foo", "bar") My application requires me to replace a single quote with two single quotes, not a double quote. For example I would call: find_and_replace(test, "'", "''") But whenever I call this, the function freezes up for some reason. Does anyone know what might be the cause of this problem? Edit: based on the answers I've gotten, I have fixed the code: std::string find_and_replace( string &source, string find, string replace ) { string::size_type pos = 0; while ( (pos = source.find(find, pos)) != string::npos ) { source.replace( pos, find.size(), replace ); pos += replace.size(); } return source; } I hope this helps some people having the same problem.
You've got an infinite loop because your condition doesn't move forward. You're always running j = source.find( find ), but you're replacing ' with '', so you're always finding the first apostrophe every time and adding a new apostrophe to the string. You need to make sure you don't match the same apostrophe twice by moving where you're scanning forward every time you replace something. The find function takes a second parameter which is the starting position in the string to look for the substring. Once you've found the position of the first match, move the starting position up to that position plus the length of the string you're replacing it with.
1,087,199
1,087,372
boost::asio: How do I use async_accept to accept incoming connections?
I'm using boost::asio, and I have code like this: void CServer::Start(int port) { tcp::acceptor acceptor(m_IoService, tcp::endpoint(tcp::v4(), port)); for ( ;; ) { shared_ptr<tcp::socket> pSocket(new tcp::socket(m_IoService)); acceptor.accept(*pSocket); HandleRequest(pSocket); } } This code works, but I'd like to switch to using Acceptor::async_accept so that I can call Acceptor::cancel to stop receiving requests. So my new code looks like this: void CServer::StartAsync(int port) { m_pAcceptor = shared_ptr<tcp::acceptor>( new tcp::acceptor(m_IoService, tcp::endpoint(tcp::v4(), port)) ); StartAccept(); } void CServer::StopAsync() { m_pAcceptor->cancel(); } void CServer::StartAccept() { shared_ptr<tcp::socket> pSocket(new tcp::socket(m_IoService)); m_pAcceptor->async_accept(*pSocket, bind(&CServer::HandleAccept, this, pSocket)); } void CServer::HandleAccept(shared_ptr<tcp::socket> pSocket) { HandleRequest(pSocket); StartAccept(); } But this code doesn't seem to work, my function CServer::HandleAccept never gets called. Any ideas? I've looked at sample code, and the main difference between my code and theirs is they seem often make a class like tcp_connection that has the socket as a member, and I'm not seeing why thats necessary. Alex
Ah, looks like to kick things off you need to run the IOService, e.g.: m_IoService.run();
1,087,514
1,087,729
std::vector visualizer doesn't work properly on std::vector<boost::variant>
The visual studio std::vector visualizer in the VS2008 autoexp.dat file doesn't seem to work if I have a std::vector<boost::variant<...>>. It does work on other types of vectors I have tried (e.g std::vector<int>, std::vector<boost::shared_ptr<..>>) Here is the visualizer code: std::vector<*>{ children ( #array ( expr : ($e._Myfirst)[$i], size : $e._Mylast-$e._Myfirst ) ) preview ( #( "[", $e._Mylast - $e._Myfirst , "](", #array ( expr : ($e._Myfirst)[$i], size : $e._Mylast-$e._Myfirst ), ")" ) ) } Instead of showing the number of items and the item values, the preview shows {_Myfirst= _Mylast= _Myend= } And the children, which should be the vector items, are the actual vector members. It's as if the std::vector visualizer didn't exist. I took a screenshot of the watch window. You can see how it displays the std::vector<boost::variant<int, std::string>> wrong, and then displays the next two vectors correctly: Hyperlink to screenshot Does anyone know what is causing this and how to stop it happening? Thanks!
It seems to be a bug related to the size of the name of your type... boost::variant generates types with very long names. I've made some tests, and it seems that the limit is a struct with name size of 497 characters. The following code reproduces the error... take the last character of the struct name, and it works fine! struct abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopq { }; int main() { std::vector< abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopqrstuvwxyz012345abcdefghijklmnopq > test2; test2.resize(10); return 0; } Feel free to report the bug on http://connect.microsoft.com/
1,087,537
1,090,268
Remove border on activex ie control
For the application im building, i use an activex ie control. It works greate but i cant work out how to remove the border around it. I have tried overriding the invoke call and setting DISPID_BORDERSTYLE to zero but it looks like it never gets hit. Any ideas?
I think you need to implement IDocHostUIHandler on your host. then in GetHostInfo you can return the DOCHOSTUIFLAG_NO3DBORDER or DOCHOSTUIFLAG_NO3DOUTERBORDER flag.
1,087,580
1,088,910
Resource temporarily unavailable in Boost ASIO
I get the error message "Resource temporarily unavailable" when I use the method receive_from(), it's a member of ip::udp::socket located here. I pass to it: boost::asio::buffer, pointer to an endpoint object, flags (set to zero), and an error_code object. I create the endpoint with just new udp::endpoint() There doesn't seem to be too much information available on this error message too. I've tried it on several machines and always get this error.
"Resource temporarily unavailable" is normally the text description for EAGAIN, indicating that the operation should be retried. In the case of UDP, it indicates that there isn't any data available at present, and you should try later. It's generally worth looking at the man page for the underlying libc function; which is recvfrom in this case.
1,087,600
1,087,662
Pointers to virtual member functions. How does it work?
Consider the following C++ code: class A { public: virtual void f()=0; }; int main() { void (A::*f)()=&A::f; } If I'd have to guess, I'd say that &A::f in this context would mean "the address of A's implementation of f()", since there is no explicit seperation between pointers to regular member functions and virtual member functions. And since A doesn't implement f(), that would be a compile error. However, it isn't. And not only that. The following code: void (A::*f)()=&A::f; A *a=new B; // B is a subclass of A, which implements f() (a->*f)(); will actually call B::f. How does it happen?
Here is way too much information about member function pointers. There's some stuff about virtual functions under "The Well-Behaved Compilers", although IIRC when I read the article I was skimming that part, since the article is actually about implementing delegates in C++. http://www.codeproject.com/KB/cpp/FastDelegate.aspx The short answer is that it depends on the compiler, but one possibility is that the member function pointer is implemented as a struct containing a pointer to a "thunk" function which makes the virtual call.
1,087,610
1,087,686
Working with imperial units
I'm toying with an application that is, roughly speaking, a sort of modeler application for the building industry. In the future I'd like it to be possible for the user to use both SI units and imperial. From what I understand, it's customary in the US building industry to use fractions of inches when specifying measurements, eg 3 1/2" - whereas in SI we'd write 3.5, not 3 1/2. I'm looking for a way to work with these different systems in my software - storing them, doing calculations on them etc, not only parsing what a users enters. It should be able to show the user a measurement in the way he entered it, yet being able to calculate with other measurements - for example add 3 cm to 1 1/2 inch. So if a user draws a length of wall of 5 feet and another one of 3 meters, the total measurement should be shown in the default unit system the user selected. I'm undecided yet on how much flexibility I should add for entering data for the user; e.g. if he enters 1 foot 14 inches, should it should 2 feet 2 inches the next time the measurement is shown? However before I decide things like that, I'm looking for a way to store measurements in an exact form, which is what my question is about. I'm using C++ and I've looked at Boost.Units, but that doesn't seem to offer a way to deal with fractions. The simple option is to convert everything to millimeters, but rounding errors would make it impossible to go back to the exact measurement a user entered (if he entered it in imperial measurements). So I'll need something more complex. For now I'm using a class that is tentatively named 'Distance' and looks conceptually like this: class Distance { public: Distance(double value); // operators +, -, *, / Distance operator+(const Distance& that); ...etc... std::string StringForm(); // Returns a textual form of the value Distance operator=(double value); private: <question: what should go here?> } This clearly shows where my problems are. The most obvious thing to do would be to have an enum that says whether this Distance is storing SI or imperial units, and have fields (doubles, presumably) that store the meters, centimeters and millimeters if it's in SI units and feet and inches if it's imperial. However this will make the implementation of the class littered with if(SI) else ..., and is very wasteful in memory. Plus I'd have to store a numerator and denominator for the feet and inches to be able to exactly store 1/3", for example. So I'm looking for general design advice on how I should solve these problems, given my design requirements. Of course if there's a C++ library out there that already does these things, or a library in another language I could look at to copy concepts from, that would be great.
Take a look at Martin Fowler's Money pattern from Patterns of Enterprise Application Architecture - it is directly applicable to this situation. Recommended reading. Fowler has also posted a short writeup on his site of the Quantity pattern, a more generic version of Money.
1,087,627
1,093,087
How can I target a specific version of the C++ runtime?
We have a very large project mostly written in C# that has some small, but important, components written in C++. We target the RTM of .NET 2.0 as the minimum required version. So far, in order to meet this requirement we've made sure to have only the RTM of .NET 2.0 on our build box so that the C++ pieces link against that version. Update: The C++ assembly that is causing the issue is a mixed-mode C++ assembly being loaded into a managed process. Unfortunately when the confiker was set to do something on April 1st, our corporate IT made a huge push to get everything patched and up to date, and as a result everything up through 3.5 SP1 got installed on the build box. We've tried uninstalling everything, which has happened before, but now we are unable to meet our minimum requirements as anything built on that particular box requires .NET 2.0 SP1. Since the box seems to be hosed in that we can't just uninstall the offending versions, is there any way to build the assemblies and explicitly tell them to use the RTM of .NET 2.0 (which is v2.0.50727.42)? I've seen pages that refer to using a manifest, but I can't figure out how to actually implement a proper manifest and get it into the assemblies. My expertise is in the managed world, so I'm at a bit of a loss on this. Can anyone explain how I can make these assemblies target the .NET 2.0 RTM SxS assemblies? Thanks!
While I'm pretty sure that Christopher's answer and code sample (thank you, Christopher!) is part of a more elegant solution, we were under the gun to get this out the door and found a very similar, but different, solution. The first step is to create a manifest for the assembly: <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.CRT' version='8.0.50608.0' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly> Next you have to set the 'Generate Manifest' option to 'No' under Configuration Properties -> Linker -> Manifest File, and set the 'Embed Manifest' option to 'No' under Configuration Properties -> Manifest Tool -> Input and Output. Finally, to get your new manifest into the assembly add the following command to the project's post-build step: mt.exe /manifest "$(ProjectDir)cppassembly.dll.manifest" /outputresource:"$(TargetDir)\cppassembly.dll";#2 -out:"$(TargetDir)\cppassembly.dll.manifest" Once built we can open the dll in Visual Studio to view the manifest under RT_MANIFEST and confirm that it has our manifest! When I put Christopher's code in the stdafx.h it ended up adding it as an additional dependency...the manifest was still looking for v8.0.50727.762. The manifest it generated looked like this: <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC80.DebugCRT" version="8.0.50608.0" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC80.DebugCRT" version="8.0.50727.762" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC80.CRT" version="8.0.50727.762" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity> </dependentAssembly> </dependency> </assembly> I could not track down another switch that would remove or clear existing dependencies. I like Christopher's approach better than a post-build step, but for now this works. If anyone has any additional input on how to clear out any existing dependencies that'd be great. Thanks!
1,087,771
1,087,782
Do I need to synchronize thread access to an int?
I've just written a method that is called by multiple threads simultaneously and I need to keep track of when all the threads have completed. The code uses this pattern: private void RunReport() { _reportsRunning++; try { //code to run the report } finally { _reportsRunning--; } } This is the only place within the code that _reportsRunning's value is changed, and the method takes about a second to run. Occasionally when I have more than six or so threads running reports together the final result for _reportsRunning can get down to -1. If I wrap the calls to _runningReports++ and _runningReports-- in a lock then the behaviour appears to be correct and consistent. So, to the question: When I was learning multithreading in C++ I was taught that you didn't need to synchronize calls to increment and decrement operations because they were always one assembly instruction and therefore it was impossible for the thread to be switched out mid-call. Was I taught correctly, and if so, how come that doesn't hold true for C#?
A ++ operator is not atomic in C# (and I doubt it is guaranteed to be atomic in C++) so yes, your counting is subject to race conditions. Use Interlocked.Increment and .Decrement System.Threading.Interlocked.Increment(ref _reportsRunning); try { ... } finally { System.Threading.Interlocked.Decrement(ref _reportsRunning); }
1,087,870
1,087,940
Drawing a full screen Quad?
What's wrong with this: pVertexBuffer[0].Position = D3DXVECTOR3(0.0f,0.0f,0.0f); pVertexBuffer[0].TexCoord = D3DXVECTOR2(0.0f,0.0f); pVertexBuffer[1].Position = D3DXVECTOR3(m_ScreenResolutionX,0.0f,0.0f); pVertexBuffer[1].TexCoord = D3DXVECTOR2(1.0f,0.0f); pVertexBuffer[2].Position = D3DXVECTOR3(0.0f,m_ScreenResolutionY,0.0f); pVertexBuffer[2].TexCoord = D3DXVECTOR2(0.0f,1.0f); pVertexBuffer[3].Position = D3DXVECTOR3(0.0f,m_ScreenResolutionY,0.0f); pVertexBuffer[3].TexCoord = D3DXVECTOR2(0.0f,1.0f); pVertexBuffer[4].Position = D3DXVECTOR3(m_ScreenResolutionX,0.0f,0.0f); pVertexBuffer[4].TexCoord = D3DXVECTOR2(1.0f,0.0f); pVertexBuffer[5].Position = D3DXVECTOR3(m_ScreenResolutionX,m_ScreenResolutionY,0.0f); pVertexBuffer[5].TexCoord = D3DXVECTOR2(1.0f,1.0f); if i try to render this, i don't see anything. in the vertex shader i use these vertex positions without transforming them.
Vertex shaders output vertices in homogenous screenspace coordinates; they are usually screen resolution independent. In other words, you should output coordinates from (-1,-1,0) to (1, 1, 0).
1,087,927
1,088,019
Function that prints something to std::ostream and returns std::ostream?
I want to write a function that outputs something to a ostream that's passed in, and return the stream, like this: std::ostream& MyPrint(int val, std::ostream* out) { *out << val; return *out; } int main(int argc, char** argv){ std::cout << "Value: " << MyPrint(12, &std::cout) << std::endl; return 0; } It would be convenient to print the value like this and embed the function call in the output operator chain, like I did in main(). It doesn't work, however, and prints this: $ ./a.out 12Value: 0x6013a8 The desired output would be this: Value: 12 How can I fix this? Do I have to define an operator<< instead? UPDATE: Clarified what the desired output would be. UPDATE2: Some people didn't understand why I would print a number like that, using a function instead of printing it directly. This is a simplified example, and in reality the function prints a complex object rather than an int.
You can't fix the function. Nothing in the spec requires a compiler to evaluate a function call in an expression in any particular order with respect to some unrelated operator in the same expression. So without changing the calling code, you can't make MyPrint() evaluate after std::cout << "Value: " Left-to-right order is mandated for expressions consisting of multiple consecutive << operators, so that will work. The point of operator<< returning the stream is that when operators are chained, the LHS of each one is supplied by the evaluation of the operator to its left. You can't achieve the same thing with free function calls because they don't have a LHS. MyPrint() returns an object equal to std::cout, and so does std::cout << "Value: ", so you're effectively doing std::cout << std::cout, which is printing that hex value. Since the desired output is: Value: 12 the "right" thing to do is indeed to override operator<<. This frequently means you need to either make it a friend, or do this: class WhateverItIsYouReallyWantToPrint { public: void print(ostream &out) const { // do whatever } }; ostream &operator<<(ostream &out, const WhateverItIsYouReallyWantToPrint &obj) { obj.print(out); } If overriding operator<< for your class isn't appropriate, for example because there are multiple formats that you might want to print, and you want to write a different function for each one, then you should either give up on the idea of operator chaining and just call the function, or else write multiple classes that take your object as a constructor parameter, each with different operator overloads.
1,087,987
1,088,155
C++ operator new, object versions, and the allocation sizes
I have a question about different versions of an object, their sizes, and allocation. The platform is Solaris 8 (and higher). Let's say we have programs A, B, and C that all link to a shared library D. Some class is defined in the library D, let's call it 'classD', and assume the size is 100 bytes. Now, we want to add a few members to classD for the next version of program A, without affecting existing binaries B or C. The new size will be, say, 120 bytes. We want program A to use the new definition of classD (120 bytes), while programs B and C continue to use the old definition of classD (100 bytes). A, B, and C all use the operator "new" to create instances of D. The question is, when does the operator "new" know the amount of memory to allocate? Compile time or run time? One thing I am afraid of is, programs B and C expect classD to be and alloate 100 bytes whereas the new shared library D requires 120 bytes for classD, and this inconsistency may cause memory corruption in programs B and C if I link them with the new library D. In other words, the area for extra 20 bytes that the new classD require may be allocated to some other variables by program B and C. Is this assumption correct? Thanks for your help.
You are correct the memory size is defined at compile time and applications B/C would be in danger of serious memory corruption problems. There is no way to handle this explicitly at the language level. You need to work with the OS to get the appropriate shared libraries to the application. You need to version your libraries. As there is no explicit way of doing this with the build tools you need to do it with file names. If you look at most products this is approx how they work. In the lib directory: libD.1.00.so libD.1.so -> libD.1.00.so // Symbolic link libD.so -> libD.1.so // Symbolic link Now at compile time you specify -lD and it links against libD.1.00.so because it follows the symbolic links. At run time it knows to use this version as this is the version it compiled against. So you now update lib D to version 2.0 In the lib directory: libD.1.00.so libD.2.00.so libD.1.so -> libD.1.00.so // Symbolic link libD.2.so -> libD.2.00.so // Symbolic link libD.so -> libD.2.so // Symbolic link Now when you build with -libD it links against version 2. Thus you re-build A and it will use version 2 of the lib from now on; while B and C will still use version 1. If you rebuild B or C it will use the new version of the library unless you explicitly use an old version of the library when building -libD.1 Some linkers do not know to follow symbolic links very well so there are linker commands that help. gcc use the '-install_name' flag your linker may have a slightly different named flag. As a runtime check it is usally a good idea to put version information into your shared objects (global variable/function call etc). Thus at runtime you can retrieve the shared libraries version information and check that your application is compatible. If not you should exit with the appropriate error message. Also note: If you serialize objects of D to a file. You know need to make sure that version information about D is maintained. Libd.2 may know how to read version 1 D objects (with some explicit work), but the inverse would not be true.
1,088,226
1,088,255
How do I *not* delete a member in a destructor?
I'd like the destructor of my class to delete the entire object except for one of the members, which is deleted elsewhere. First of all, is this totally unreasonable? Assuming it's not, how do I do this? I thought that created an destructor with an empty body would prevent all the members from being deleted (because the destructor wouldn't do anything), but that doesn't seem to be the case.
Short answer: You don't. Longer answer: If the "member" is actually a pointer to some other allocation, you can arrange to not delete the other allocation. But usually, if you allocated the other block in the constructor, you want to delete it in the destructor. Anything else will require careful handling of the "ownership" of the block in question. It will be a lot like memory management in plain c. Possible, but fraught with danger. Good luck.
1,088,290
1,088,295
#define statements within a namespace
If I have a #define statement within a namespace as such: namespace MyNamespace { #define SOME_VALUE 0xDEADBABE } Am I correct in saying that the #define statement is not restricted to the namespace? Is the following the "correct" thing to do? namespace MyNamespace { const unsigned int SOME_VALUE = 0xDEADBABE; }
Correct,#define's aren't bound by namespaces. #define is a preprocessor directive - it results in manipulation of the source file prior to being compiled via the compiler. Namespaces are used during the compilation step and the compiler has no insight into the #define's. You should try to avoid the preprocessor as much as possible. For constant values like this, prefer const over #define's.
1,088,520
1,088,722
Are there Windows API binaries for Subversion or do I have to build SVN to call the API from Windows C++?
I want to call a Subversion API from a Visual Studio 2003 C++ project. I know there are threads here, here, here, and here that tell how to get started with C#.NET on Windows (the consensus seems to be SharpSvn, which I've used easily and successfully on another project) but that's not what I want. I've read the chapter on using APIs in the red-bean book which says: Subversion is primarily a set of C libraries, with header (.h) files that live in the subversion/include directory of the source tree. These headers are copied into your system locations (e.g., /usr/local/include) when you build and install Subversion itself from source. These headers represent the entirety of the functions and types meant to be accessible by users of the Subversion libraries. I'd like to use CollabNet Subversion but there doesn't seem to be API binary downloads, and I'd just as soon not build the whole thing if I can avoid it. Considering another approach, I found RapidSVN's C++ API, but it doesn't appear to offer Windows API binaries either and seems to require building SVN (which I would be willing to do as a last choice if RapidSVN's API is higher-level than the stock SVN offering.) Does calling the API from C++ in Windows have to be this much more work compared to using SharpSvn under .NET, or is there something I haven't found that would help me achieve my goal?
You need the dev (e.g. svn-win32-1.6.16_dev.zip) package from here. Probably download also the binaries (e.g. svn-win32-1.6.16.zip) of the tools (DLLs are there).
1,088,689
1,088,990
Boost::any and polymorphism
I am using boost::any to store pointers and was wondering if there was a way to extract a polymorphic data type. Here is a simple example of what ideally I'd like to do, but currently doesn't work. struct A {}; struct B : A {}; int main() { boost::any a; a = new B(); boost::any_cast< A* >(a); } This fails because a is storing a B*, and I'm trying to extract an A*. Is there a way to accomplish this? Thanks.
The other way is to store an A* in the boost::any and then dynamic_cast the output. Something like: int main() { boost::any a = (A*)new A; boost::any b = (A*)new B; A *anObj = boost::any_cast<A*>(a); B *anotherObj = dynamic_cast<B*>(anObj); // <- this is NULL anObj = boost::any_cast<A*>(b); anotherObj = dynamic_cast<B*>(anObj); // <- this one works! return 0; }
1,088,821
1,089,200
Keeping C# and C++ classes in sync at runtime?
My application is built in two sections. A C# executable which is the front end UI and a C++ dll which is more the low-level stuff. My application creates and manages many instances of objects, where every C++ object instance has a corresponding C# object instance. What techniques or libraries can I use to ensure that objects in the C# and C++ sections and data in those objects are always in sync at runtime? A change of one member in one object instance should update the corresponding object instance. Thanks! Edit: clarified a little what I meant by keeping the objects in "sync"
It's not quite clear whether it would solve the problem, but have you considered Managed C++? I have had pretty good success simply compiling my C++ code as Managed C++, then using the managed extensions to create .NET classes that use the underlying C++ data directly. That way, there's only one copy of the data. Probably not suitable for every situation (and I haven't tested its limits by any means) but I found it quite a timesaver. And since Managed C++ is a proper .NET language, the result was clean to use from the C# side, with none of the usual oddities or quirks one often has to work around when trying this sort of thing. (Another similar approach would be to use SWIG (http://www.swig.org/) to generate wrappers for you. I hear it is easy to use and works well, but I haven't used it myself.)
1,089,176
1,089,181
is size_t always unsigned?
As title: is size_t always unsigned, i.e. for size_t x, is x always >= 0 ?
Yes. It's usually defined as something like the following (on 32-bit systems): typedef unsigned int size_t; Reference: C++ Standard Section 18.1 defines size_t is in <cstddef> which is described in C Standard as <stddef.h>. C Standard Section 4.1.5 defines size_t as an unsigned integral type of the result of the sizeof operator
1,089,217
1,089,260
Functional programming in C++11, F# style
I've been looking at the new features in C++11 and it really looks like it will be possible to program in a very functional programming style using it. I've gotten use to using the types List, Seq, Array in F# and I see no reason why their members couldn't be ported into some sort of C++11 template. What problems or advantages do you see in using C++11 vs something like F# for a mixed functional programming style? Maybe the Boost guys will make a new functional once C++11 comes out.
The biggest problem with trying to program in a functional style in C++ is that it does not support tail recursion. In a functional language you don't have to worry about stack explosion when you tail recurse correctly, but in C++ you always have to worry about that. Therefore, many "functional" type algorithms will be clumsy or heavy.
1,089,296
2,036,855
Memory leak in Mixed Mode C++/CLR application
I'm having problems with a slow memory leak in my mixed mode C++/CLR .NET application. (It's C++ native static libraries linked into a VS2008 C++/CLR Windows Forms app with the "/clr" compiler setting) Typical behaviour: app starts using 30 MB (private memory). Then leaks memory slowish, say a MB every hour when running under simulated heavy load. This simulates the app being live for days or weeks. I've tried using several tools to track down memory leaks including both the CRT debugging stuff that comes with the Visual Studio CRT libs. I've also used a commercial leak detection tool ("Memory Validator"). Both report negligible memory leaks at shutdown (a few minor entries that amount to a few KB that I'm not worried about). Also, I can see when running that the tracked memory doesn't seem to amount to that much (so I don't believe it is just memory that is being held and only released at app exit). I get around 5 MB of listed memory (out of total > 30MB). The tool (Memory Validator) is setup to track all memory usage (including malloc, new, Virtual memory allocation and a whole bunch of other types of memory allocation). Basically, every setting for which memory to track has been selected. The .NET image reports that it is using around 1.5 MB of memory (from perfmon). Here's a final bit of information: we have a version of the app which runs as a native console application (purely native - not CLR at all). This is 95% the same as the mixed mode except without the UI stuff. This doesn't seem to leak memory at all, and peaks at around 5MB private bytes. So basically what I'm trying to get across here is that I don't think any of the native code is leaking memory. Another piece of the puzzle: I found this which refers to memory leaks in mixed mode applications when targeting 2.0 framework (which I am): http://support.microsoft.com/kb/961870 Unfortunately the details are infuriatingly sparse so I'm not sure if it's relevant. I did try targeting 3.5 framework instead of 2.0 but still had the same problem (maybe I didn't do this right). Anyone have any suggestions? A few things that might help me: Are there any other kind of memory allocations that I'm not tracking? How come the figures don't add up? I get 5 MB of CRT memory usage, 1.5 MB of .NET memory so how come the whole app uses 30MB private bytes? Is that all tied up in the .NET framework? Why don't I see these in the leak tool? Won't the .NET framework appear as some kind of allocated memory? Any other leak detection tools which work well with mixed mode apps? Thanks for any help John
OK I finally found the problem. It was caused by an incorrect setting for /EH (Exception Handling). Basically, with mixed mode .NET apps, you need to make sure all statically linked libs are compiled with /EHa instead of the default /EHs. (The app itself must also be compiled with /EHa, but this is a given - the compiler will report error if you don't use it . The problem is when you link in other static native libs.) The problem is that exceptions caught in the managed bit of the app, which were thrown within native libraries compiled with /EHs end up not handling the exception correctly. Destructors for C++ objects are not then called correctly. In my case, this only occurred in a rare place, hence why it took me ages to spot.
1,089,437
1,089,557
Learning C++ from scratch in Visual Studio?
I need to get up to speed with C++ quite quickly (I've never used it previously) - is learning through Visual Studio (i.e. Managed C++) going to be any use? Or will I end up learning the extensions and idiosyncracies of C++ in VS, rather then the language itself? If learning in VS is not recommended, what platform / IDE do you guys suggest? Edit: Can anyone elaborate on what VS will hide or manage for me when coding unmanaged C++? I really need to be learning things like pointers, garbage collection and all the nuts and bolts of the low level language.. does VS abstract or hide any of this kind of stuff from you? Thanks for all the suggestions..
Visual Studio (or the free version, Visual C++ Express) is a perfectly fine choice on Windows. On Linux, you'll probably end up using GCC. Both are fine compilers. Visual C++ supports both "real" native C++ and C++/CLI, the managed .NET version, so if you want to learn C++, simply create a regular C++ project. If you're concerned with learning "proper" standard C++, note that the compiler by default enables a number of Microsoft extensions, which you may want to disable. (Project properties -> C/C++ -> Language -> Disable Language Extensions). For the record, GCC has similar extensions (which can be disabled by calling the compiler with --ansi), so this isn't just Microsoft being big and evil and nonstandard. ;)
1,089,490
1,090,733
Eclipse CDT: How to reference 3rd party includes via a Relative path
I'm new to Eclipse-CDT, setting up a new project for the first time. I'm trying to reference Boost without hardcoding an absolute path. I've put boost in my workspace folder, e.g. /home/user/workspace/boost_1_39_0 I was then hoping to add an include directory pointing to that folder relative to the workspace, but Eclipse won't do that, it seems to only want to point to thinks in /home/user/workspace/[MyProjectNameHere] Any tips? It doesn't seem to make sense to copy Boost into my project folder, because then it shows up in Eclipse and Eclipse wants to build it (sure, I could exclude it). Alex
When adding an include file path in the CDT project (Project Properties/C/C++ General/Paths and Symbols), there are 3 buttons to browse for a location: Variables... Workspace... File system... If you press the Workspace... button, the path will be relative to the workspace/project. If you select the Variables... button, you'll get to incorporate variables such as ${WorkspaceDirPath}. The variables can also reference environment variables, which might be handy if you want a single install of boost to be referenced from projects that might reside anywhere on your machine. If you incorporate variables into the path, make sure the "Is a workspace path" option is checked - otherwise the variable seems to get evaluated when you press "OK" instead of staying a variable to be evaluated at build time.
1,089,679
1,089,711
Designing a class architecture for network messages
I have client/server applications and a very simple protocol for communication. More precisely, it's a set of commands a server sends and a set of requests a client can make. The idea is as follows: When a command is made by the server, a client has to execute it. When a request is made, server checks permissions and if everything is ok it grants the request. The application is written in C++ and I got slightly stuck designing the architecture for this sort of communication protocol. Assuming that command/request is a tab-delimited string with first parameter being the name of the message, I was planning to make a MessageManager class which would store all messages in a hash-table and retrieve them when necessary. The problem here is this: typedef std::vector< std::string > ArgArray; class Request : public Message { public: Request( const char *name ) : Message( name ) { } #ifdef CLIENT /** problem here **/ virtual void make( ... ) = 0; #elif defined SERVER virtual void grant( const Client &c, const ArgArray &params ) const = 0; protected: virtual void checkPermissions( const Client &c, const ArgArray &params ) const = 0; #endif }; Because different messages can take different arguments to be constructed I can't really create a complete interface. For example, some messages might need a simple string to be constructed, whereas others might need some numeric data. This complicates things and makes the design a bit untidy... I.e. I have to get round the problem by ommitting make() from interface definition and simply add different make() for each Request I make. Also, if I wish to store pointers to different Requests in one container I cannot use dynamic_cast because Request is not a polymorphic type. An obvious (untidy) solution would use make( int n, ... ) definition and use stdarg.h to extract different arguments but I consider this to be unsafe and confusing for the programmer. There is obviously a design flaw in my idea. I already have a solution in mind but I am just wondering, how would people at SO tackle this problem? What sort of Object architecture would you use? Is there a simpler approach that could solve this problem? There aren't any specific requirements to this except to keep it as simple as possible and to keep the actual protocol as it is (tab-delimited strings with first parameter indicating which message it is).
I think the problem in your design is that you tried to cram too many functionality into one class. For example, the part about constructing/parsing messages to contain numeric data or string (i.e. serialization) should be separate from the underlying connection logic. Check out Boost.Serialization if you are allowed to use additional libraries. Boost has got a very nice network library too called ASIO. Even if you are not allowed to use boost you should probably consult their library design.
1,089,828
1,089,847
Same Header File for both DLL and Static Library
So the common (at least VS 2005 states) way to define exports/imports for a DLL is: #ifdef MY_EXPORTS #define MY_API __declspec(dllexport) #else #define MY_API __declspec(dllimport) #endif class MY_API MyClass { ... }; This works great if I'm just building my code as a DLL. However, I want to have the option of using a static library OR a DLL. Now one obvious (but terrible) solution, is to copy all the code, removing the DLL 'MY_API' defines. Now what would seem a much better approach is a command line switch to either define, or not define the DLL stuff. However in the case of a static library what should 'MY_API' be? #ifdef DLL_CONFIG #ifdef MY_EXPORTS #define MY_API __declspec(dllexport) #else #define MY_API __declspec(dllimport) #endif #else #define MY_API // What goes here? #endif class MY_API MyClass { ... }; Now assuming that this can be done will there be issues when a user of the library includes the header files (ie. will they have to define 'DLL_CONFIG')?
Nothing. Leave it as #define MY_API and all instances of MY_API will simply vanish. You can add new build configurations, such as Debug - DLL and Release - DLL that mimic the others except they #define DLL_CONFIG. To clone a configuration, get to the configuration manager (like the drop down of the Debug/Release list box), then under 'Active solution configuration' select new. You can now name it "Debug - DLL" and set Copy Settings to Debug and now that's left to do is define DLL_CONFIG. To do this, go to project properties->configuration properties->C/C++->Preprocessor, and type DLL_CONFIG in there. You will also see that's where things like NDEBUG and WIN32 are defined. Like haffax said, use project specific names. I would recommend something like: #ifdef THEPROJECT_USE_DLL #ifdef THEPROJECT_BUILDING_PROJECT #define THEPROJECT_API __declspec(dllexport) #else #define THEPROJECT_API __declspec(dllimport) #endif #else #define THEPROJECT_API #endif Now users of your DLL just #define THEPROJECT_USE_DLL if they are using the DLL version, just like your "- DLL" configurations have.
1,090,075
1,090,344
How do you farm out variables to persistent data?
Basically, I want to have my program retrieve various variables from the hard drive disk for use in the program. I guess, before asking for details, I should verify that is even possible. Is it? If it is, what is the best way? I've seen the use of .ini files, but I don't know how to retrieve data specifically from .ini files. Is it the same as a text file that you have messed with to make sure variables will always be on x line? For instance: ifstream variables("variables.ini"); //some code later //assume line 'x' holds a variable if(variables.good()) { variables.get(x); } //or whatever =/ I'm kind of at a loss for what to do here. Edit: my language of choice is C++.
The first questions you need to address are the who and the why. Your options on the how will follow from those. So who (or what) will be accessing the data? If it is just the program itself then you can store the data however you want - binary file, xml, database, ini file, whatever. However if the data needs to be easily accessible to the user so they can change it prior to a run then a text file like an ini, which can be easily edited, makes sense. In order to edit the data stored in other formats you may have to write an entirely separate program just to manipulate the stored parameters. Maybe that makes sense in your situation or maybe not but it will be more work. If you choose to go the ini route then you are on the right track. They are just text files. A common format is to have sections (usually in brackets), and then key/value pairs within the sections. Usually comment lines start with semicolon, a nice touch for the users who may want to flip back and forth between settings. So something like this: [System] datapath = /home/me/data [Application] start_count = 12 ; start_count = 20 //this is a comment You don't have to worry about specific lines for your data. You just read through the file line by line. Empty or comment lines get tossed. You take note of what section you are in and you process the key/value pairs. There are many ways to store the parsed file in your program. A simple one may be to concatenate the section name and key into a key for a map. The value (of the key/value pair) would be the data for the map. So "Systemdatapath" could be one map key and its value would be "/home/me/data". When your program needs to use the values it just looks it up by key. That's the basics. Ultimately you will want to embellish it. For instance, methods to retrieve values by type. E.g. getString(), getInteger(), getFloat(), etc.
1,090,261
1,090,295
Get the graphics card model?
I was wondering how I can get the graphics card model/brand from code particularly from DirectX 9.0c (from within C++ code).
At runtime, you can query the device model and vendor: In OpenGL, use the command glGetString(GL_VENDOR) or GL_RENDERER or GL_VERSION to get the information you're after. In DirectX 9, it appears the info is in the Microsoft config system, and is queried from the device database. It's section 3 of this document, which also has example code: http://msdn.microsoft.com/en-us/library/bb204848(VS.85).aspx Using the same system you can get such information as the amount of ram the video card has, the driver number, etc.
1,090,406
1,130,846
Parameters to watch while running an application on linux?
I am running an application overnight on my Linux xscale device. I am looking for things,which would increase with the increase in the amount of time of running. One thing,is the memory. If you observe the memory on the xscale systems,the free memory would start decreasing,but you will see an increase in the cached memory. What are the other parameters which we can observe ,e.g. can we observe the amount of stack or heap usage?
If the application is developed by you, i would recommend the following heap profiler to use for getting more deeper details. http://code.google.com/p/google-perftools/wiki/GooglePerformanceTools
1,090,428
1,090,537
How to output array of doubles to hard drive?
I would like to know how to output an array of doubles to the hard drive. edit: for further clarification. I would like to output it to a file on the hard drive (I/O functions). Preferably in a file format that can be quickly translated back into an array of doubles in another program. It would also be nice if it was stored in a standard 4 byte configuration so that i can look at it through a hex viewer and see the actual values.
Hey... so you want to do it in a single write/read, well its not too hard, the following code should work fine, maybe need some extra error checking but the trial case was successful: #include <string> #include <fstream> #include <iostream> bool saveArray( const double* pdata, size_t length, const std::string& file_path ) { std::ofstream os(file_path.c_str(), std::ios::binary | std::ios::out); if ( !os.is_open() ) return false; os.write(reinterpret_cast<const char*>(pdata), std::streamsize(length*sizeof(double))); os.close(); return true; } bool loadArray( double* pdata, size_t length, const std::string& file_path) { std::ifstream is(file_path.c_str(), std::ios::binary | std::ios::in); if ( !is.is_open() ) return false; is.read(reinterpret_cast<char*>(pdata), std::streamsize(length*sizeof(double))); is.close(); return true; } int main() { double* pDbl = new double[1000]; int i; for (i=0 ; i<1000 ; i++) pDbl[i] = double(rand()); saveArray(pDbl,1000,"test.txt"); double* pDblFromFile = new double[1000]; loadArray(pDblFromFile, 1000, "test.txt"); for (i=0 ; i<1000 ; i++) { if ( pDbl[i] != pDblFromFile[i] ) { std::cout << "error, loaded data not the same!\n"; break; } } if ( i==1000 ) std::cout << "success!\n"; delete [] pDbl; delete [] pDblFromFile; return 0; } Just make sure you allocate appropriate buffers! But thats a whole nother topic.
1,090,484
1,090,595
is this possible in C++?
to create an instance of another class from a class even if the class I want to have an instance of is declared next of the class I am creating an instance from. Just like in C# and Java. Thank you
Sure. You just need a forward declaration. Something like this works just fine: #include <iostream> class B; class A { public: void hello( B &b ); void meow(); }; class B { public: void hello( A &a ); void woof(); }; void A::hello( B &b ) { b.woof(); } void A::meow() { std::cout << "Meow!" << std::endl; } void B::hello( A &a ) { a.meow(); } void B::woof() { std::cout << "Woof!" << std::endl; } int main() { A a; B b; a.hello( b ); b.hello( a ); return 0; } The key here is that you can only use pointers or references to a class until it has been fully defined. So in the example I gave, the hello() method in A can be declared to take a reference to B, even though we haven't defined B at the point. After the definition of B, however, the definition of the method A::hello() is free to use B as it pleases.
1,090,755
1,090,914
Using v-table thunks to chain procedure calls
I was reading some articles on net regarding Vtable thunks and I read somewhere that thunks can be used to hook /chain procedures calls. Is it achievable? Does anyone know how that works , also I am not able to find good resource explaining thunks. Any suggestions for that?
Implementing a raw thunk in the style of v-table thunks is a last resort. Whatever you need to accomplish can most likely be achieved with a wrapper function, and it will be much less painful. In general, a thunk does the following: Fix up the input parameters (e.g., convert to a different format) Call the real implementation Clean up step 1 / fix the output parameters To see an example of how it works, let's turn to our good friend Raymond Chen and his discussion of adjuster thunks: http://blogs.msdn.com/oldnewthing/archive/2004/02/06/68695.aspx The thunk he used was as follows: [thunk]:CSample::QueryInterface`adjustor{4}': sub DWORD PTR [esp+4], 4 ; this -= sizeof(lpVtbl) jmp CSample::QueryInterface As he describes, you have a class that implements the same methods through multiple interfaces, so it has multiple v-tables. (If you don't know COM, all you need to know is that it works with v-tables directly, so a pointer to a specific interface must contain function pointers to all the methods of that interface in order.) If you implement two interfaces with different methods in a particular slot, you need multiple v-tables. But, you only write the overlapping methods once, so that method needs to be able to work with both "this" pointers. To do that, the compiler generates a method that does the fixup necessary and calls the original implementation. So, this thunk does the following steps: Fix up the input parameters, namely the hidden "this" pointer, in the first line. Call the real implementation in the second line. Cleanup: none required (see below) This is where the jmp instruction comes in. Normally, if you were to call the function using call, it would return to you, and you'd have to ret back to your caller. Since there is no cleanup to do, the compiler does an optimization where it moves execution straight to the real implementation and let's the real implementation's return statement return to your caller. This is only an optimization, not a fundamental part of thunking. For example, 16/32-bit thunks will convert the input / output parameters between 16 and 32 bits as necessary, so it can't skip the cleanup step; it has to call, not jmp. The moral of the story is: if you need to do something, such as the jmp optimization, that you can't write directly in C++ or your other high level language of choice, go ahead and write an assembly language thunk. Otherwise, just write a wrapper and be done with it. Honestly, it sounds like you're asking for the performance optimization, and most of the time (1) the compiler is better at optimizing than we think and (2) it's not going to give you as big of an improvement as you think.
1,090,782
1,090,794
Different address with map indexes vs content of map index
In the code below, why it is that when I take the address of a map index (which contains a list) and I take the address of the list itself, they both have different values. See the code below for clarification. #include <iostream> #include <list> #include <map> using namespace std; int main() { list<char> listA; //list of chars map<int,list<char> > mapper; //int to char map mapper[1] = listA; cout << &(mapper[1]) << endl; cout << &listA << endl; }
You get different addresses because you create a copy of the original list and assing it to the map structure. Consider using pointers (map< int, list<char>* >).
1,090,819
1,090,850
Template class inside class template in c++
noob here still experimenting with templates. Trying to write a message processing class template template <typename T> class MessageProcessor { //constructor, destructor defined //Code using t_ and other functions foo( void ) { //More code in a perfectly fine method } private: T *t_ }; All defined in a header file. I've built and tested my class and all is well. Now, I'm trying to do this: template <typename T> class MessageProcesor { //Same stuff as before foo(void) { //Same code as before in foo, but one new line: t_->getMessageSender<MessageType>(); } private: T *t_; }; However, this line gives me an error of bad expression-type before '>' token. I've added the necessary header files to define what a MessageType is. I've used this function many time before, just not in this context. I suspect that the compiler doesn't like the fact that the template function is fully defined (specialized?) within an undefined class template (unspecialized?). I'm not fully grokking what makes a template 'specialized'. Most explanations center on the concepts of 'full' or 'partial', but not what makes it specialized in the first place. Apologies if you'd like to see more code. I have no internet access at work and that's where I'm doing this, so I have to put everything into my mental 'scratchpad' and bring it home.
Your member function 'foo' needs a return type and you need to use the keyword 'template' when you use member templates in dependent expressions (expressions whose meanings rely directly or indirectly on a generic template parameter) t_->template getMessageSender<MessageType>(); // ok t_->getMessageSender<MessageType>(); // not ok Perhaps this example will help you appreciate when a member template needs to be prefixed by the 'template' keyword [Note: in the interest of symmetry you may always use the 'template' prefix on member templates, but it is optional when used on a non-dependent expression. struct MyType { template<class T> void foo() { } }; template<class U> struct S { template<class T> void bar() { MyType mt; // non-dependent on any template parameter mt.template foo<int>(); // ok mt.foo<int>(); // also ok // 't' is dependent on template parameter T T t; t.template foo<int>(); // ok t.foo<int>(); // not ok S<T> st; // 'st' is dependent on template parameter T st.template foo<int>(); // ok st.foo<int>(); // not ok S<MyType> s; // non-dependent on any template parameter s.bar<int>(); // ok s.template bar<int>(); // also ok } }; Hope that helps.
1,090,884
1,091,183
Get the size of jpeg from memory (converted using GDI++)
This is my first post here. I have a problem. I need to take a sceenshot of the desktop, convert it to jpeg, store it in a buffer and then manipulate it and send it over the internet. I have written the code for doing this with GetDC....and GDI+ for converting the HBITMAP to jpeg. The problem I am having now is that I don't know the size of the jpeg that has been saved into the IStream. Here is part of the code that transforms the bitmap referenced by the HBITMAP hBackBitmap into jpeg and save it into pStream. I need to know how many bytes have been written into pStream and how I can use pStream (get a PVOID handle): Gdiplus::Bitmap bitmap(hBackBitmap, NULL);///loading the HBITMAP CLSID clsid; GetEncoderClsid(L"image/jpeg", &clsid); HGLOBAL hGlobal = GlobalAlloc(GMEM_FIXED, nBlockSize) ;//allocating memory, the size of the current bitmap size. i'm over allocating but i don't think there is any way to get the exact ammount I need to allocate, is there? if(!hGlobal) return; IStream* pStream = NULL ; if(CreateStreamOnHGlobal(hGlobal, TRUE, &pStream) != S_OK ) return; bitmap.Save(pStream, &clsid); What I need is: 1. Find out the size of jpeg, how many bytes have been written in the stream 2. How to use the stream. Can I get a PVOID for the data in stream for example? Thank you.
According to the CreateStreamOnHGlobal documentation, your use of it is incorrent. Quote: The current contents of the memory block are undisturbed by the creation of the new stream object. Thus, you can use this function to open an existing stream in memory. The initial size of the stream is the size of the memory handle returned by the GlobalSize function. Therefore, you should replace nBlockSize with 0 to allocate an zero-sized buffer. As the memory buffer must be moveable, you'll also need to replace GMEM_FIXED with GMEM_MOVEABLE: HGLOBAL gGlobal = GlobalAlloc(GMEM_MOVEABLE, 0); After saving to the stream, the resulting size will be available as size_t size = GlobalSize(hGlobal); To access the JPEG encoded data, you'll need to use GlobalLock to get a pointer to the actual location in memory. Note that Global and Local functions are marked as deprecated and should not be used anymore, but I don't know a better IStream implementation for your needs without crawling the MSDN documentation. Perhaps somebody else can help here!?
1,090,901
1,090,916
c++ array value matching variable
I would like to see if a value equals any of the values in an array. like this Beginning of function(here I give Val differnt values with for loops...) for (i=0;i<array_size;i++) if (Val==array[i]) do something else do something else if non of the above values matched val... If none of the Arrayvalues matches my val I would like to do something else, but only once... And if it matches then I would like to go back to the beginning of the function that will give me a different value to val... Where should I put in this code Thx, for a great forum /Buxley
Use a flag to indicate whether the condition was satisfied at least once: bool hasMatch = false; for (i=0;i< array_size;i++) { if (Val==array[i]) { // do something hasMatch = true; } } if( !hasMatch ) { // do whatever else } This will invoke the "do something" for every matching element. If you want to invoke it for the first matching element only use break; after "do something".
1,090,917
1,091,037
Does anyone know a good/easy/free/open 3d modeling program?
Does anyone know of an easy 3D modeling application like sketchup but is opensource? I don't have time for learning blender ( guess I never will ): and I'm a fan of having multiple small tools do their part of the job ( first cut the plank using the saw the nail it using the hammer :) ). Edit: I also might need to do some modifications to the application, for an example I want to be able to preview my GLSL shaders directly at the model. I want also be able to cut the model in half ( or as many cuts as I want to ) and have it saved in my own fileformet. I does almost only know C++, done some hacking in other langs to. Ask me if I'm unclear with my askings :) Edit2: I'm not a GUI tool programmer and have never done anything like a 3D editor, the most tools I've mada have been consolebased. Does anyone know a good startingpoint for a 3Dtool? ( like nehe.gamedev.net but for 3d tools instead of 3d games )
Blender is the only decent one I know, why not taking a look in Youtube/Vimeo on some tutorials? There are plenty and it's quite fast to scrap with Video tutorials.
1,090,956
1,090,982
What is CString::StringTraits? What is it for? There seems to be no documentation
Using Visual Studio 2005 As per the title; MSDN and google can't tell me, I'm hoping it'll let me know if the contained string contains Unicode characters or not - but that's a different problem!
I used traits for custom defined comparison function.eg Currently default comparison implementation of two CStrings is case insensitive. If you want to do case sensitive comparison between two strings then you can define that behavior in traits. I am not sure if there are any other use cases.
1,091,336
1,091,356
Date manipulation in C++
I am sure that this kind of questions must have been asked before, but failed to find anything by searching this site. My apologies in advance if I missed any similar questions. Is there anything in C++ that just does date manipulation at all? I am aware of SYSTEMTIME structure (it is the structure returned when you do GetSystemTime I think) but it does not seem to contain any manipulation functions. For example, I am looking at something which can do "give me the day of the second Tuesday in July 2010". Also, fitting a time not sourced from the system clock into a SYSTEMTIME structure just seems, well, wrong. Is there any library routine to validate a date at all? I am not thinking about the basic "check day is between 1 and 28". The routine must be able to say that 29-02-2009 does not exist, for example. Thank you.
You should check out Boost::DateTime. But to answer your question there is no date time 'handling' as such in C++
1,091,557
1,099,581
WndProc hook does not receive WM_COMMAND from menus
For tracking user activity, I am using a Windows Hook for the main application thread, and monitor (among others) WM_COMMAND messages. I receive them as expected from dialog buttons, toolbar buttons, accelerators and popup menus, but I do NOT receive them from the main menu. Strangely enough, Spy++ does show the main window receiving them. What could be wrong? Installing the hook: currentHook = SetWindowsHookEx(WH_CALLWNDPROC, HookProc, 0, GetCurrentThreadId()); HookProc, minimalistic: LRESULT CALLBACK HookProc(int nCode, WPARAM wp, LPARAM lp) { CWPSTRUCT cwp = *(CWPSTRUCT *)lp; if (cwp.message == WM_COMMAND) { ATLTRACE("[hook!] WM_COMMAND id=%d\n", LOWORD(cwp.wParam)); } return CallNextHookEx(currentHook, nCode, wp, lp); } (The actual code is more complex, and needs to check for reentrancy etc., but I've remvoed it for this test) Any ideas? [Edit] the main window I test is an MFC application, but the instrumentation code does not use any MFC.
Menu commands are posted, not sent (yes, the documentation is rather unclear on this - but Spy++ tells the truth). And WH_CALLWNDPROC hooks only catch sent messages. You should be able to use a WH_GETMESSAGE hook to intercept posted messages. You'll need both if you want to handle both forms of WM_COMMAND.
1,091,602
1,091,647
C++ Changing a class in a dll where a pointer to that class is returned to other dlls
Horrible title I know, horrible question too. I'm working with a bit of software where a dll returns a ptr to an internal class. Other dlls (calling dlls) then use this pointer to call methods of that class directly: //dll 1 internalclass m_class; internalclass* getInternalObject() { return &m_class; } //dll 2 internalclass* classptr = getInternalObject(); classptr->method(); This smells pretty bad to me but it's what I've got... I want to add a new method to internalclass as one of the calling dlls needs additional functionality. I'm certain that all dlls that access this class will need to be rebuilt after the new method is included but I can't work out the logic of why. My thinking is it's something to do with the already compiled calling dll having the physical address of each function within internalclass in the other dll but I don't really understand it; is anyone here able to provide a concise explanation of how the dlls (new internal class dll, rebuilt calling dll and calling dll built with previous version of the internal class dll) would fit together? Thanks, Patrick
The client dll's 'learn' the actual address of the class' functions at load-time by looking at the export table of the serving dll. So as long as the export table stays compatible, no harm is done. Compatibility will be broken when your class has a virtual function table, and the functions in it change order. It will also break when linking by ordinal instead of by symbol.
1,091,643
1,091,672
C++ operators and arguments
Let's say I have a class Point: class Point { int x, y; public: Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; } }; Why can I not call this as such: Point p1; p1 += Point(10,10); And is there any way to do this, while still having a reference as the argument?
Here's the code you need: class Point { int x,y; public: Point(int x=0,int y=0) : x(x), y(y) {} Point& operator+=(const Point&p) {x+=p.x;y+=p.y;return *this;} }; As Konrad pointed out, you need a constructor. Also you need to explicitly perform the additions inside your operator overload.
1,091,927
1,091,941
When does the space occupied by a variable get deallocated in c++?
Doesn't the space occupied by a variable get deallocated as soon as the control is returned from the function?? I thought it got deallocated. Here I have written a function which is working fine even after returning a local reference of an array from function CoinDenom,Using it to print the result of minimum number of coins required to denominate a sum. How is it able to print the right answer if the space got deallocated?? int* CoinDenom(int CoinVal[],int NumCoins,int Sum) { int min[Sum+1]; int i,j; min[0]=0; for(i=1;i<=Sum;i++) { min[i]=INT_MAX; } for(i=1;i<=Sum;i++) { for(j=0;j< NumCoins;j++) { if(CoinVal[j]<=i && min[i-CoinVal[j]]+1<min[i]) { min[i]=min[i-CoinVal[j]]+1; } } } return min; //returning address of a local array } int main() { int Coins[50],Num,Sum,*min; cout<<"Enter Sum:"; cin>>Sum; cout<<"Enter Number of coins :"; cin>>Num; cout<<"Enter Values"; for(int i=0;i<Num;i++) { cin>>Coins[i]; } min=CoinDenom(Coins,Num,Sum); cout<<"Min Coins required are:"<< min[Sum]; return 0; }
The contents of the memory taken by local variables is undefined after the function returns, but in practice it'll stay unchanged until something actively changes it. If you change your code to do some significant work between populating that memory and then using it, you'll see it fail.
1,092,045
1,092,069
WriteConsole() weird characters?
I use this snippet to create a console from inside a dll. That dll gets loaded in a game. CODE SNIPPET The console window creates fine. But when i write stuff to it, i just get stuff like "???D??". I know i have to use the printf() syntax. So i use wprintf("%s", "test"); Any pointers?
Try using: wprintf(L"%s", "test"); as wprintf takes an wide character string as input Edit: Based on the fact that the behaviour of %s and %S changes when used in wprintf what about: wprintf("%s", L"test"); The %s in wprintf expects a wide character string this L"test" is. I removed the "L" on the format parameter since wprintf is defined as: int wprintf(char *fmt, ...)
1,092,331
1,092,384
Overloading += in c++
If I've overloaded operator+ and operator= do I still need to overload operator+= for something like this to work: MyClass mc1, mc2; mc1 += mc2;
operator+= is not a composite of + and =, therefore you do need to overload it explicitly, since compiler do not know to build puzzles for you. but still you do able to benefit from already defined/overloaded operators, by using them inside operator+=.
1,092,561
1,092,572
Is returning a std::list costly?
I was wondering if returning a list, instead of returning a pointer to one, was costly in term of performance because if I recall, a list doesn't have a lot of attributes (isn't it something like 3 pointers? One for the current position, one for the beginning and one for the end?).
If you return a std::list by value it won't just copy the list head, it will copy one list node per item in the list. So yes, for a large list it is costly. If the list is built in the function which is returning it, then you might be able to benefit from the named return value optimisation, to avoid an unnecessary copy. That's specific to your compiler, though. It never applies if for example the list already existed before the function was called (for example if it's a member variable of an object). A common idiom in C++, to avoid returning containers by value, is to take an output iterator as a parameter. So instead of: std::list<int> getListOfInts() { std::list<int> l; for (int i = 0; i < 10; ++i) { l.push_back(i); } return l; } You do: template<typename OutputIterator> void getInts(OutputIterator out) { for (int i = 0; i < 10; ++i) { *(out++) = i; } } Then the caller does: std::list<int> l; getInts(std::back_inserter(l)); Often once the compiler has finished inlining and optimising, the code is more or less identical. The advantage of this is that the caller isn't tied to a particular collection - for instance he can have the items added to a vector instead of a list if that is more useful for the particular circumstances. If he only needs to see each item once, instead of all of them together, then he can save memory by processing them in streaming mode using an output iterator of his own devising. The disadvantages are the same as with any template code: the implementation must be available to the caller at compile time, and you can end up with a lot of "duplicate" object code for multiple instantiations of the template. Of course you can use the same pattern without using templates, by taking a function pointer (plus a user data pointer if desired) as a parameter and calling it once with each item, or by defining an IntVisitor abstract class, with a pure virtual member function, and having the caller provide an instance of it. [Edit: T.E.D points out in a comment that another way to avoid the copy without using templates is for the caller to pass in a list by reference. This certainly works, it just gives the caller less flexibility than the template, and hence is not the idiom used by the STL. It's a good option if you don't want the "advantage of this" that I describe above. One of the original intentions behind the STL, though, is to separate "algorithms" (in this case whatever determines the values) from "containers" (in this case, the fact that the values happen to be stored in a list, as opposed to a vector or an array or a self-sorting set, or just printed out without storing them at all).]
1,092,714
1,092,724
conversion precedence in c++
I have the following code: Some functions: A::A(int i_a) {cout<<"int Ctor\n";} //conversion constructor void h(double d) {cout<<"double param\n";} //f1 void h(A a) {cout<<"A param\n";} //f2 In the main function: h(1); The function that h(1) calls is f1. My question is why does it choose to call that. 1 is an int and therefore requires implicit conversion to double. It could just as easily convert the int into an A using the conversion constructor defined above. Why don't I get an error? What are the precedence rules with casting? N.b. I've posted above the code that I think will be necessary to answer the question, but below I'm posting the entire code: #include <iostream> using namespace std; class B; class A { public: explicit A(const B&) {cout<<"Ctor through B\n";} A() {cout<<"Default Ctor\n";} A(int i_a) {cout<<"int Ctor\n";} operator int() {cout<<"A => int\n"; return 2;} }; class B { public: operator A() const {cout<<"B => A\n"; A a; return a;} }; void h(double d) {cout<<"double param\n";} void h(A a) {cout<<"A param\n";} void f(const A& a) { cout<<"f function\n"; //Without the const it will never try to convert } void main() { B b; cout <<"-----------------\n"; f(b); cout <<"-----------------\n"; h(1); }
When overload resolution is performed to select the best candidate out of all viable overloads - the compiler ranks all the conversion sequences for each argument for each candidate. For a function to win (be selected as the best candidate), its conversion ranks for each argument have to be better than or equal to every other function's conversion ranks for that argument AND at least one conversion rank has to be better than all the other function's conversion ranks for a certain argument. The user defined conversion (which uses either a constructor or a cast operator) has one of the worst possible ranks (only the ellipsis has a worse rank). The integral-floating conversion has a better rank (see below for a list of the rankings). Thus, the compiler prefers converting an int -> double (using a standard conversion) than converting an int -> A (using a user defined conversion), and therefore it selects f1. Edit: Although "Overload resolution" works in the background and most of the time does exactly what you would expect (i.e. most programmers won't need to delve into the technicalities) - if you do want to go deeper (but be warned that some of the darker corners of overload resolution are considered to be one of the trickiest aspects for compiler writers to get exactly right in a C++ compiler) refer to the excellent C++ Templates: The Complete Guide by David Vandevoorde and Nicolai M. Josuttis which provides, in appendix B, one of the best introductions to the machinery behind overload resolution that I have read. Here is an excerpt from B.2: Overload resolution ranks the viable candidate functions by comparing how each argument of the call matches the corresponding parameter of the candidates. For one candidate to be considered better than another, the better candidate cannot have any of its parameters be a worse match than the corresponding parameter in the other candidate. ... Given this first principle, we are left with specifying how well a given argument matches the corresponding parameter of a viable candidate. As a first approximation we can rank the possible matches as follows (from best to worst): Perfect match. The parameter has the type of the expression, or it has a type that is a reference to the type of the expression (possibly with added const and/or volatile qualifiers). Match with minor adjustments. This includes, for example, the decay of an array variable to a pointer to its first element, or the addition of const to match an argument of type int** to a parameter of type int const* const*. Match with promotion. Promotion is a kind of implicit conversion that includes the conversion of small integral types (such as bool, char, short, and sometimes enumerations) to int, unsigned int, long or unsigned long, and the conversion of float to double. Match with standard conversions only. This includes any sort of standard conversion (such as int to float) but excludes the implicit call to a conversion operator or a converting constructor. Match with user-defined conversions. This allows any kind of implicit conversion. Match with ellipsis. An ellipsis parameter can match almost any type (but non-POD class types result in undefined behavior). But that's just the beginning - if you are intrigued - I urge you to read the book and then the relevant portions of the standard :)
1,092,777
1,093,004
How do I read the windows registry (Default) value using QSettings?
I want to read the registry to find the current PowerPoint version. However this just returns Zero: QSettings settings("HKEY_CLASSES_ROOT\\PowerPoint.Application\\CurrVer", QSettings::NativeFormat); QString sReturnedValue = settings.value("(Default)", "0").toString(); Any suggestions as to how I get the value from a (default) key?
Ok, just figured it out. Whilst regedit shows it as (Default) you just read it as Default. QString sReturnedValue = settings.value( "Default", "0" ).toString();
1,092,972
1,092,982
casting producing const objects in c++
Would it be correct to say that whenever casting is used, the resulting object is a const object? ...And therefore can only be used as an argument to a function if that function accepts it as a const object? e.g. class C1 { public: C1(int i=7, double d = 2.5){}; }; void f(C1& c) {}; int main(){ f(8); return 1; } //won't compile (Of course if f(....) receives the argument by value then it gets a non-const version which it can work with)
Usually when an object of a certain type is converted to an object of another type (a non-reference type), a temporary object is created (not a const object). A temporary object (invisible, nameless, rvalue) can only bind (in C++98/03) to references that are const (except for the temporary known as the 'exception object'). Therefore, the result of a conversion that creates a temporary can only be used as an argument to a function that either accepts it as a const reference, or as a type that it can be copied/converted into. So for e.g. void f(double); // 1 void f(const int&); // 2 void f(int&); // 3 struct B { B(int) { } }; struct C { C(int) { } }; void f(B b); // 4 void f(B& b); // 5 void f(const C& c); //6 void f(C& c); // 7 // D inherits from B struct D : B { D(int) : B(0) { } }; void f(D& d); // 8 int main() { f( (int) 3.0 ); // calls 2, NOT 3 f( (float) 3 ); // calls 1 - const reference requires the same type f( 1 ); // calls 2, NOT 3 f( (B) 1 ); // calls 4, not 5 - can accept it by non-const value f( (C) 1 ); // calls 6, not 7 - can accept it by const-reference f( (D) 1 ); // calls 4, not 8 - since a 'D' temporary object can be converted to a 'B' object - but will not bind to a non-const reference } Hope that helps.
1,093,813
1,093,837
What is the most dangerous feature of C++?
I've heard lots of times that phrase of Bjarne Stroustrup "C++ makes it harder to shoot yourself in the foot; but when you do, it takes off the whole leg" and I don't really know if it is as terrible as it sounds. What's the worst thing that has ever happened to you (or more properly, to your software) while programming in C++? In which ways can it be more dangerous than say plain C, for example?
delete [] array; can sometimes become delete array; in the hands of someone who doesn't know. Tracking that bug down can suck horribly, and doesn't happen when you're doing malloc and free.
1,093,857
1,093,945
AccessViolationException when string is too long (C++)
I asked a similar question a couple of days ago, but I'm looking for more insight. I'm getting an AccessViolationException when I add a string to my program: Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at _cexit() at <CrtImplementationDetails>.LanguageSupport._UninitializeDefaultDomain(Void * cookie) at <CrtImplementationDetails>.LanguageSupport.UninitializeDefaultDomain() at <CrtImplementationDetails>.LanguageSupport.DomainUnload(Object source, EventArgs arguments) at <CrtImplementationDetails>.ModuleUninitializer.SingletonDomainUnload(Object source, EventArgs arguments) The program has a bunch of const std::string's at the top level: const std::string caseDelimitedOption = "CaseDelimited"; const std::string endOfLineOption = "EndOfLine"; const std::string functionNameDelimitWordsOption = "FunctionNameDelimitWords"; const std::string functionNameStartCaseOption = "FunctionNameStartCase"; const std::string indentStringOption = "IndentString"; const std::string lowerCaseOption = "LowerCase"; const std::string newLineBetweenDoAndWhileOption = "NewLineBetweenDoAndWhile"; const std::string nextLineOption = "NextLine"; const std::string nextLineAsWellAsCloseParenOption = "NextLineAsWellAsCloseParen"; const std::string noBracesAroundSingleStatementBlockOption = "NoBracesAroundSingleStatementBlock"; const std::string openBraceLocationOption = "OpenBraceLocation"; const std::string underscoreDelimitedOption = "UnderscoreDelimited"; const std::string upperCaseOption = "UpperCase"; const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment"; If I replace last string with: const std::string whiteSpaceBeforeLeadingCmntOption = ""; //"WhiteSpaceBeforeLeadingComment"; then the exception goes away. Is this just extra memory (from the string) hitting some bad memory that was caused elsewhere in my program? Or is the exception related to the string? Thanks for any help, Joe
I assume these strings are global variables. Are you trying to access these strings from the constructor of another global variable (or from some method that is called before main is entered)? If this is the case you are suffering from the probelem that global variable initialization order is undefined across multiple compilation units. There are a few solutions but more information about your application would probably be useful. First test to see if main is even entered. I would think that it working with the empty string is the result of some compiler optimization trick.
1,093,883
1,099,673
Google Performance Tools (profiler) tutorial
I just downloaded and built the libraries/executables of Google Performance Tools. Before I run the CPU profiler on the application that I want to investigate, I want to learn how to use the tools properly perhaps on a sample application. What would be a good example to run the Google CPU profiler on? Thanks in advance.
The following paragraph appears in the README.windows file distributed with perftools 1.3: The heap-profiler has had a preliminary port to Windows. It has not been well tested, and probably does not work at all when Frame Pointer Optimization (FPO) is enabled -- that is, in release mode. The other features of perftools, such as the cpu-profiler and leak-checker, have not yet been ported to Windows at all.
1,093,903
1,094,906
What is the destruction order of the View/Doc/Frame in a CMultiDocTemplate?
I'm working in an MDI application that has a pointer to a document's frame object. Other threads are calling PostMessage using the pointer. During shutdown, the threads continue trying to post messages to the frame while the frame is being destructed. Does anyone know the destruction order of the multiple documents in MFC's MDI implementation? Is there a message that I should be handling that would make this easier (Maybe the Frame's ON_WM_CLOSE)?
If your threads are posting messages only to frame object you could notify these threads about frame's destruction by using CEvent in frame's WM_CLOSE handler. In that case I don't see why do you need to know destruction order?
1,094,039
1,094,081
When might multiple inheritance be the only reasonable solution?
To be clear, I'm not asking if/why multiple inheritance is good or bad. I've heard a lot of arguments from both sides of that debate. I'm wondering if there is any kind of design problem or scenario in C++ in which multiple inheritance is either the only way to accomplish something, or at least is the most optimal way over all other alternatives to the point that it wouldn't make sense to consider anything else. Obviously, this question doesn't apply to languages that don't support multiple inheritance.
You can't do policy-based design without multiple inheritance. So if policy-based design is the most elegant way to solve your problem, than that means you need multiple inheritance to solve your problem, over all other options. Multiple-inheritance can be very useful if it's not misused (like everything, in any language).
1,094,046
1,094,078
Using auto and decltype in C++11
I'm trying to learn the currently accepted features of c++11 and I'm having trouble with auto and decltype. As a learning exercise I'm extending the std class list with some generic functions. template<class _Ty, class _Ax = allocator<_Ty>> class FList : public std::list<_Ty, _Ax> { public: void iter(const function<void (_Ty)>& f) { for_each(begin(), end(), f); } auto map(const function<float (_Ty)>& f) -> FList<float>* { auto temp = new FList<float>(); for (auto i = begin(); i != end(); i++) temp->push_back(f(*i)); return temp; } }; auto *ints = new FList<int>(); ints->push_back(2); ints->iter([](int i) { cout << i; }); auto *floats = ints->map([](int i) { return (float)i; }); floats->iter([](float i) { cout << i; }); For the member map I want the return type to be generic depending on what the passed function returns. So for the return type I could do something like this. auto map(const function<float (_Ty)>& f) -> FList<decltype(f(_Ty))>* This would also need to remove the float type in the function template. auto map(const function<auto (_Ty)>& f) -> FList<decltype(f(_Ty))>* I could use a template class but that makes the use of instances more verbose since i have to specify the return type. template<class T> FList<T>* map(const function<T (_Ty)>& f) To sum of my question i'm trying to figure out how to define map without using a template class and still have it generic in the type it returns.
Deriving from std::list or other std:: containers is discouraged. Write your operations as free functions so they can work on any standard container via iterators. Do you mean "define map without using a template function"? You should be able to use the result_type member type of std::function to get the type it returns. Also it's not necessary for you to specify that the function is passed as a std::function. You could leave it open as any type, and let the compiler join everything up. You only need std::function for runtime polymorphism. And using new to create raw heap-allocation objects and returning them by pointer is soooo 1992! :) Your iter function is essentially the same thing as the range-based for loop. But all that aside... do you mean something like this? template <class TFunc> auto map(const TFunc &f) -> FList<decltype(f(_Ty()))>* { auto temp = new FList<decltype(f(_Ty()))>(); for (auto i = begin(); i != end(); i++) temp->push_back(f(*i)); return temp; } This will match anything callable, and will figure out the return type of the function by using decltype. Note that it requires _Ty to be default constructable. You can get around that by manufacturing an instance: template <class T> T make_instance(); No implementation is required because no code is generated that calls it, so the linker has nothing to complain about (thanks to dribeas for pointing this out!) So the code now becomes: FList<decltype(f(make_instance<_Ty>()))>* Or, literally, a list of whatever the type would be you'd get from calling the function f with a reference to an instance of _Ty. And as a free bonus for accepting, look up rvalue references - these will mean that you can write: std::list<C> make_list_somehow() { std::list<C> result; // blah... return result; } And then call it like this: std::list<C> l(make_list_somehow()); Because std::list will have a "move constructor" (like a copy constructor but chosen when the argument is a temporary, like here), it can steal the contents of the return value, i.e. do the same as an optimal swap. So there's no copying of the whole list. (This is why C++0x will make naively-written existing code run faster - many popular but ugly performance tricks will become obsolete). And you can get the same kind of thing for free for ANY existing class of your own, without having to write a correct move constructor, by using unique_ptr. std::unique_ptr<MyThing> myThing(make_my_thing_somehow());
1,094,066
1,094,071
Static declarations are not considered for a function call if the function is not qualified
"painting/qpathclipper.cpp", line 1643.30: 1540-0274 (S) The name lookup for "fuzzyCompare" did not find a declaration. "painting/qpathclipper.cpp", line 1643.30: 1540-1292 (I) Static declarations are not considered for a function call if the function is not qualified. I'm trying to compile Qt 4.5.0 on xlC 9.0.0.4a, and getting the above compiler message for the following code: static bool fuzzyCompare(qreal a, qreal b) { return qFuzzyCompare(a, b); } template <typename InputIterator> InputIterator qFuzzyFind(InputIterator first, InputIterator last, qreal val) { while (first != last && !fuzzyCompare(qreal(*first), qreal(val))) //line 1643 ++first; return first; }
The "static" keyword is in error here, fuzzyCompare should be declared just bool fuzzyCompare(qreal a, qreal b)
1,094,215
1,094,245
Faster to malloc multiple small times or few large times?
When using malloc to allocate memory, is it generally quicker to do multiple mallocs of smaller chunks of data or fewer mallocs of larger chunks of data? For example, say you are working with an image file that has black pixels and white pixels. You are iterating through the pixels and want to save the x and y position of each black pixel in a new structure that also has a pointer to the next and previous pixels x and y values. Would it be generally faster to iterate through the pixels allocating a new structure for each black pixel's x and y values with the pointers, or would it be faster to get a count of the number of black pixels by iterating through once, then allocating a large chunk of memory using a structure containing just the x and y values, but no pointers, then iterating through again, saving the x and y values into that array? I'm assuming certain platforms might be different than others as to which is faster, but what does everyone think would generally be faster?
It depends: Multiple small times means multiple times, which is slower There may be a special/fast implementation for small allocations. If I cared, I'd measure it! If I really cared a lot, and couldn't guess, then I might implement both, and measure at run-time on the target machine, and adapt accordingly. In general I'd assume that fewer is better: but there are size and run-time library implementations such that a (sufficiently) large allocation will be delegated to the (relatively slow) O/S. whereas a (sufficiently) small allocation will be served from a (relatively quick) already-allocated heap.
1,094,276
1,094,382
Strange memory problem of Loki::Singleton, Loki::SmartPtr, and std::vector
I had encountered a problem while using Loki::Singleton, Loki::SmartPtr, and std::vector under VC express 2008. Following is my source. #include <iostream> #include <vector> #include <loki/Singleton.h> #include <loki/SmartPtr.h> class Foo { public: std::vector<Loki::SmartPtr<Foo>> children ; void add() { Loki::SmartPtr<Foo> f = new Foo ; children.push_back(f) ; } Foo () { } ~Foo () { } } ; typedef Loki::SingletonHolder<Foo> SingletonFoo ; int main () { std::cout << "Start" << std::endl ; SingletonFoo::Instance().add() ; std::cout << "End" << std::endl ; } Compiling and linking has no problem, but after the program finished, an error pops: Windows has triggered a breakpoint in test.exe. This may be due to a corruption of the heap, which indicates a bug in test.exe or any of the DLLs it has loaded. This may also be due to the user pressing F12 while test.exe has focus. The output window may have more diagnostic information. It seems some memory are deleted twice, I am quite not sure. Is that a bug of VC or I miss used Loki? Thanks in advance.
As you're using VC, you should be able to run your code in debug mode, step by stp (F10,F11) to see where it breaks. Anyway, looking at the Loki singleton code, it seems that the error comes from the assert in SingletonHolder::DestroySingleton() : SingletonHolder<T, CreationPolicy, L, M, X>::DestroySingleton() 00837 { 00838 assert(!destroyed_); // there, but it's a wild guess 00839 CreationPolicy<T>::Destroy(pInstance_); 00840 pInstance_ = 0; 00841 destroyed_ = true; 00842 } That function seems to be called by the LifetimePolicy (here DefaultLifetime) as this code suggests : 00800 template 00801 < 00802 class T, 00803 template <class> class CreationPolicy, 00804 template <class> class LifetimePolicy, 00805 template <class, class> class ThreadingModel, 00806 class MutexPolicy 00807 > 00808 void SingletonHolder<T, CreationPolicy, 00809 LifetimePolicy, ThreadingModel, MutexPolicy>::MakeInstance() 00810 { 00811 typename ThreadingModel<SingletonHolder,MutexPolicy>::Lock guard; 00812 (void)guard; 00813 00814 if (!pInstance_) 00815 { 00816 if (destroyed_) 00817 { 00818 destroyed_ = false; 00819 LifetimePolicy<T>::OnDeadReference(); 00820 } 00821 pInstance_ = CreationPolicy<T>::Create(); 00822 LifetimePolicy<T>::ScheduleDestruction(pInstance_, // here 00823 &DestroySingleton); 00824 } 00825 } I'm not sure why it is called twice, but I guess the pointer to the singleton is first destroyed (the pointer, not the instance) on the SingletonHolder instance destruction and then the LifetimePolicy try to call it's DestroySingleton() function... But I might be wrong, you'll have to check that.
1,094,387
1,094,421
Why does removing const give me linker errors?
I have a global variable: const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment"; When I remove the const on this variable declaration, I get many occurrences of the following linker error: error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > whiteSpaceBeforeLeadingCmntOption" (?whiteSpaceBeforeLeadingCmntOption@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in REGISTER_TO_UNSRLZ.obj This is in a .h file, which is included various places, but I have a #ifndef band on it to avoid including it in several places. Any ideas what the error is from?
This works when you have const in the .h, since const implies static so you can have the same variable in multiple compilands. By removing const on a variable defined in a .h file, you are creating multiple instances with the same identifier within the same program. If you need to remove const, in the .h, you could do: extern std::string whiteSpaceBeforeLeadingCmntOption; And then have: std::string whiteSpaceBeforeLeadingCmntOption = ""; In one of your .cpp files.
1,094,532
1,094,560
Problem in overriding malloc
I am trying to override malloc by doing this. #define malloc(X) my_malloc((X)) void* my_malloc(size_t size) { void *p = malloc(size); printf ("Allocated = %s, %s, %s, %x\n",__FILE__, __LINE__, __FUNCTION__, p); return p; } However, this is indefinitely calling my_malloc recursively (because of malloc call inside my_malloc). I wanted to call C malloc function inside my_malloc and not the macro implementation. Could you please let me know how to do that? Thanks.
Problem solved: void* my_malloc(size_t size, const char *file, int line, const char *func) { void *p = malloc(size); printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size); return p; } #define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__)
1,094,865
1,095,170
const std::map<boost::tuples::tuple, std::string>?
// BOOST Includes #include <boost/assign.hpp> // Boost::Assign #include <boost/assign/list_of.hpp> // Boost::Assign::List_Of #include <boost/assign/std/map.hpp> // Boost::Assign::Map_List_Of #include <boost/tuple/tuple.hpp> // Boost::Tuples // STD Includes #include <map> #include <vector> #include <string> // Using namespaces using namespace std; using namespace boost; using namespace boost::assign; // Consts const map<string, string> query_map = map_list_of<string, string> ("4556_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 4556") ("7552_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 7552") ("234x_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 2344 OR PMU_ID = 2345 OR PMU_ID = 2346 OR PMU_ID = 2347 OR PMU_ID = 2348") ("813x_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 8132 OR PMU_ID = 8133 OR PMU_ID = 8134 OR PMU_ID = 8135 OR PMU_ID = 8136"); const map<string, std::vector<int>> vector_map = map_list_of<string, std::vector<int>> ("4556", list_of(4556)) ("7552", list_of(7552)) ("234x", list_of(2344)(2345)(2346)(2347)(2348)) ("813x", list_of(8132)(8133)(8134)(8135)(8136)); Using boost - it's possible to init const std::containers for testing etc. making a const std::map or std::map is pretty easy as the above code shows. Creating a const map<string, std::vector<int>> is a bit more complex - but still fairly easy. I'm trying to come up with a const std::map<boost::tuples::tuple<string, string, string>, string> but I'm failing to initialize it. Has anyone else had any luck with it ? // Typedefs typedef boost::tuples::tuple<string, string, string> x3_string_tuple; // Constants const map<x3_string_tuple, string> query_selector_map = map_list_of<x3_string_tuple, string> ("4556", "SELECT", "FILENAME"), "4556_SELECT_FILENAME"); // ETC.
I tried this, and it fails because the keys of the map need to be comparable (with std::less, thus there needs to be an operator< defined). boost::tuple's comparison operators are defined in the header boost/tuple/tuple_comparison.hpp. Having included that, this code works fine: #include <boost/assign/list_of.hpp> #include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <map> #include <string> using std::string; typedef boost::tuple<string, string, string> tpl_t; int main() { using boost::assign::map_list_of; std::map<tpl_t, string> const m = map_list_of(tpl_t("a","b","c"), "c")(tpl_t("x","y","c"), "z"); }
1,094,918
1,096,211
Performance difference in for loop condition?
I have a simple question that I am posing mostly for my curiousity. What are the differences between these two lines of code? (in C++) for(int i = 0; i < N, N > 0; i++) for(int i = 0; i < N && N > 0; i++) The selection of the conditions is completely arbitrary, I'm just interested in the differences between , and &&. I'm not a beginner to coding by any means, but I've never bothered with the comma operator. Are there performance/behavior differences or is it purely aesthetic? One last note, I know there are bigger performance fish to fry than a conditional operator, but I'm just curious. Indulge me. Edit Thanks for your answers. It turns out the code that prompted this question had misused the comma operator in the way I've described. I wondered what the difference was and why it wasn't a && operator, but it was just written incorrectly. I didn't think anything was wrong with it because it worked just fine. Thanks for straightening me out.
Although it looks like it, for(int i = 0; i < N, N > 0; i++) and for(int i = 0; i < N && N > 0; i++) are not equivalent. Here is the proof. int main(int argc, char* argv[]) { int N = 10; int i = 5; int val = (N, i); cout << val << endl; } Result: 5 Which means that the when determining when the loop will exit it will use N > 0. If N = 10, this means that it will always be true and the loop will never exit. Run this and see the proof. int main(int argc, char* argv[]) { int N = 10; int i = 5; for(int i = 0; i < N, N > 0; i++){ cout << val << endl; } } bash-2.05$ ./a.out 0 1 2 3 4 5 6 7 8 9 10 11 ... 142 143 144 145 146 147 148 ^C If N is a constant or variable that doesn't change inside the loop then you could just remove the N > 0 check by checking it once first, i.e. if (N > 0){ for (int i = 0; i < N; i++) ... }
1,095,225
1,095,233
Exception slicing - is this due to generated copy constructor?
I've just fixed a very subtle bug in our code, caused by slicing of an exception, and I now want to make sure I understand exactly what was happening. Here's our base exception class, a derived class, and relevant functions: class Exception { public: // construction Exception(int code, const char* format="", ...); virtual ~Exception(void); <snip - get/set routines and print function> protected: private: int mCode; // thrower sets this char mMessage[Exception::MessageLen]; // thrower says this FIXME: use String }; class Derived : public Exception { public: Derived (const char* throwerSays) : Exception(1, throwerSays) {}; }; void innercall { <do stuff> throw Derived("Bad things happened!"); } void outercall { try { innercall(); } catch(Exception& e) { printf("Exception seen here! %s %d\n", __FILE__, __LINE__); throw e; } } The bug was of course that outercall ends up throwing an Exception, instead of a Derived. My bug resulted from higher in the call stack attempts to catch the Derived failing. Now, I just want to make sure I understand - I believe that at the 'throw e' line, a new Exception object is being created, using a default copy constructor. Is that what's really going on? If so, am I allowed to lock out copy constructors for objects that will be thrown? I'd really prefer this not happen again, and our code has no reason to copy Exception objects (that I know of). Please, no comments on the fact that we have our own exception hierarchy. That's a bit of old design that I'm working to correct (I'm making good progress. I've gotten rid of the home-grown string class, and many of the home-grown containers.) UPDATE: To be clear, I had fixed the bug (by changing 'throw e' to 'throw') before I ever asked the question. I was just looking for confirmation of what was going on.
When you throw an object, you're actually throwing a copy of the object, not the original. Think about it - the original object is on the stack, but the stack is being unwound and invalidated. I believe this is part of the standard, but I don't have a copy to reference. The type of exception being thrown in the catch block is the base type of the catch, not the type of the object that was thrown. The way around this problem is to throw; rather than throw e; which will throw the original caught exception.
1,095,298
1,095,321
GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'
I'm setting up a C++ project, on Ubuntu x64, using Eclipse-CDT. I'm basically doing a hello world and linking to a commerical 3rd party library. I've included the header files, linked to their libraries, but I still get linker errors. Are there some possible problems here other than the obvious (e.g. I am 99% sure I'm linking to the correct library). Is there a way to confirm the static libraries I am linking to are 64bit? Is there a way to confirm that the library has the class (and methods) I am expecting it to have? Eclipse says: Building target: LinkProblem Invoking: GCC C++ Linker g++ -L/home/notroot/workspace/somelib-3/somelib/target/bin -o"LinkProblem" ./src/LinkProblem.o -lsomelib1 -lpthread -lsomelib2 -lsomelib3 ./src/LinkProblem.o: In function `main': /home/notroot/workspace/LinkProblem/Debug/../src/LinkProblem.cpp:17: undefined reference to `SomeClass::close()' ./src/LinkProblem.o: In function `SomeOtherClass': /home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `SomeClass::SomeClass()' /home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `vtable for SomeOtherClass' /home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:151: undefined reference to `SomeClass::~SomeClass()' ./src/LinkProblem.o: In function `~SomeOtherClass': /home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `vtable for SomeOtherClass' /home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()' /home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()' collect2: ld returned 1 exit status make: *** [LinkProblem] Error 1
Assuming those methods are in one of the libs it looks like an ordering problem. When linking libraries into an executable they are done in the order they are declared. Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies. How it works: Take all the object files and combine them into an executable Resolve any dependencies among object files. For-each library in order: Check unresolved dependencies and see if the lib resolves them. If so load required part into the executable. Example: Objects requires: Open Close BatchRead BatchWrite Lib 1 provides: Open Close read write Lib 2 provides BatchRead (but uses lib1:read) BatchWrite (but uses lib1:write) If linked like this: gcc -o plop plop.o -l1 -l2 Then the linker will fail to resolve the read and write symbols. But if I link the application like this: gcc -o plop plop.o -l2 -l1 Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved.
1,095,378
1,096,487
How do I destruct data associated with an object after the object no longer exists?
I'm creating a class (say, C) that associates data (say, D) with an object (say, O). When O is destructed, O will notify C that it soon will no longer exist :( ... Later, when C feels it is the right time, C will let go of what belonged to O, namely D. If D can be any type of object, what's the best way for C to be able to execute "delete D;"? And what if D is an array of objects? My solution is to have D derive from a base class that C has knowledge of. When the time comes, C calls delete on a pointer to the base class. I've also considered storing void pointers and calling delete, but I found out that's undefined behavior and doesn't call D's destructor. I considered that templates could be a novel solution, but I couldn't work that idea out. Here's what I have so far for C, minus some details: // This class is C in the above description. There may be many instances of C. class Context { public: // D will inherit from this class class Data { public: virtual ~Data() {} }; Context(); ~Context(); // Associates an owner (O) with its data (D) void add(const void* owner, Data* data); // O calls this when he knows its the end (O's destructor). // All instances of C are now aware that O is gone and its time to get rid // of all associated instances of D. static void purge (const void* owner); // This is called periodically in the application. It checks whether // O has called purge, and calls "delete D;" void refresh(); // Side note: sometimes O needs access to D Data *get (const void *owner); private: // Used for mapping owners (O) to data (D) std::map _data; }; // Here's an example of O class Mesh { public: ~Mesh() { Context::purge(this); } void init(Context& c) const { Data* data = new Data; // GL initialization here c.add(this, new Data); } void render(Context& c) const { Data* data = c.get(this); } private: // And here's an example of D struct Data : public Context::Data { ~Data() { glDeleteBuffers(1, &vbo); glDeleteTextures(1, &texture); } GLint vbo; GLint texture; }; }; P.S. If you're familiar with computer graphics and VR, I'm creating a class that separates an object's per-context data (e.g. OpenGL VBO IDs) from its per-application data (e.g. an array of vertices) and frees the per-context data at the appropriate time (when the matching rendering context is current).
The question is rather vague on the requirements, so it's hard to give a good concrete answer. I hope the following helps. If you want the data to disappear immediately when its owner dies, have the owner delete it (and notify C if the C instances need to know). If you want C to do the deletion at its leisure, your solution looks fine. Deriving from Data seems to me the right thing to do. (Of course it is crucial that ~Data() be virtual, as you have done.) What if D is an array of objects? There are two interpretations of this question. If you mean that D is always an array, let it be an array (or vector<>) of pointers to Data. Then in C::purge() walk the vector and delete the objects. If you mean that D could be an array of objects but could also be a single object, there are two ways to go. Either decide that it is always an array (possibly of size 1), or that it is a single object (derived from Data) which can be a class wrapping the array of the actual objects (or pointers to them). In the latter case, the wrapper class destructor should walk the array and do the deletions. Note that if you want the array (or vector<>) to contains the actual objects, not pointers to them, (in which case you won't have to walk the array and delete manually) then you'll have the following limitations. 1. All objects in the array will have to be of the same actual type. 2. You will have to declare the array to be of that type. This will lose you all the benfits of polymorphism.