question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,837,854
2,838,033
Initializing an object to all zeroes
Oftentimes data structures' valid initialization is to set all members to zero. Even when programming in C++, one may need to interface with an external API for which this is the case. Is there any practical difference between: some_struct s; memset(&s, 0, sizeof(s)); and simply some_struct s = { 0 }; Do folks find themselves using both, with a method for choosing which is more appropriate for a given application? (Hopefully it is understood that this is only currently applicable to POD structures; you'd get all sorts of havoc if there was a C++ std::string in that structure.) For myself, as mostly a C++ programmer who doesn't use memset much, I'm never certain of the function signature so I find the second example is just easier to use in addition to being less typing, more compact, and maybe even more obvious since it says "this object is initialized to zero" right in the declaration rather than waiting for the next line of code and seeing, "oh, this object is zero initialized." When creating classes and structs in C++ I tend to use initialization lists; I'm curious about folks thoughts on the two "C style" initializations above rather than a comparison against what is available in C++ since I suspect many of us interface with C libraries even if we code mostly in C++ ourselves. Edit: Neil Butterworth posed this question, in followup, that I believe is an interesting corollary to this question.
memset is practically never the right way to do it. And yes, there is a practical difference (see below). In C++ not everything can be initialized with literal 0 (objects of enum types can't be), which is why in C++ the common idiom is some_struct s = {}; while in C the idiom is some_struct s = { 0 }; Note, that in C the = { 0 } is what can be called the universal zero initializer. It can be used with objects of virtually any type, since the {}-enclosed initializers are allowed with scalar objects as well int x = { 0 }; /* legal in C (and in C++) */ which makes the = { 0 } useful in generic type-independent C code (type-independent macros for example). The drawback of = { 0 } initializer in C89/90 and C++ is that it can only be used as a part of declaration. (C99 fixed this problem by introducing compound literals. Similar functionality is coming to C++ as well.) For this reason you might see many programmers use memset in order to zero something out in the middle of C89/90 or C++ the code. Yet, I'd say that the proper way to do is still without memset but rather with something like some_struct s; ... { const some_struct ZERO = { 0 }; s = ZERO; } ... i.e. by introducing a "fictive" block in the middle of the code, even though it might not look too pretty at the first sight. Of course, in C++ there's no need to introduce a block. As for the practical difference... You might hear some people say that memset will produce the same results in practice, since in practice the physical all-zero bit pattern is what is used to represent zero values for all types. However, this is generally not true. An immediate example that would demonstrate the difference in a typical C++ implementation is a pointer-to-data-member type struct S; ... int S::*p = { 0 }; assert(p == NULL); // this assertion is guaranteed to hold memset(&p, 0, sizeof p); assert(p == NULL); // this assertion will normally fail This happens because a typical implementation usually uses the all-one bit pattern (0xFFFF...) to represent the null pointer of this type. The above example demonstrates a real-life practical difference between a zeroing memset and a normal = { 0 } initializer.
2,838,107
2,838,133
Initializing structs in C++
As an addendum to this question, what is going on here: #include <string> using namespace std; struct A { string s; }; int main() { A a = {0}; } Obviously, you can't set a std::string to zero. Can someone provide an explanation (backed with references to the C++ Standard, please) about what is actually supposed to happen here? And then explain for example): int main() { A a = {42}; } Are either of these well-defined? Once again an embarrassing question for me - I always give my structs constructors, so the issue has never arisen before.
Your struct is an aggregate, so the ordinary rules for aggregate initialization work for it. The process is described in 8.5.1. Basically the whole 8.5.1 is dedicated to it, so I don't see the reason to copy the whole thing here. The general idea is virtually the same it was in C, just adapted to C++: you take an initializer from the right, you take a member from the left and you initialize the member with that initializer. According to 8.5/12, this shall be a copy-initialization. When you do A a = { 0 }; you are basically copy-initializing a.s with 0, i.e. for a.s it is semantically equivalent to string s = 0; The above compiles because std::string is convertible from a const char * pointer. (And it is undefined behavior, since null pointer is not a valid argument in this case.) Your 42 version will not compile for the very same reason the string s = 42; will not compile. 42 is not a null pointer constant, and std::string has no means for conversion from int type. P.S. Just in case: note that the definition of aggregate in C++ is not recursive (as opposed to the definition of POD, for example). std::string is not an aggregate, but it doesn't change anything for your A. A is still an aggregate.
2,838,297
2,838,330
How does calling this function object work?
I have a class class fobj{ public: fobj(int i):id(i) {} void operator()() { std::cout<<"Prints"<<std::endl; } private: int id; }; template<typename T> void func(T type) { type(); } If I invoke func like Method 1: func(fobj(1)); the message I wanted to print is printed. I was always thinking I needed to do something like Method 2: fobj Iobj(1); // create an instance of the fobj class func(Iobj); // call func by passing Iobj(which is a function object) How does Method 1 work? I mean what exactly happens? And how is a call made to the operator() in class fobj ?
One thing to note is that this works because your template class is taking an object by value: template<typename T> void func(T type) // this takes a T by value ... because of this, it can take either an lvalue (such as an actual variable) or an rvalue (such as the temporary). If for some reason you did want to limit func to only taking an lvalue, you could modify the function to using pass by reference: template <typename T> void func(T &type) // this takes a T by reference ... using pass by reference does allow the side effect of the function being able to modify the object.
2,838,345
2,838,378
When does code bloat start having a noticeable effect on performance?
I am looking to make a hefty shift towards templates in one of my OpenGL projects, mainly for fun and the learning experience. I plan on watching the size of the executable carefully as I do this, to see just how much of the notorious bloat happens. Currently, the size of my Release build is around 580 KB when I favor speed and 440 KB when I favor size. Yes, it's a tiny project, and in fact even if my executable bloats 10 x its size, it's still going to be 5 MB or so, which hardly seems large by today's standards... or is it? This brings me to my question. Is speed proportional to size, or are there leaps and plateaus at certain thresholds, thresholds which I should be aiming to stay below? (And if so, what are the thresholds specifically?)
On most modern processors, locality is going to be more important than size. If you can keep all the currently executing code and a good portion of the data in your L1 cache, you're going to see big wins. If you're jumping all around, you may force code or data out of the cache and then need it again shortly thereafter. "Data Oriented Design" helps with both code and data locality, in my experience. You may be interested in the Pitfalls of Object Oriented Programming slides (pdf) (mirrored here (pdf)), which do a good job of showing how to tackle things in such a way that you get both good data and code locality. (Incidentally, this whole cache size and locality thing is one of the reasons why "optimize for size" can outperform "optimize for speed" in some cases.)
2,838,542
14,391,105
How can I get the contents of a file at build time into my C++ string?
I have a file I am compiling in C++ in which I wish to have a string whose value is the contents of a file at the time of compilation. In other words, I'd like to #include the file but have that be inside double quotes. How can I do this in C++? Now what if that file contains double quotes as part of its text, how do I get those escaped?
To correctly create a header with the correct null termination in the string use sed: xxd -i ${INPUT_FILE_NAME} | sed s/}\;/,0x00}\;/ > ${INPUT_FILE_PATH}.h See http://gamesfromwithin.com/quick-tip-working-with-shaders-on-ios for details.
2,838,608
2,849,430
How to check for cancel button in custom action without doing anything else
I know when I put something in the log using ::MsiProcessMessage(hModule, INSTALLMESSAGE(INSTALLMESSAGE_INFO), ...); that I can check if the return value is IDCANCEL and return ERROR_INSTALL_USEREXIT to Windows installer. How do I check for that return value without having to put something in the log or alter the progress bar?
I believe the call you describe will place the info message in the log. But other than that, why would you have to put something in the log or alter the progress bar? If your action takes a long time, it should report progress. If it is short and you never call MsiProcessMesssage, Windows Installer will handle cancel immediately afterward. The only problem case is if you call MsiProcessMessage and swallow a cancel without reporting it.
2,838,720
2,838,793
Is the stack unwound when you stop debugging?
Just curious if my destructors are being called. (Specifically for Visual Studio, when you hit the red stop button)
No the process is terminated in VS2005, VS2008 and VS2010 when you press stop debugging. You can easily check this by making a destructor that writes something to a file (and flushes output). I'm not sure what standard you mean, but there is no standard that would define this behavior.
2,838,790
2,838,795
Efficient update of SQLite table with many records
I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server). I have to update hundreds of thousands of records sometimes to enter left right values (they are hierarchical), but have found the standard update table set left_value = 4, right_value = 5 where id = 12340; to be very slow. I have tried surrounding every thousand or so with begin; .... update... update table set left_value = 4, right_value = 5 where id = 12340; update... .... commit; but again, very slow. Odd, because when I populate it with a few hundred thousand (with inserts), it finishes in seconds. I am currently trying to test the speed in python (the slowness is at the command line and python) before I move it to the C++ implementation, but right now this is way to slow and I need to find a new solution unless I am doing something wrong. Thoughts? (would take open source alternative to SQLite that is portable as well)
Create an index on table.id create index table_id_index on table(id)
2,838,972
2,839,024
What is the most efficient way to find missing semicolons in VS with C++?
What are the best strategies for finding that missing semicolon that's causing the error? Are there automated tools that might help. I'm currently using Visual Studio 2008, but general strategies for any environment would be interesting and more broadly useful. Background: Presently I have a particularly elusive missing semicolon (or brace) in a C++ program that is causing a C2143 error. My header file dependencies are fairly straightforward, but still I can't seem to find the problem. Rather than post my code and play Where's Wally (or Waldo, depending on where you're from) I thought it would be more useful to get some good strategies that can be applied in this and similar situations. As a side-question: the C2143 error is showing up in the first line of the first method declaration (i.e. the method's return type) in a .cpp file that includes only its associated .h file. Would anything other than semicolons or braces lead to this behaviour?
It's unlikely to be a missing semicolon, except (as @Michael suggested) from the end of a class. Generally a missing semicolon causes an error within a line or two. If it's a scope brace then it's usually not too far away, although sometimes they can be a long way off.. Backtrack from the error line (go backwards up the code, and then backwards through each include from the bottom one), checking the braces. Chances are it's at the start of your cpp file just prior to the site of the error, or the end of the last include, so that's the best place to start. You can use various techniques: Just read the code. If you follow a clean symmetrical coding style a missing brace will often slap you in the face. (You can use Edit->Advanced->Format Document to tidy up code if it is in an inconsistent style). Place the cursor on each end of scope } and press ctrl+} to take the cursor to the matching brace. This will either do nothing, in which case there is no match, or will jump to the match and you can check that it is the correct brace. If you have a lot of code to consider, just comment a lot of it out with #if FALSE. You'll get different compiler errors, but if the original error stays you know it's not caused by the commented code, and you can move on to the next include/class/block. The worst case scenario is that it's some code in a macro. If you have added/edited/used any macros in the last day, then check them first.
2,838,980
2,838,996
Error while excuting a simple boost thread program
Could you tell mw what is the problem with the below boost::thread program #include<iostream> #include<boost/thread/thread.hpp> boost::mutex mutex; class A { public: A() : a(0) {} void operator()() { boost::mutex::scoped_lock lock(mutex); } private: int a; }; int main() { boost::thread thr1(A()); boost::thread thr2(A()); thr1.join(); thr2.join(); } I get the error message: error: request for member 'join' in 'thr1', which is of non-class type 'boost::thread()(A ()())' BoostThread2.cpp:30: error: request for member 'join' in 'thr2', which is of non-class type 'boost::thread ()(A ()())'
You have stumbled on something wonderfully known as the most vexing parse. The quickest way to fix that is to add an extra set of parentheses: boost::thread thr1((A())); You can also introduce a temporary: A tmp1; boost::thread thr1(tmp1); In the most vexing parse, what you think is generating a temporary is parsed as if it's a function taking no parameters. It then treats thr1 as a prototype to a function that takes a single parameter (which is the function mentioned previously) and returning a boost::thread.
2,839,017
2,839,035
Does this have anything to do with endian-ness?
For this code: #include<stdio.h> void hello() { printf("hello\n"); } void bye() { printf("bye\n"); } int main() { printf("%p\n", hello); printf("%p\n", bye); return 0; } output on my machine: 0x80483f4 0x8048408 [second address is bigger in value] on Codepad 0x8048541 0x8048511 [second address is smaller in value] Does this have anything to do with endian-ness of the machines? If not, Why the difference in the ordering of the addresses? Also, Why the difference in the difference? 0x8048541 - 0x8048511 = 0x30 0x8048408 - 0x80483f4 = 0x14 Btw, I just checked. This code (taken from here) says that both the machines are Little-Endian #include<stdio.h> int main() { int num = 1; if(*(char *)&num == 1) printf("Little-Endian\n"); else printf("Big-Endian\n"); return 0; }
It has nothing to do with endinanness, but with the C++ standard. C++ isn't required to write functions in the order you see them to disk (and think about cross-file linking and even linking other libraries, that's just not feasable), it can write them in any order it wishes. About the difference between the actual values, one compiler might add guards around a block to prevent memory overrides (or other related stuff, usually only in debug mode). And there's nothing preventing the compiler from writing other functions between your 2 functions. Keep in mind even a simple hello world application comes with thousands of bytes of executable code. The bottom line is: never assume anything about how things are positioned in memory. Your assumptions will almost always be wrong. And why even assume? There's nothing to be gained over writing normal, safe, structured code anyway.
2,839,068
2,839,115
template warnings and error help, (gcc)
I'm working on an container class template (for int,bool,strings etc), and I've been stuck with this error cont.h:56: error: expected initializer before '&' token for this section template <typename T> const Container & Container<T>::operator=(const Container<T> & rightCont){ what exactly have I done wrong there?. Also not sure what this warning message means. cont.h:13: warning: friend declaration `bool operator==(const Container<T>&, const Container<T>&)' declares a non-template function cont.h:13: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning at this position template <typename T> class Container{ friend bool operator==(const Container<T> &rhs,const Container<T> &lhs); public:
In the first case you've done things backwards. When you specify the return type, you have to include the template parameter list into the template identifier (Container<T>), but when you specify parameter type, you don't need to do it (just Container is enough) template <typename T> const Container<T> & Container<T>::operator=(const Container & rightCont){ ... You did it the other way around for some reason. In the second case, when you declare operator == as a friend it simply warns you that that in this case operator == you are referring to is an ordinary function. It can't be a specialization of a template. I.e. for the class Container<int> the function bool operator==(const Container<int> &rhs, const Container<int> &lhs) { // ... } will be a friend. But specialization of function template template <class U> bool operator==(const Container<U> &rhs, const Container<U> &lhs) { // ... } for U == int will not be a friend of Container<int>. If that's your intent, you are OK. If you wanted to befriend a specific specialization of the above template, you'd have to say template <typename T> class Container { friend bool operator==<T>(const Container<T> &rhs, const Container<T> &lhs); ... If you wanted to befriend all specialization of the above template, you'd have to say template <typename T> class Container { template <class U> friend bool operator==(const Container<U> &rhs, const Container<U> &lhs); ...
2,839,087
2,861,798
How to test your code on a machine with big-endian architecture?
Both ideone.com and codepad.org have Little-Endian architechtures. I want to test my code on some machine with Big-Endian architechture (for example - Solaris - which I don't have). Is there some easy way that you know about?
Googling "big endian online emulator" lead me to PearPC. I assume that if you have the patience you can install Mandrake Linux, get gcc, and go party.
2,839,142
2,839,206
creating a vector with references to some of the elements of another vector
I have stored instances of class A in a std:vector, vec_A as vec_A.push_back(A(i)). The code is shown below. Now, I want to store references some of the instances of class A (in vec_A) in another vector or another array. For example, if the A.getNumber() returns 4, 7, 2 , I want to store a pointer to that instance of A in another vector, say std:vector<A*> filtered_A or an array. Can someone sow me how to do this?? Thanks! class A { public: int getNumber(); A(int val); ~A(){}; private: int num; }; A::A(int val){ num = val; }; int A::getNumber(){ return num; }; int main(){ int i =0; int num; std::vector<A> vec_A; for ( i = 0; i < 10; i++){ vec_A.push_back(A(i)); } std::cout << "\nPress RETURN to continue..."; std::cin.get(); return 0; }
I think the safest thing would be to have a second vector that holds indexes into the first vector: using std::vector; vector<A> main; vector<vector<A>::size_type> secondary; main.push_back(...); secondary.push_back(main.size() - 1); // add the index of the last item Now, to look up an item you take the value in secondary and use that to index into main: main[secondary[...]]; The reason I recommend this instead of just having secondary store a direct pointer is that every time you add to vector it may need to resize the vector which can invalidate any existing pointers: using std::vector; vector<A> vec; vec.push_back(A()); // get a pointer to the item you just added A *p0 = &vec[0]; // add another item a.push_back(A()); // because a push_back() can cause the vector to resize, p0 may no // longer point to valid memory and cannot safely be dereferenced
2,839,381
2,839,428
deleting an array that stores pointers to some objects
I am storing pointers to elements of a vec_A in an array A* a_ptrs[3] . Assume that vec_A will not be resized. So, a_ptrs[i] will point to the correct element. My question is: Suppose A* a_ptrs[3] is declared in a class B. Since it is not created using 'new' I am guessing I don't need to delete it in the destructor. Am I right?? class A { public: int getNumber(); A(int val); ~A(){}; private: int num; }; A::A(int val){ num = val; }; int A::getNumber(){ return num; }; int main(){ int i =0; int num; std::vector<A> vec_A; for ( i = 0; i < 10; i++){ vec_A.push_back(A(i)); } A* a_ptrs[3]; a_ptrs[0] = &vec_A[0]; a_ptrs[1] = &vec_A[3]; a_ptrs[2] = &vec_A[5]; for (i = 0; i<3; i++){ std::cout<<"\n: a_ptrs[i].getNumber() = "<<a_ptrs[i]->getNumber(); } std::cout << "\nPress RETURN to continue..."; std::cin.get(); return 0; }
Yep, thats correct. You don't need to use delete. The only issue is if the vector is resized e.g. by calling push_back etc - but you called that out in your post.
2,839,390
2,839,641
How do I convert a double into a string in C++(without scientific notation)?
How to convert a double into a floating-point string representation without scientific notation in C++. "Small" samples (effective numbers may be of any size, such as 1.5E200 or 1e-200) : 0.0000000000000000000000000000000000000000000000000000000023897356978234562 Thank you.
string doubleToStr(double d) { stringstream ss; ss << fixed << setprecision(400) << d; return ss.str(); }
2,839,470
2,839,510
Class lookup structure array in C++
I'm trying to create a structure array which links input strings to classes as follows: struct {string command; CommandPath cPath;} cPathLookup[] = { {"set an alarm", AlarmCommandPath}, {"send an email", EmailCommandPath}, {"", NULL} }; which will be used as follows: CommandPath *cPath = NULL; string input; getline(cin, input); for(int i = 0; cPathLookup[i] != ""; i++) { if(cPathLookup[i].command == input) cPath = new cPathLookup[i].cPath; } Obviously, this code is meaningless, but I think my intention is apparent - depending on input, I'd like cPath to be initialized as either a new AlarmCommandPath or a new EmailCommandPath. I could handle it with a function returning an instance depending on input, but a whole sequence of ifs just seems inelegant. I should also note that, in case it's not apparent and important, that AlarmCommandPath and EmailCommandPath are derived from CommandPath, and CommandPath is an abstract class. Thanks for any help you can offer. EDIT: I just noticed that, in spite of CommandPath being abstract, I have a declaration: CommandPath *cPath = NULL; in working code. Why does that compile?
AlarmCommandPath and EmailCommandPath are derived from COmmandPath, correct? In this case you cannot assign an instance of AlarmCommandPath/EmailCommandPath to CommandPath - it is technically possible, but it won't do what you want. The instance CommandPath will remain an instance of CommandPath (it will have virtual function table of CommandPath), no matter what you assign to it. You need to use factory methods (a function that will return CommandPath*). Something like that: struct A{ }; struct B: public A{ }; struct C: public A{ }; A* factoryA(){ return new A(); } A* factoryB(){ return new B(); } A* factoryC(){ return new C(); } typedef A* (*FactoryMethod)(); struct{ const char* command; FactoryMethod factoryMethod; } factoryTable[] = { {"A", factoryA}, {"B", factoryB}, {"C", factoryC}, {0,0} };
2,839,551
2,839,555
What's the equivalent of new/delete of C++ in C?
What's the equivalent of new/delete of C++ in C? Or it's the same in C/C++?
There's no new/delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety. #include <stdlib.h> int* p = malloc(sizeof(*p)); // int* p = new int; ... free(p); // delete p; int* a = malloc(12*sizeof(*a)); // int* a = new int[12]; ... free(a); // delete[] a;
2,839,592
2,839,616
Equivalent of %02d with std::stringstream?
I want to output an integer to a std::stringstream with the equivalent format of printf's %02d. Is there an easier way to achieve this than: std::stringstream stream; stream.setfill('0'); stream.setw(2); stream << value; Is it possible to stream some sort of format flags to the stringstream, something like (pseudocode): stream << flags("%02d") << value;
You can use the standard manipulators from <iomanip> but there isn't a neat one that does both fill and width at once: stream << std::setfill('0') << std::setw(2) << value; It wouldn't be hard to write your own object that when inserted into the stream performed both functions: stream << myfillandw( '0', 2 ) << value; E.g. struct myfillandw { myfillandw( char f, int w ) : fill(f), width(w) {} char fill; int width; }; std::ostream& operator<<( std::ostream& o, const myfillandw& a ) { o.fill( a.fill ); o.width( a.width ); return o; }
2,839,597
2,839,610
left-hand operand of comma has no effect?
I'm having some trouble with this warning message, it is implemented within a template container class int k = 0, l = 0; for ( k =(index+1), l=0; k < sizeC, l < (sizeC-index); k++,l++){ elements[k] = arryCpy[l]; } delete[] arryCpy; this is the warning i get cont.h: In member function `void Container<T>::insert(T, int)': cont.h:99: warning: left-hand operand of comma has no effect cont.h: In member function `void Container<T>::insert(T, int) [with T = double]': a5testing.cpp:21: instantiated from here cont.h:99: warning: left-hand operand of comma has no effect cont.h: In member function `void Container<T>::insert(T, int) [with T = std::string]': a5testing.cpp:28: instantiated from here cont.h:99: warning: left-hand operand of comma has no effect >Exit code: 0
The comma expression a,b,c,d,e is similar to { a; b; c; d; return e; } therefore, k<sizeC, l<(sizeC - index) will only return l < (sizeC - index). To combine conditionals, use && or ||. k < sizeC && l < (sizeC-index) // both must satisfy k < sizeC || l < (sizeC-index) // either one is fine.
2,839,940
2,840,125
Problem Building dschaefer / android-box2d
I'm trying to build dschaefer android-box2d, and did follow the recipe. I do get this error when trying to build the TestBox2d with eclipse: make all /cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/bin/arm-eabi-ld \ -nostdlib -shared -Bsymbolic --no-undefined \ -o obj/libtest.so obj/test.o -L../box2d/lib/android -lbox2d \ -L/cygdrive/c/android/android-ndk-r3/build/platforms/android-3/arch-arm/usr/lib \ -llog -lc -lstdc++ -lm \ /cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/lib/gcc/arm-eabi/4.2.1/interwork/libgcc.a \ /cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/bin/arm-eabi-ld: cannot find -lbox2d make: *** [obj/libtest.so] Error 1 The only thing I did change was in the TestBox2d\Makefile where i did change the path to the NDK. There are some other that have the same problem HERE but I do not know how to fix it.
The error indicates that the linker cannot find the library box2d. What I think is the problem is that you have a relative path pointing to the location of the box2d library (-L../box2d/lib/android). If your build directory changes, your build will break. What you might want to do is substitute an absolute path for the box2d library (such as -L/cygdrive/c/box2d/lib/android). All of your other link paths to the NDK are absolute. A better way would be to put the path to your box2d library in an environment variable and use this environment variable in your makefile.
2,839,980
2,840,022
Visual Studio Solution: static or shared projects?
When a whole project (solution) consists of multiple subprojects (.vcproj), what is a preferable way to tie them: as static libraries or as shared libraries? Assuming that those subprojects are not used elsewhere, the shared libraries approach shouldn't decrease memory usage or load time.
Opinion: Static, in nearly all cases. Building interfaces across dynamically loaded libraries is much harder in C++ on Windows. For example, unlike with Unix shared objects, you cannot have a standard singleton for all modules, because a DLL would have it's own set of static variables. Object oriented interfaces are often hard to export from a DLL. As for load time, issues like rebasing need to be adressed with shared libraries. On the other hand, the libraries you do not share today might become shared in future. However, in most cases it is better to pay the price of duplication in RAM or disk image than the price of dependency on extra modules.
2,840,026
3,092,278
What grid distributed computing frameworks are currently favoured for trading systems
There seems to a quite a few grid computing frameworks out there, but which ones are actually being used to any great extent by the investment banks for purposes of low latency distributing calculation? I'd be interested to hear answers covering both windows,Linux and cross platform. Also, what RPC mechanisms seem to be favoured most? I've heard that for reason of low latency and speed, the calculations themselves are quite often written in C++/C as calculations running on VMs are several orders of magnitude slower than native code. Does this seem to be a common scenario in practice? e.g distributed .NET grid framework running calculations written in native c++/c?
Some directions (actually used in some corporate investment banks) : Home made solutions involving PC farms (traders queue their computation requests) GPU since computationally intensive fiancial operations (eg. Monte Carlo pricing) are usually heavily parallelizable.
2,840,079
2,840,113
Statically Init a derived class
With c++, Is there a way to get a derived class to inherit its own static initializer? I am trying to do something like the following: class Base { public: class StaticInit { public: virtual StaticInit() =0; }; }; class Derived: public Base { public: virtual StaticInit::StaticInit() { //do something with the derived class } static StaticInit init; } static Derived::StaticInit init; it would also be nice if I didn't have to define the init var in each derived class. I am currently redefining the StaticInit internal class in each derived class but it seems redundant. Each derived class is a singleton, and I need the instance to be stored in a lookup table at program startup.
I use templates to do this, rather than inheritance - something like: template <typename T> struct StaticInit { StaticInit() { // do whatever with T } }; in use: static StaticInit <SomeClass> init;
2,840,193
2,840,225
allocating extra memory for a container class
Hey there, I'm writing a template container class and for the past few hours have been trying to allocate new memory for extra data that comes into the container (...hit a brick wall..:| ) template <typename T> void Container<T>::insert(T item, int index){ if ( index < 0){ cout<<"Invalid location to insert " << index << endl; return; } if (index < sizeC){ //copying original array so that when an item is //placed in the middleeverything else is shifted forward T *arryCpy = 0; int tmpSize = 0; tmpSize = size(); arryCpy = new T[tmpSize]; int i = 0, j = 0; for ( i = 0; i < tmpSize; i++){ for ( j = index; j < tmpSize; j++){ arryCpy[i] = elements[j]; } } //overwriting and placing item and location index elements[index] = item; //copying back everything else after the location at index int k = 0, l = 0; for ( k =(index+1), l=0; k < sizeC || l < (sizeC-index); k++,l++){ elements[k] = arryCpy[l]; } delete[] arryCpy; arryCpy = 0; } //seeing if the location is more than the current capacity //and hence allocating more memory if (index+1 > capacityC){ int new_capacity = 0; int current_size = size(); new_capacity = ((index+1)-capacityC)+capacityC; //variable for new capacity T *tmparry2 = 0; tmparry2 = new T[new_capacity]; int n = 0; for (n = 0; n < current_size;n++){ tmparry2[n] = elements[n]; } delete[] elements; elements = 0; //copying back what we had before elements = new T[new_capacity]; int m = 0; for (m = 0; m < current_size; m++){ elements[m] = tmparry2[m]; } //placing item elements[index] = item; } else{ elements[index] = item; } //increasing the current count sizeC++; my testing condition is Container cnt4(3); and as soon as i hit the fourth element (when I use for egsomething.insert("random",3);) it crashes and the above doesnt work. where have I gone wrong?
Several things don't make too much sense to me: if (index+1 > capacityC){ shouldn't that be: if (index >= capacityC){ Also, when you grow the array I don't see why you are doing two lots of copying. shouldn't: delete[] elements; elements = 0; be: delete[] elements; elements = tmparray2;
2,840,305
2,840,332
Including Libraries C++
How do I properly include libraries in C++? I'm used to doing the standard libraries in C++ and my own .h files. I'm trying to include wxWidgets or GTK+ in code::blocks and/or netbeans C/C++ plugin. I've included ALL libraries but I constantly get errors such as file not found when it is explicitly in the include! One error: test1.cpp:1:24: wx/msw/wx.rc: No such file or directory : Yes the .h file library is included; what am I missing? Do I need to be importing other things as well? Is there a tutorial for this? Obviously my shoddy textbook hasn't prepared me for this.
Firstly, header files are not the same thing as libraries. A header is a C++ text file containing declarations of things, while a library is a container for compiled, binary code. When you #include a header file, the compiler/IDE needs to know where to find it. There is typically an IDE setting which tells the compiler where to look, or you can do it from the command line, normally using the -I switch. It sounds to me as if you have not set up the path to search for header files on in your IDE.
2,840,342
2,840,391
Benefit of using multiple SIMD instruction sets simultaneously
I'm writing a highly parallel application that's multithreaded. I've already got an SSE accelerated thread class written. If I were to write an MMX accelerated thread class, then run both at the same time (one SSE thread and one MMX thread per core) would the performance improve noticeably? I would think that this setup would help hide memory latency, but I'd like to be sure before I start pouring time into it.
The SSE and MMX instruction sets share the same set of vector processing execution units in the CPU. Therefore, running an SSE thread and an MMX thread will have the same resources available each thread as if running two SSE threads (or two MMX threads). The only difference is in instructions which exist in SSE but not MMX (since SSE is an extension of MMX). But in that case the MMX is probably going to be slower because it doesn't have those more advanced instructions available to it. So the answer is: No, you would not see a performance improvement compared to running two SSE threads.
2,840,496
2,840,512
Visual studio c++ documentation generator
Is there a way to get documentation(like javadoc) in a visual-c++ project? I'm using visual studio 2010. thanks!
You could use the XML-Documentation format, supported by VS2010, too. http://msdn.microsoft.com/en-us/library/ms177226%28VS.80%29.aspx After commenting your code, you can use Sandcastle to create a MSDN-like documentation: http://sandcastle.codeplex.com/. (Here is a GUI representation for Sandcastle, which is a lot easier to use: https://github.com/EWSoftware/SHFB) I use AtomineerUtils to create the XML-Documentation headers automatically. This tool will help you a lot. You can have free base version here: http://www.atomineerutils.com/products.php
2,840,640
2,840,647
How to loop through a boost::mpl::list?
This is as far as I've gotten, #include <boost/mpl/list.hpp> #include <algorithm> namespace mpl = boost::mpl; class RunAround {}; class HopUpAndDown {}; class Sleep {}; template<typename Instructions> int doThis(); template<> int doThis<RunAround>() { /* run run run.. */ return 3; } template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; } template<> int doThis<Sleep>() { /* zzz.. */ return -2; } int main() { typedef mpl::list<RunAround, HopUpAndDown, Sleep> acts; // std::for_each(mpl::begin<acts>::type, mpl::end<acts>::type, doThis<????>); return 0; }; How do I complete this? (I don't know if I should be using std::for_each, just a guess based on another answer here)
Use mpl::for_each for runtime iteration over type lists. E.g.: struct do_this_wrapper { template<typename U> void operator()(U) { doThis<U>(); } }; int main() { typedef boost::mpl::list<RunAround, HopUpAndDown, Sleep> acts; boost::mpl::for_each<acts>(do_this_wrapper()); };
2,840,830
2,840,842
How to call a templated operator overload without using the word 'operator'?
class RunAround; class HopUpAndDown; class Sleep; template<typename Acts> int doThis(); template<> int doThis<RunAround>() { /* run run run.. */ return 3; } template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; } template<> int doThis<Sleep>() { /* zzz.. */ return -2; } struct Results { template<typename Act> int& operator()() { static int result; return result; } }; int main() { Results results; //results<RunAround>() = doThis<RunAround>(); results.operator ()<RunAround>() = doThis<RunAround>(); results.operator ()<Sleep>() = doThis<Sleep>(); return 0; }; If I remove the comment, the compiler thinks I am calling operator() in non-existant template class Results<RunAround> when I want operator<RunAround>() in class Results. If I want to continue using an operator overload instead of a normal name, am I doomed to use the awful syntax below the comment (which does work)?
The most comfortable thing is to let template argument deduction work for you: struct Results { template<typename Act> int& operator()(Act) { /* ... */ } }; results(RunAround()) = /* ... */;
2,840,835
2,840,917
Way to get unsigned char into a std::string without reinterpret_cast?
I have an unsigned char array that I need in a std::string, but my current way uses reinterpret_cast which I would like to avoid. Is there a cleaner way to do this? unsigned char my_txt[] = { 0x52, 0x5f, 0x73, 0x68, 0x7e, 0x29, 0x33, 0x74, 0x74, 0x73, 0x72, 0x55 } unsigned int my_txt_len = 12; std::string my_std_string(reinterpret_cast<const char *>(my_txt), my_txt_len);
Use the iterator constructor: std::string my_std_string(my_txt, my_txt + my_txt_len); This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done. In your example, though, it doesn't make any difference, because all of the values in your array are within the range 0 to CHAR_MAX. So it's guaranteed that those values are represented the same way in char as they are in unsigned char, and hence that reinterpreting them is the same as converting them. If you had values greater then CHAR_MAX then implementations are allowed to treat them differently.
2,840,848
2,840,858
Are tr1 headers available for gcc v3.4.6?
Are tr1 headers available for g++ v3.4.6? If so, how can I locate them at compile time. The following is failing to compile: #include <tr1/memory> With the following error: myModule.h:20:24: tr1/memory: No such file or directory Do I need to move to a later compiler or do I have the headers somewhere?
As an alternative, Boost provides a TR1 implementation too.
2,840,878
2,916,467
"Ambiguous template specialization" problem
I'm currently porting a heap of code that has previously only been compiled with Visual Studio 2008. In this code, there's an arrangement like this: template <typename T> T convert( const char * s ) { // slow catch-all std::istringstream is( s ); T ret; is >> ret; return ret; } template <typename T, typename T2> T convert( T2 * s ) { return convert<T>( static_cast<const char*>( s )); } template <typename T, typename T2> T convert( T2 s ) { return T( s ); } template <> inline int convert<int>( const char * s ) { return (int)atoi( s ); } Generally, there are a lot of specializations of the templated function with different return types that are invoked like this: int i = convert<int>( szInt ); The problem is, that these template specializations result in "Ambiguous template specialization". If it was something besides the return type that differentiated these function specializations, I could obviously just use overloads, but that's not an option. How do I solve this without having to change all the places the convert functions are called? Update I added these two catch-all template specializations that I omitted the first time around. I am embarassed to say, I am unsure about the motivation for the second one, but the first one is due to the convert function being used a lot of places where string data is passed as a void *. I am unable to check it with GCC right now, but I suspect that these might be the problem. Update 2 Here's the complete cpp file that will reproduce this. If you remove both of the "general purpose" functions, it will compile. If you let either of them stay, the ambiguous template specialization error will result. #include <iostream> #include <sstream> template <typename T> T convert( const char * s ) { // this is a slow slow general purpose catch all, if no specialization is provided std::istringstream is( s ); T ret; is >> ret; return ret; } // general purpose 1 template <typename T, typename T2> T convert( T2 * s ) { return convert<T>( static_cast<const char*>( s )); } // general purpose 2 template <typename T, typename T2> T convert( T2 s ) { return T( s ); } // Type specialized template <> inline float convert<float>( const char * s ) { return (float)atof( s ); } int main( int argc, const char * sz[] ) { return 0; }
Apparently return convert<T>( static_cast<const char*>( s )); (or something else I can't see) is inducing the compiler to create a template instantiation of T convert( const char * s ) for T=float. Then when you try to specialize it later, it fails because the template version already exists. When I moved the inline float convert<float>( const char * s ) before the general purpose converters (immediately after the const char* template function), I was able to compile successfully with g++ 4.2.
2,840,908
2,841,014
Linker, Libraries & Directories Information
I've finished both my C++ 1/2 classes and we did not cover anything on Linking to libraries or adding additional libraries to C++ code. I've been having a hay-day trying to figure this out; I've been unable to find basic information linking to objects. Initially I thought the problem was the IDE (Netbeans; and Code::Blocks). However I've been unable to get wxWidgets and GTKMM setup. Can someone point me in the right direction on the terminology and basic information about #including files and linking files in a Cpp application? Basically I want/need to know everything in regards to this process. The difference between .dll, .lib, .o, .lib.a, .dll.a. The difference between a .h and a "library" (.dll, .lib correct?) I understand I need to read the compiler documentation I am using; however all compilers (that I know of) use linker and headers; I need to learn this information. Please point me in the right direction! :] So far on my quest I've found out: Linker links libraries already compiled to your project. .a files are static libraries (.lib in windows) .dll in windows is a shared library (.so in *nix)
On a Unix-like system, you usually find libraries in /usr/lib. The .a extension indicates that you are dealing with an archive file created for example with ar. They are created from object files with the extension .o. The linker can then resolve references at compile time. They are called static libraries, because the machine code from the object file is copied into the final executable. If you for example consider the math library, you will find the library itself at /usr/bin/libm.a and the corresponding header file in your include directory (e.g.:/usr/include/math.h). You have to include the header math.h for the compiler and for the linker specify the library libm.a to resolve the references, which where left by the compiler. Shared libraries use the extension .so. They are useful if you want to have a small executable file. Here, the references are not resolved by the linker, but when the executable is started, the loader will look for the library dynamically and load them according to the unresolved references into memory. .dll are dynamically linked libraries for Microsoft Windows and I am not very familiar with them, but I assume, that the steps involved are similar.
2,840,940
2,841,161
Is it secure to use malloc?
Somebody told me that allocating with malloc is not secure anymore, I'm not a C/C++ guru but I've made some stuff with malloc and C/C++. Does anyone know about what risks I'm into? Quoting him: [..] But indeed the weak point of C/C++ it is the security, and the Achilles' heel is indeed malloc and the abuse of pointers. C/C++ it is a well known insecure language. [..] There would be few apps in what I would not recommend to continue programming with C++."
[...] C/C++ it is a well known insecure language. [...] Actually, that's wrong. Actually, "C/C++" doesn't even exist. There's C, and there's C++. They share some (or, if you want, a lot of) syntax, but they are indeed very different languages. One thing they differ in vastly is their way to manage dynamic memory. The C way is indeed using malloc()/free() and if you need dynamic memory there's very little else you can do but use them (or a few siblings of malloc()). The C++ way is to not to (manually) deal with dynamic resources (of which memory is but one) at all. Resource management is handed to a few well-implemented and -tested classes, preferably from the standard library, and then done automatically. For example, instead of manually dealing with zero-terminated character buffers, there's std::string, instead of manually dealing with dynamically allocated arrays, there std:vector, instead of manually dealing with open files, there's the std::fstream family of streams etc.
2,841,114
2,841,127
Is there a concurrent container library for C++
Possible Duplicate: Is there a production ready lock-free queue or hash implementation in C++ I'm looking for implementations of lock-free containers: Queue Stack Hash Map etc... How about blocking containers: Blocking Queue Blocking Stack Are there any good libraries out there? I would like to refrain from writing these data structures... I would much rather use something that has been tested by the community.
Have a look at the container classes of Intel TBB. The reference says: The container classes permit multiple threads to simultaneously invoke certain methods on the same container.
2,841,204
2,841,222
Use the keyword class as a variable name in C++
I am having trouble writing C++ code that uses a header file designed for a C file. In particular, the header file used a variable name called class: int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs); This works in C as class isn't taken as a keyword, but in C++, class is. So is there anyway I can #include this header file into a c++ file, or am I out of luck? Thank you.
try something like this: #define class class_variable // if class is only used in declarations, you can also do // #define class #include "c.h" #undef class it may cause problems, but maybe worth a shot alternative (using Makefile): python_.hpp: /usr/include/python.h perl -pe 's/\Wclass\W//g' $< > $@ ... #include "python_.hpp"
2,841,332
2,859,126
C++ (g++) Compile Error, Expected "="/etc. Before 'MyWindow" (my class name)
I have a very strange problem and the following code wont compile: #ifndef MYWINDOW_HPP_INCLUDED #define MYWINDOW_HPP_INCLUDED class MyWindow{ private: WNDCLASSEX window_class; HWND window_handle; HDC device_context_handle; HGLRC open_gl_render_context; MSG message; BOOL quit; public: Window(int height=416, int width=544, WindowStyle window_style=WINDOWED); void Show(); void Close(); ~Window(); }; #endif // MYWINDOW_HPP_INCLUDED I get the following error: error: expected '=', ',', ';', 'asm' or 'attribute' before 'MyWindow' I can't see any syntax errors here, although I coukd be wrong as I am very (very) new in c++. Thanks in advance, ell. EDIT: Yeah, I tried renaming my class to MyWindow from Window to solve the problem but it didn't work, I forgot to rename the constructor. I have updated the code now but that still hasn't solved the problem. Here is the only other code I have in my project, I linked it because adding al those spaces would take a while: here's the code
Ahh, silly me, I had main saved as a .c file instead of .cpp, resulting in Code::Blocks trying to compile it as in c instead of c++, thanks for your help guys!
2,841,353
2,842,200
Example applications and benefits of using C , C++ or Java
Ok, I'm revising for my upcoming year 2 exams on a CS course and its likely something like this will come up. my question is what is an ideal application that would especially benefit from the program features of each of the three languages? I have a vague idea but getting a second opinion could really help. JavaPortability, easy - good for GUIs. C++Fast but may requite significant changes in order to be moved from system to system, good for image processing. CI'm unsure here small embedded applications? Some clarification on this would be really appreciated, thanks again StackOverflow
C: device drivers and other low level things C++: applications where you don't want to annoy the user by having to install a runtime environment C/C++: realtime applications; or in cases where the programs runtime is extremely short (the C/C++ program terminates before the jvm startup is done); in cases where memory footprint has to be small Java: in nearly all other cases (provided no better suited domain specific language exists); mobile applications; web (especially on the server) performance of java is IMHO no more an issue. It is at least comparable to C++, and in many cases it's even superior to that of C++ - we reimplemented a large number crunching application in java and it runs an order of magnitude faster than the old one implemented in C++. Surprising? Well, I think the main reason is better tooling support, faster turn-around cycles and less time spent for plugging existing libraries together: Using Java, we have more time to concentrate on algorithms. Plus, some things that can slow down C++ applications simply are not an issue with jave (like temporary object creation). concerning GUI development, I think swing has come a long way and SWT is native, so here java is an option, too. Standard C++ should be portable at the source level in theory, but in practice it's not. Not just threads, but also networking, file system access (i.e. no standard function to tell a files' size), etc. And even incompatibility on one platform is an issue - we have std::string, but how many libraries still exist using their own string classes? If I build my GUI with one library and want to store data in a databse, I'll sure have to convert first. Another example: If I want to use regular expressions, should I go for boost::regex or the GNU library?
2,841,422
2,843,516
Problem linking SDL_Image against libpng
I'm trying to compile SDL_Image 1.2.10 with MinGW + MSys (gcc 4.5.0) on Windows, I have compiled all the requires libs (zlib 1.2.5, libpng 1.4.2, libjpeg 8a, libtiff 3.9.2). SDL_Image compiles fine, but fails to link to libpng, throwing .libs/IMG_png.o:IMG_png.c:(.text+0x16): undefined reference errors on various png structs. If I run ./configure --prefix=/mingw --disable-png for SDL_Image, it compiles and links against the other libs just fine. I have tried older versions of libpng (1.2.43), but they also caused SDL_Image to throw the same errors.
Downgrading my GCC suite to 4.4.0 fixed the problem, it seems 4.5.0 still has a few teething issues. Unless someone comes up with a better answer as to why I can't link properly with GCC 4.5.0 I shall mark my own answer as correct.
2,841,563
2,841,681
testing directory S_ISDIR acts inconsistently
I'm doing simple tests on all files in directory. But from some reason, sometimes, they behave wrongly? What's bad with my code? using namespace std; int main() { string s = "/home/"; struct dirent *file; DIR *dir = opendir(s.c_str()); while ((file = readdir(dir)) != NULL){ struct stat * file_info = new (struct stat); stat(file->d_name,file_info); if ((file_info->st_mode & S_IFMT) == S_IFDIR) cout << "dir" << endl; else cout << "other" << endl; } closedir(dir); }
You made some mistakes, the most important being to call stat() without checking its return value. I modified your program to this: #include <cstdio> #include <dirent.h> #include <iostream> #include <string> #include <sys/stat.h> using namespace std; int main() { string s = "/home/"; struct dirent *file; DIR *dir = opendir(s.c_str()); while ((file = readdir(dir)) != NULL) { struct stat file_info; if (stat(file->d_name, &file_info) == -1) { perror("stat"); return 1; } if (S_ISDIR(file_info.st_mode)) cout << "dir " << file->d_name << endl; else cout << "other " << file->d_name << endl; } closedir(dir); } When I ran it, I got this output: $ ./a.exe dir . dir .. stat: No such file or directory Now I saw that stat was called with a filename of roland, which doesn't exist in my current working directory. You have to prefix the filenames with the directory name. Your second bug was to allocate a new struct stat everytime but not freeing the memory after use. By default, C++ doesn't have garbage collection, so your program would run out of memory soon.
2,841,589
2,841,724
What is the proper use of boost::fusion::push_back?
// ... snipped includes for iostream and fusion ... namespace fusion = boost::fusion; class Base { protected: int x; public: Base() : x(0) {} void chug() { x++; cout << "I'm a base.. x is now " << x << endl; } }; class Alpha : public Base { public: void chug() { x += 2; cout << "Hi, I'm an alpha, x is now " << x << endl; } }; class Bravo : public Base { public: void chug() { x += 3; cout << "Hello, I'm a bravo; x is now " << x << endl; } }; struct chug { template<typename T> void operator()(T& t) const { t->chug(); } }; int main() { typedef fusion::vector<Base*, Alpha*, Bravo*, Base*> Stuff; Stuff stuff(new Base, new Alpha, new Bravo, new Base); fusion::for_each(stuff, chug()); // Mutates each element in stuff as expected /* Output: I'm a base.. x is now 1 Hi, I'm an alpha, x is now 2 Hello, I'm a bravo; x is now 3 I'm a base.. x is now 1 */ cout << endl; // If I don't put 'const' in front of Stuff... typedef fusion::result_of::push_back<const Stuff, Alpha*>::type NewStuff; // ... then this complains because it wants stuff to be const: NewStuff newStuff = fusion::push_back(stuff, new Alpha); // ... But since stuff is now const, I can no longer mutate its elements :( fusion::for_each(newStuff, chug()); return 0; }; How do I get for_each(newStuff, chug()) to work? (Note: I'm only assuming from the overly brief documentation on boost::fusion that I am supposed to create a new vector every time I call push_back.)
(Note: I'm only assuming from the overly brief documentation on boost::fusion that I am supposed to create a new vector every time I call push_back.) You're not creating a new vector. push_back returns a lazily evaluated view on the extended sequence. If you want to create a new vector, then e.g. typedef NewStuff as typedef fusion::vector<Base*, Alpha*, Bravo*, Base*, Alpha*> NewStuff; Your program works then. Btw, fusion is a very functional design. I think it would be more fusion-like if you'd store actual objects rather than pointers and used transform. The chug logic would then be moved out of the classes into the struct chug which had appropriate operator()'s for each type. No new vectors would have to be created then, you could work with lazily evaluated views.
2,841,619
2,841,824
Function Composition in C++
There are a lot of impressive Boost libraries such as Boost.Lambda or Boost.Phoenix which go a long way towards making C++ into a truly functional language. But is there a straightforward way to create a composite function from any 2 or more arbitrary functions or functors? If I have: int f(int x) and int g(int x), I want to do something like f . g which would statically generate a new function object equivalent to f(g(x)). This seems to be possible through various techniques, such as those discussed here. Certainly, you can chain calls to boost::lambda::bind to create a composite functor. But is there anything in Boost which easily allows you to take any 2 or more functions or function objects and combine them to create a single composite functor, similar to how you would do it in a language like Haskell?
I don't know of anything that supports the syntax you wish for currently. However, it would be a simple matter to create one. Simply override * for functors (boost::function<> for example) so that it returns a composite functor. template < typename R1, typename R2, typename T1, typename T2 > boost::function<R1(T2)> operator * (boost::function<R1(T2)> const& f, boost::function<R2(T2)> const& g) { return boost::bind(f, boost::bind(g, _1)); } Untested, but I suspect it's close if it doesn't work out of the box.
2,841,647
2,841,668
What C++ templates issue is going on with this error?
Running gcc v3.4.6 on the Botan v1.8.8 I get the following compile time error building my application after successfully building Botan and running its self test: ../../src/Botan-1.8.8/build/include/botan/secmem.h: In member function `Botan::MemoryVector<T>& Botan::MemoryVector<T>::operator=(const Botan::MemoryRegion<T>&)': ../../src/Botan-1.8.8/build/include/botan/secmem.h:310: error: missing template arguments before '(' token What is this compiler error telling me? Here is a snippet of secmem.h that includes line 310: [...] /** * This class represents variable length buffers that do not * make use of memory locking. */ template<typename T> class MemoryVector : public MemoryRegion<T> { public: /** * Copy the contents of another buffer into this buffer. * @param in the buffer to copy the contents from * @return a reference to *this */ MemoryVector<T>& operator=(const MemoryRegion<T>& in) { if(this != &in) set(in); return (*this); } // This is line 310! [...]
Change it to this: { if(this != &in) this->set(in); return (*this); } I suspect that the set function is defined in the base-class? Unqualified names are not looked up in a base class that depends on a template parameter. So in this case, the name set is probably associated with the std::set template which requires template arguments. If you qualify the name with this->, the compiler is explicitly told to look into the scope of the class, and includes dependent base classes in that lookup.
2,841,716
2,841,739
Using preprocessor directives to define command line options
If I wanted to add, let's say, a new .lib to the build only if a particular #define was set, how would I do that? In the MSVC++ 2008 "Property Pages", you would simply add: Config Properties -> Linker -> Input -> Additional Dependencies, but I would like it if something like #define COMPILE_WITH_DETOURS was set, then the particular library would be added to the dependencies, otherwise it would be removed.
You can set some linker options by using #pragma comment in one of your source files. For example, to link against a 'detours.lib' library only if COMPILE_WITH_DETOURS is defined, you can use: #ifdef COMPILE_WITH_DETOURS # pragma comment(lib, "detours.lib") #endif (this is specific to Microsoft Visual C++ and is not portable)
2,841,752
2,841,774
Accessing methods of an object put inside a class
A class A possesses an instance c of a class C. Another class B has to modify c through C::setBlah(); method. Is it bad to create an accessor C getC(); in A and then use A.getC().setBlah() ? Or should I create a method A::setBlah(); that would call C::setBlah(); ? Isn't it annoying if there are several methods like that ?
As with most "is it bad to do X?" questions, the answer is that it depends entirely on a given situation. Sometimes it might be a really bad idea to have a getC() sort of function because it breaks encapsulation. Other times it might be completely fine because encapsulation of that detail might be irrelevant, and writing a lot of wrapper functions increases the amount of code that you have to write. Pick whichever makes the most sense for the given situation. In code that I've written, I've taken both approaches. If you do go the getC() route, do make sure you return a reference; otherwise you'll be modifying a copy which doesn't sound like what you want. Or, you might consider making A::c public so that you don't need a function at all. A third option to consider would be inheritance from C, which removes the need for getC() or wrapper functions in A.
2,841,757
2,841,764
C++ Template: 'is not derived from type'
Why is this code not valid? #include <vector> template <typename T> class A { public: A() { v.clear(); } std::vector<A<T> *>::const_iterator begin() { return v.begin(); } private: std::vector<A<T> *> v; }; GCC reports the following errors: test.cpp:8: error: type 'std::vector<A<T>*, std::allocator<A<T>*> >' is not derived from type 'A<T>' test.cpp:8: error: expected ';' before 'begin' test.cpp:12: error: expected `;' before 'private' What is wrong? How to fix it?
In this line, you are missing the typename keyword: std::vector<A<T> *>::const_iterator begin(){ You need: typename std::vector<A<T> *>::const_iterator begin(){ This because std::vector<A<T> *> is dependent on the template parameter (T) of the class template (A). To enable correct parsing of the template without having to make any assumptions about possible specializations of any other templates, the language rules require you to indicate which dependent names denote types by using the typename keyword.
2,841,849
2,841,886
Using preprocessor directives to define the output path
Using the following pseudo-code: #define BUILD_PATH "C:/MyBuild/" #define BUILD_NAME "mydll.dll" // Set build path here representing how I would like to build the current project (a dll) into C:/MyBuild/mydll.dll, how would I accomplish this by only using preprocessor directives?
I may be misunderstanding, but I really cannot understand WHY you want to do this but it is doable: #pragma comment( linker, "/out:c:\mydll.dll" ) I cannot re-iterate enough exactly how much you don't want to be doing this though ... If you want to GET the output path via pre-processor info then, I'm afraid ... you can't. That info comes from several steps after the pre-processor so there is no way the pre-processor could get that info.
2,841,941
2,841,957
Constant template parameter class manages to link externally
I have a class foo with an enum template parameter and for some reason it links to two versions of the ctor in the cpp file. enum Enum { bar, baz }; template <Enum version = bar> class foo { public: foo(); }; // CPP File #include "foo.hpp" foo<bar>::foo() { cout << "bar"; } foo<baz>::foo() { cout << "baz"; } I'm using msvc 2008, is this the standard behavior? Are only type template parameters cannot be linked to cpp files?
You are specializing both forms of the contstructor. Why are you surprised it links both forms in?
2,842,005
2,842,096
Objective-C/C++ - Linker error/Method Signature issue
There is a static class Pipe, defined in C++ header that I'm including. The static method I'm interested in calling (from Objective-c) is here: static ERC SendUserGet(const UserId &_idUser,const GUID &_idStyle,const ZoneId &_idZone,const char *_pszMsg); I have access to an objective-c data structure that appears to store a copy of userID, and zoneID -- it looks like: @interface DataBlock : NSObject { GUID userID; GUID zoneID; } Looked up the GUID def, and it's a struct with a bunch of overloaded operators for equality. UserId and ZoneId from the first function signature are #typedef GUID Now when I try to call the method, no matter how I cast it (const UserId), (UserId), etc, I get the following linker error: Ld build/Debug/Seeker.app/Contents/MacOS/Seeker normal i386 cd /Users/josh/Development/project/Mac/Seeker setenv MACOSX_DEPLOYMENT_TARGET 10.5 /Developer/usr/bin/g++-4.2 -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk -L/Users/josh/Development/TS/Mac/Seeker/build/Debug -L/Users/josh/Development/TS/Mac/Seeker/../../../debug -L/Developer/Platforms/iPhoneOS.platform/Developer/usr/lib/gcc/i686-apple-darwin10/4.2.1 -F/Users/josh/Development/TS/Mac/Seeker/build/Debug -filelist /Users/josh/Development/TS/Mac/Seeker/build/Seeker.build/Debug/Seeker.build/Objects-normal/i386/Seeker.LinkFileList -mmacosx-version-min=10.5 -framework Cocoa -framework WebKit -lSAPI -lSPL -o /Users/josh/Development/TS/Mac/Seeker/build/Debug/Seeker.app/Contents/MacOS/Seeker Undefined symbols: "SocPipe::SendUserGet(_GUID const&, _GUID const&, _GUID const&, char const*)", referenced from: -[PeoplePaneController clickGet:] in PeoplePaneController.o ld: symbol(s) not found collect2: ld returned 1 exit status Is this a type/function signature error, or truly some sort of linker error? I have the headers where all these types and static classes are defined #imported -- I tried #include too, just in case, since I'm already stumbling :P Forgive me, I come from a web tech background, so this c-style memory management and immutability stuff is super hazy. Edit: Added full linker error text. Changed "function" to "method". Also I'll note that we're using a custom makefile to compile a few projects external to this one. SocPipe static methods are referenced elsewhere, though, in this xcode project and seems to compile fine.
(Eh, let's turn that comment into an answer.) The method signature looks fine; that is, what you're calling matches what is declared in the header. If it was not, you would probably be getting a compilation error rather than a linker error. The linker's problem is that it doesn't have any corresponding object code to connect this call to: the method is declared but never defined. The latter should occur either in a C++ source file which your project can compile, or else in some precompiled library or framework that you can link to. Either way, that file needs to be included in your project so that it can be made available to the linker.
2,842,012
2,842,042
Template type deduction with a non-copyable class
Suppose I have an autolocker class which looks something like this: template <T> class autolocker { public: autolocker(T *l) : lock(l) { lock->lock(); } ~autolocker() { lock->unlock(); } private: autolocker(const autolocker&); autolocker& operator=(const autolocker&); private: T *lock; }; Obviously the goal is to be able to use this autolocker with anything that has a lock/unlock method without resorting to virtual functions. Currently, it's simple enough to use like this: autolocker<some_lock_t> lock(&my_lock); // my_lock is of type "some_lock_t" but it is illegal to do: autolocker lock(&my_lock); // this would be ideal Is there anyway to get template type deduction to play nice with this (keep in my autolocker is non-copyable). Or is it just easiest to just specify the type?
Yes you can use the scope-guard technique struct autolocker_base { autolocker_base() { } protected: // ensure users can't copy-as it autolocker_base(autolocker_base const&) { } autolocker_base &operator=(autolocker_base const&) { return *this; } }; template <T> class autolocker : public autolocker_base { public: autolocker(T *l) : lock(l) { lock->lock(); } autolocker(const autolocker& o) :autolocker_base(o), lock(o.lock) { o.lock = 0; } ~autolocker() { if(lock) lock->unlock(); } private: autolocker& operator=(const autolocker&); private: mutable T *lock; }; Then write a function creating the autolocker template<typename T> autolocker<T> makelocker(T *l) { return autolocker<T>(l); } typedef autolocker_base const& autolocker_t; You can then write it like this: autolocker_t lock = makelocker(&my_lock); Once the const reference goes out of scope, the destructor is called. It doesn't need to be virtual. At least GCC optimizes this quite well. Sadly, this means you have to make your locker-object copyable since you need to return it from the maker function. But the old object won't try to unlock twice, because its pointer is set to 0 when it's copied, so it's safe.
2,842,048
2,844,913
How to use boost::fusion::transform on heterogeneous containers?
Boost.org's example given for fusion::transform is as follows: struct triple { typedef int result_type; int operator()(int t) const { return t * 3; }; }; // ... assert(transform(make_vector(1,2,3), triple()) == make_vector(3,6,9)); Yet I'm not "getting it." The vector in their example contains elements all of the same type, but a major point of using fusion is containers of heterogeneous types. What if they had used make_vector(1, 'a', "howdy") instead? int operator()(int t) would need to become template<typename T> T& operator()(T& const t) But how would I write the result_type? template<typename T> typedef T& result_type certainly isn't valid syntax, and it wouldn't make sense even if it was, because it's not tied to the function.
Usually, fusion::transform is used with a templated (or -as shown above- otherwise overloaded) function operator: struct triple { template <typename Sig> struct result; template <typename This, typename T> struct result<This(T)> { typedef /*...figure out return type...*/ type; }; template <typename T> typename result<triple(T)>::type operator()(T t) const { return 3*t; // relies on existing operator*() for 'T' } }; And, additional sources of information about Fusion are the examples and the test directory where you can find demonstrations of some of the techniques. Regards Hartmut
2,842,215
2,866,713
Where can I find boost::fusion articles, examples, guides, tutorials?
I am going to go ahead and shamelessly duplicate this question because the accepted answer is essentially "nope, no guides" and it's been nearly a year now since it's been asked. Does anyone know of any useful articles, guides, tutorials, etc. for boost::fusion besides the barebones documentation on boost.org? (which I'm sure is great as a reference after one has learned the library.) I'm completely open to, say, a link to a book on Amazon. Searched for it myself just now but all I came up with was green tea. The top links on Google aren't much better.
Ugh. Still no bites... I did find some helpful examples in the <boostdir>/libs/fusion/test area though.
2,842,319
2,843,324
SwapBuffers causes redraw
I'm making a Win32 application with OpenGL in the main window (not using GLUT). I have my drawing code in WM_PAINT right now when I call swapBuffers it must be invalidating itself because it is constantly rerendering and using lots of cpu resources. How can I make it only render when it honestly receives WM_PAINT like when using GDI? Thanks
WM_PAINT messages keep on being sent until Windows has validated the dirty region of the window. The API that resets the dirty region is 'EndPaint'. Calling SwapBuffers should not effect the invalid window region at all. Your WM_PAINT handler should be something like the following: case WM_PAINT: HDC hdc; PAINTSTRUCT ps; hdc = BeginPaint(hwnd,&ps); wglMakeCurrent(hdc,scene.m_oglContext); scene.Render(); // wglSwapBuffers(hdc); wglMakeCurrent(hdc,0); EndPaint(hwnd,&ps); return 0; Lots of sample code for Open GL programming has a single HDC and OpenGL context setup at application start. While it makes sample code simpler, it does mean that the code cannot correctly deal with multiple OpenGL contexts. This WM_PAINT handler assumes that the OpenGL context is created for a scene, and then made current as necessary. The side effect of swapping the OpenGL context as necessary is that, the hdc retrieved from BeginPaint is used as the render (and SwapBuffer) target, which means the OpenGL application will now paint synchronously if and when other windows are dragged over the App's window.
2,842,387
2,891,962
Where do I put the logic of my MFC program?
I created an application core, in C++, that I've compiled into a static library in Visual Studio. I am now at the process of writing a GUI for it. I am using MFC to do this. I figured out how to map button presses to execute certain methods of my application core's main class (i.e. buttons to have it start and stop). The core class however, should always be sampling data from an external source every second or two. The GUI should then populate some fields after each sample is taken. I can't seem to find a spot in my MFC objects like CDialog that I can constantly check to see if my class has grabbed the data.. then if it has put that data into some of the text boxes. A friend suggested that I create a thread on the OnInit() routine that would take care of this, but that solution isn't really working for me. Is there no spot where I can put an if statement that keeps being called until the program quits? i.e. if( coreapp.dataSampleReady() ) { // put coreapp.dataItem1() in TextBox1 // set progress bar to coreapp.dataItem2() // etc. // reset dataSampleReady }
You mentioned "every second or two" while another answer suggested "using an event driven paradigm". How about setting a Timer in the dialog and when the timer fires, sample data from your external source. You indicated you figured out how to map event handlers for buttons, so mapping a handler to the timer should be a natural extension for you.
2,842,471
2,842,520
Is this 2D array initialization a bad idea?
I have something I need a 2D array for, but for better cache performance, I'd rather have it actually be a normal array. Here's the idea I had but I don't know if it's a terrible idea: const int XWIDTH = 10, YWIDTH = 10; int main(){ int * tempInts = new int[XWIDTH * YWIDTH]; int ** ints = new int*[XWIDTH]; for(int i=0; i<XWIDTH; i++){ ints[i] = &tempInts[i*YWIDTH]; } // do things with ints delete[] ints[0]; delete[] ints; return 0; } So the idea is that instead of newing a bunch of arrays (and having them placed in different places in memory), I just point to an array I made all at once. The reason for the delete[] (int*) ints; is because I'm actually doing this in a class and it would save [trivial amounts of] memory to not save the original pointer. Just wondering if there's any reasons this is a horrible idea. Or if there's an easier/better way. The goal is to be able to access the array as ints[x][y] rather than ints[x*YWIDTH+y]. EDIT: A simple benchmark suggests that my way is faster without the optimizer, but gcc may optimize better on the simple way for some reason. http://pastebin.com/YDRuLuXv If you compile with gcc -O0, the best should be stack, then mine, then normal. If you compile with X_MAX set to large value and Y_MAX set to a small value, and use gcc -O3, mine and stack should be really really fast, but the normal one won't be. If you make X_MAX small and Y_MAX big, the normal way should win (even over the stack method for some reason).
The problem with that kind of approach is that it is error prone. I would tell yout to wrap the allocation and access to individual elements os your 2D array in a class. class Array2D { private: /* Pointer necessary for the choosen implementation */ public: Array2D(unsigned int dim1, unsigned int dim2); ~Array2D() /* Needed, since you will be allocation memory for this class */ double operator()(unsigned int x, unsigned int y); } In that case, if you ever feel the need of changing the allocation, you can only change the methods implementation, keeping the interface intact. The rest of your code would actually use only the operator() and the constructor. It will help you, also, to prevent memory leaking.
2,842,527
2,842,551
Help C++ifying this C style code
Hey I'm used to developing in C and I would like to use C++ in a project. Can anyone give me an example of how I would translate this C-style code into C++ code. I know it should compile in a c++ complier but I'm talking using c++ techniques(I.e. classes, RAII) typedef struct Solution Solution; struct Solution { double x[30]; int itt_found; double value; }; Solution *NewSolution() { Solution *S = (Solution *)malloc(sizeof(Solution)); for (int i=0;<=30;i++) { S->x[i] = 0; } S->itt_found = -1; return S; } void FreeSolution(Solution *S) { if (S != NULL) free(S); } int main() { Solution *S = NewSolution(); S->value = Evaluate(S->x);// Evaluate is another function that returns a double S->itt_found = 0; FreeSolution(S); return EXIT_SUCCESS; } Ideally I would like to be able to so something like this in main, but I'm not sure exactly how to create the class, i've read a lot of stuff but incorporating it all together correctly seems a little hard atm. Solution S(30);//constructor that takes as an argument the size of the double array S.Evaluate();//a method that would run eval on S.x[] and store result in S.value cout << S.value << endl; Ask if you need more info, thanks. Edit: changed eval to Evaluate since i think eval is a reserved word, or at least confusing. In my actual code I have an array of function pointers which i was using to evaluate the X array and store the result in value. I thought including them would just cause unnecessary bulk and obscure my question.
Here's one way to do it: class Solution { public: // This is the constructor for this class. Note that the constructor // must always have the same name as the class. The line following // the ':' is called the initializer list. It initializes the data // members to a known state. Solution(size_t size) : x(size, 0.0), found(false), value(0.0) { // The 'x(size, 0.0)' is a call to a constructor for the // std::vector class. It creates an array of a size equal to // the first argument, and initializes each element to whatever's // supplied in the second argument (0.0 in this case). } int Evaluate() { // x.begin() returns an iterator that points to the first element // in the array. value = eval(x.begin()); found = true; return EXIT_SUCCESS; } // The 'const' means that this function won't change any (non-mutable) // variables in the class. double GetValue() const { return value; } bool FoundValue() const { return found; } // You may add some more functions to allow users to access/manipulate // the array, if needed. // It is a good idea to keep data members private. private: // Use a vector for resizable arrays. std::vector<double> x; bool found; double value; }; int main() { Solution s(30); // The constructor will be called here. s.Evaluate(); cout << S.GetValue() << endl; }
2,842,560
2,842,566
Quick question regarding Conditional Compilation (ifndef)
This is quite probably a very silly question but I need to be sure. I've been given a class declaration in a header file eg. #ifndef file_H #define file_H class ex{ private: public: }; #endif and I've been required to write the method definitions in the same file, which I have done, my question is does the "#endif" stay where it is just after the class declaration or does it go at the end of my file after the class method definitions?.
At the end of the file. The goal of this form of this #ifndef pattern is to prevent a situation where the same declaration or definition appears twice in a compilation unit. This is done because a C file may include several H files, which somewhere up the chain may in turn include the same file. IF you simply ran the preprocessor without these, you would have multiple copies of the H file. This way, you have multiple copies, but the preprocessor ignores everything after the first encounter. Since you're not supposed to be defining anything more than once, if you have to place method definitions in the header file, put them within the #endif.
2,842,687
2,842,692
Typecast cross-platform compatibility
what I'm trying to do is append a binary integer into a string object. So far I have this: int number = 5; cppstring.append((char*)&number, 4); It works fine on a x86 system with Windows, but some people are saying its not cross-platform and is unsafe. What is the preferred method to do this?
The reason it's not portable is that ints are not always 4 bytes. For instance, the ILP64 data model uses 8-bytes ints. C99 only requires that ints are at least 2 bytes. Why do you need to do this, and what is the desired behavior if the size of the int is not 4 bytes?
2,842,728
2,842,786
Can someone explain to me why my output is this? And how would I correct my output?
In this slice of code I get an output of bbb 55 66 77 88 aaa the output I expect and want is bbb 55 66 77 88 bbb because I reassign ss from log[0] to log[1]. So my question is why is the output different from what I expect and how do I change it to what I want? int w,x,y,z; stringstream ss (stringstream::in | stringstream::out); string word; string log[2]; log[0]="aaa 11 22 33 44"; log[1]="bbb 55 66 77 88"; ss<<log[0]; ss>>word; int k=0; ss>>w>>x>>y>>z; k++; ss<<log[k]; cout<<log[k]<<endl; ss>>word; cout<<word<<endl; return 0;
When ss >> w >> x >> y >> z; was executed, there is no content left to operate on and ss.good() returns false, which expresses the need to call ss.clear() in order to assure everything is ok and we can move on. However, given that you do ss.clear(); ss<<log[k]; The content of ss will be aaa 11 22 33 44bbb 55 66 77 88 If you want it this way, fine. But maybe you expected it to contain bbb 55 66 77 88 which is done by ss.str(log[k]); ss.clear();
2,842,837
2,842,846
Pass arguments to a parameter class object
This is undoubtedly a simple question. I used to do this before, but it's been around 10 years since I worked in C++ so I can't remember properly and I can't get a simple constructor call working. The idea is that instead of parsing the args in main, main would create an object specifically designed to parse the arguments and return them as required. So: Parameters params = new Parameters(argc, argv) then I can call things like params.getfile() Only problem is I'm getting a complier error in Visual Studio 2008 and I'm sure this is simple, but I think my mind is just too rusty. What I've got so far is really basic: In the main: #include "stdafx.h" #include "Parameters.h" int _tmain(int argc, _TCHAR* argv[]) { Parameters params = new Parameters(argc, argv); return 0; } Then in the Parameters header: #pragma once class Parameters { public: Parameters(int, _TCHAR*[]); ~Parameters(void); }; Finally in the Parameters class: include "Stdafx.h" #include "Parameters.h" Parameters::Parameters(int argc, _TCHAR* argv[]) { } Parameters::~Parameters(void) { } I would appreciate if anyone could see where my ageing mind has missed the really obvious. Thanks in advance.
Use: Parameters params(argc, argv); The new operator is generally used when you want dynamic (heap) allocation. It returns a pointer (Parameter *).
2,842,902
2,842,905
error C3662: override specifier 'new' only allowed on member functions of managed classes
Okay, so I'm trying to override a function in a parent class, and getting some errors. here's a test case #include <iostream> using namespace std; class A{ public: int aba; void printAba(); }; class B: public A{ public: void printAba() new; }; void A::printAba(){ cout << "aba1" << endl; } void B::printAba() new{ cout << "aba2" << endl; } int main(){ A a = B(); a.printAba(); return 0; } And here's the errors I'm getting: Error 1 error C3662: 'B::printAba' : override specifier 'new' only allowed on member functions of managed classes c:\users\test\test\test.cpp 12 test Error 2 error C2723: 'B::printAba' : 'new' storage-class specifier illegal on function definition c:\users\test\test\test.cpp 19 test How the heck do I do this?
There's no need to put any keywords in the derived class to override a function. class B: public A{ public: void printAba(); }; But the base class's method should be virtual, to allow the method be selected depending on the actual identity of the variable. class A{ public: int aba; virtual void printAba(); }; And if you create an B on stack and copy into A, slicing would occur. You should create a B on heap and cast the pointer as A. A* a = new B(); a->printAba(); // if printAba is not virtual, A::printAba will be called. delete a;
2,842,928
2,842,942
Default value of function parameter
1. int Add (int a, int b = 3); int Add (int a, int b) { } 2. int Add (int a, int b); int Add (int a, int b = 3) { } Both work; which is the standard way and why?
If you put the declaration in a header file, and the definition in a separate .cpp file, and #include the header from a different .cpp file, you will be able to see the difference. Specifically, suppose: lib.h int Add(int a, int b); lib.cpp int Add(int a, int b = 3) { ... } test.cpp #include "lib.h" int main() { Add(4); } The compilation of test.cpp will not see the default parameter declaration, and will fail with an error. For this reason, the default parameter definition is usually specified in the function declaration: lib.h int Add(int a, int b = 3);
2,843,030
2,843,067
Seg Fault with malloc'd pointers
I'm making a thread class to use as a wrapper for pthreads. I have a Queue class to use as a queue, but I'm having trouble with it. It seems to allocate and fill the queue struct fine, but when I try to get the data from it, it Seg. faults. http://pastebin.com/Bquqzxt0 (the printf's are for debugging, both throw seg faults) edit: the queue is stored in a dynamically allocated "struct queueset" array as a pointer to the data and an index for the data
C++ provides a built-in queue class for you: #include <queue> struct queueset { void* ptr; int index; queueset(void* p, int i) : ptr(p), index(i) {} }; class pthreadmutexlock { public: pthreadmutexlock() { pthread_mutex_init(&lock, NULL); pthread_mutex_lock(&lock); } ~pthreadmutexlock() { pthread_mutex_unlock(&lock); pthread_mutex_destroy(&lock); } private: pthread_mutex_t lock; }; class ThreadSafeQueue { public: void add(void* msg, int index); queueset get(); bool hasitems() const { return !queue.empty(); } private: std::queue<queueset> queue; pthread_mutex_t lock; }; void ThreadSafeQueue::add(void* msg, int index) { pthreadmutexlock lock; queue.push(queueset(msg, index)); } queueset ThreadSafeQueue::get() { pthreadmutexlock lock; queueset temp = queue.front(); queue.pop(); return temp; } In C++, the best way to avoid memory problems is to minimize the management of memory using raw pointers as much as possible, and use standard classes where applicable.
2,843,167
2,843,270
How would I create this background effect?
What would you call the effect applied to the backgrounds in the Giygas fight of Earthbound, and the battle backgrounds in Mother 3? This is what I'm talking about. http://www.youtube.com/watch?v=tcaErqaoWek http://www.youtube.com/watch?v=ubVnmeTRqhg Now anyone know how I could go about this without using animated images, or using openGL?
These are also called demo effects. They are used on demoscene events, beside games. Check out this effect collection.
2,843,248
2,843,271
Launch C# .Net Application from C++
Is it possible to launch a C#.Net (2.0) application from an application written in C++??? Thanks, EDIT: Cool - so I just have to know where the app is: LPTSTR szCmdline = _tcsdup(TEXT("C:\\Program Files\\MyApp -L -S")); CreateProcess(NULL, szCmdline, /* ... */);
You can launch any EXE using CreatePocess or ShellExecute API. ( including C#.Net)
2,843,357
2,843,361
Window screenshot using WinAPI
How to make a screenshot of program window using WinAPI & C#? I sending WM_PAINT (0x000F) message to window, which I want to screenshot, wParam = HDChandle, but no screenshot in my picturebox. If I send a WM_CLOSE message, all waorking (target window closes). What I do wrong with WM_PAINT? May be HDC is not PictureBox (WinForms) component? P.S. GetLastError() == "" [DllImport("User32.dll")] public static extern Int64 SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); ..... SendMessage(targetWindowHandle, 0x000F, pictureBox.Handle, IntPtr.Zero);
pictureBox.Handle is a window handle, not a DC handle. There are several guides online for doing screenshots. One is here. See also @In silico's answer.
2,843,421
2,843,434
Custom string class (C++)
I'm trying to write my own C++ String class for educational and need purposes. The first thing is that I don't know that much about operators and that's why I want to learn them. I started writing my class but when I run it it blocks the program but does not do any crash. Take a look at the following code please before reading further: class CString { private: char* cstr; public: CString(); CString(char* str); CString(CString& str); ~CString(); operator char*(); operator const char*(); CString operator+(const CString& q)const; CString operator=(const CString& q); }; First of all I'm not so sure I declared everything right. I tried googleing about it but all the tutorials about overloading explain the basic ideea which is very simple but lack to explain how and when each thing is called. For instance in my = operator the program calls CString(CString& str); but I have no ideea why. I have also attached the cpp file below: CString::CString() { cstr=0; } CString::CString(char *str) { cstr=new char[strlen(str)]; strcpy(cstr,str); } CString::CString(CString& q) { if(this==&q) return; cstr = new char[strlen(q.cstr)+1]; strcpy(cstr,q.cstr); } CString::~CString() { if(cstr) delete[] cstr; } CString::operator char*() { return cstr; } CString::operator const char* () { return cstr; } CString CString::operator +(const CString &q) const { CString s; s.cstr = new char[strlen(cstr)+strlen(q.cstr)+1]; strcpy(s.cstr,cstr); strcat(s.cstr,q.cstr); return s; } CString CString::operator =(const CString &q) { if(this!=&q) { if(cstr) delete[] cstr; cstr = new char[strlen(q.cstr)+1]; strcpy(cstr,q.cstr); } return *this; } For testing I used a code just as simple as this CString a = CString("Hello") + CString(" World"); printf(a); I tried debugging it but at a point I get lost. First it calls the constructor 2 times for "hello" and for " world". Then it get's in the + operator which is fine. Then it calls the constructor for the empty string. After that it get's into "CString(CString& str)" and now I'm lost. Why is this happening? After this I noticed my string containing "Hello World" is in the destructor (a few times in a row). Again I'm very puzzeled. After converting again from char* to Cstring and back and forth it stops. It never get's into the = operator but neither does it go further. printf(a) is never reached. I use VisualStudio 2010 for this but it's basically just standard c++ code and thus I don't think it should make that much of a difference
The line: cstr=new char[strlen(str)]; should be: cstr=new char[strlen(str) + 1]; Also, the test for self-assignment does not make sense in the copy constructor - you are creating a new object - it cannot possibly have the same address as any existing object. And the copy constructor should take a const reference as a parameter, If in your code, you were expecting the assignment operator to be used, you would be expectining wrong. This code: CString a = CString("Hello") + CString(" World"); is essentially the same as: CString a( CString("Hello") + CString(" World") ); which is copy construction, not assignment. The temporary CString "Hello world" will be destroyed (invoking the destructor) after a has been constructed. Basically, it sounds as if your code is working more or less as expected.
2,843,478
2,843,490
variables in abstract classes C++
I have an abstract class CommandPath, and a number of derived classes as below: class CommandPath { public: virtual CommandResponse handleCommand(std::string) = 0; virtual CommandResponse execute() = 0; virtual ~CommandPath() {} }; class GetTimeCommandPath : public CommandPath { int stage; public: GetTimeCommandPath() : stage(0) {} CommandResponse handleCommand(std::string); CommandResponse execute(); }; All of the derived classes have the member variable 'stage'. I want to build a function into all of them which manipulates 'stage' in the same way, so rather than defining it many times I thought I'd build it into the parent class. I moved 'stage' from the private sections of all of the derived classes into the protected section of CommandPath, and added the function as follows: class CommandPath { protected: int stage; public: virtual CommandResponse handleCommand(std::string) = 0; virtual CommandResponse execute() = 0; std::string confirmCommand(std::string, int, int, std::string, std::string); virtual ~CommandPath() {} }; class GetTimeCommandPath : public CommandPath { public: GetTimeCommandPath() : stage(0) {} CommandResponse handleCommand(std::string); CommandResponse execute(); }; Now my compiler tells me for the constructor lines that none of the derived classes have a member 'stage'. I was under the impression that protected members are visible to derived classes? The constructor is the same in all classes, so I suppose I could move it to the parent class, but I'm more concerned about finding out why the derived classes aren't able to access the variable. Also, since previously I've only used the parent class for pure virtual functions, I wanted to confirm that this is the way to go about adding a function to be inherited by all derived classes.
Try this: class CommandPath { protected: int stage; public: CommandPath(int stage_) : stage(stage_) {} }; class GetTimeCommandPath : public CommandPath { public: GetTimeCommandPath(int stage_) : CommandPath(stage_) {} }; (Omitted extra code for brevity). You can't use the initializer list on a parent class' members, only the current one's. If that makes sense.
2,843,552
3,009,537
RESTful interface for C++/Qt?
I want to integrate the RESTful-API in my Qt-Project. I already read the example on this page, but this is only for receiving data from a RESTful-interface, not for sending new data to the server. In Java, I can use RESTlet for example, is there any possibility to use something like that for Qt, too? Or is there even a simple way to send data from Qt to RESTful, for example when I create a XML before?
Since REST is just normal URL access, there's no reason you can't use the Qt HttpClient interfaces to talk to you backend Java REST interface. You just have to make a determination to use XML or JSON - both have very capable libraries available, and both are just text interfaces. Odd you ask, I'm in the middle of doing this very thing myself today - I'm implementing a JSON based REST interface in Java, and I'll wire up the plumbing to my Qt app shortly. I'll make an effort to update this answer as I progress.
2,843,703
2,843,727
Pass a pointer to a proc as an argument
I want to pass a pointer to a procedure in c++. I tried passing this LRESULT(*)(HWND, UINT, WPARAM, LPARAM) prc but it didn't work. How is this done? Thanks HWND OGLFRAME::create(HWND parent, LRESULT(*)(HWND, UINT, WPARAM, LPARAM) prc) { if(framehWnd != NULL) { return framehWnd; ZeroMemory(&rwc,sizeof(rwc)); } } By "it didn't work" I mean it's a syntax error. from the compiler: Error 2 error C3646: 'prc' : unknown override specifier c:\users\josh\documents\visual studio 2008\projects\vectorizer project\vectorizer project\oglframe.h 10 Error 5 error C3646: 'prc' : unknown override specifier c:\users\josh\documents\visual studio 2008\projects\vectorizer project\vectorizer project\oglframe.cpp 7 Error 1 error C2146: syntax error : missing ')' before identifier 'prc' c:\users\josh\documents\visual studio 2008\projects\vectorizer project\vectorizer project\oglframe.h 10 Error 4 error C2146: syntax error : missing ')' before identifier 'prc' c:\users\josh\documents\visual studio 2008\projects\vectorizer project\vectorizer project\oglframe.cpp 7 Error 3 error C2059: syntax error : ')' c:\users\josh\documents\visual studio 2008\projects\vectorizer project\vectorizer project\oglframe.h 10 Error 6 error C2059: syntax error : ')' c:\users\josh\documents\visual studio 2008\projects\vectorizer project\vectorizer project\oglframe.cpp 7
HWND OGLFRAME::create(HWND parent, LRESULT(*prc)(HWND, UINT, WPARAM, LPARAM)) You could also just use the WNDPROC type: HWND OGLFRAME::create(HWND parent, WNDPROC prc)
2,843,796
2,844,041
GCC: visibility of symbols in standalone C++ applications
Because of a strange C++ warning about the visibility of some symbols and an interesting answer, linking to a paper which describes the different visibility types and cases (section 2.2.4 is about C++ classes), I started to wonder if it is needed for a standalone application to export symbols at all (except main - or is that needed?). Why exactly are they needed to be exported in standalone applications? Is "an exported symbol" an synomym for "visible symbol"? I.e. a hidden symbol is a symbol which is not exported? Do the object files already differ between visible symbols and hidden symbols? Or is this made at the linking step, so that only the visible symbols are exported? Does the visibility of symbols matter in case for debug information? Or is that completely independent, i.e. I would also get a nice backtrace if I have all symbols hidden? How is STABS/DWARF related to the visibility of symbols?
For applications you do not need this because you do not have API... The visibility is relevant for shared-objects only.
2,843,820
2,843,933
C++ Standard Library Exception List?
Is there a reference about C++ Standard Library Exceptions? I just want to know that which functions may throw an exception or not.
Actually, most of the standard library function don't throw exceptions themselves. They just pass on exception thrown by user code invoked by them. For example, if you push_back() an element to a vector, this can throw (due to memory allocation errors and) if the object's copy constructor throws. A few notable exceptions (no pun intended) where library functions throw are: Some methods will throw out_of_range if the index provided is invalid: std::vector<>::at() std::basic_string<>::at() std::bitset<>::set(), reset() and flip(). Some methods will throw std::overflow_error on integer overflow: std::bitset<>::to_ulong() and (C++0x) to_ullong(). std::allocator<T> will pass on std::bad_alloc thrown by new which it invokes. Streams can be setup so that std::ios_base::failure are thrown when a state bit is set. Large array allocations can throw std::bad_array_new_length dynamic_cast on a reference can throw a std::bad_cast (technically not part of the standard library) Throwing an invalid exception from a function with an exception specification will throw a std::bad_exception Calling a std::function::operator(...) if it has no value will throw std::bad_function_call. Using typeinfo of a null pointer may throw a std::bad_typeid. Accessing a weak_ptr after the pointee has been released will throw a std::bad_weak_ptr. Incorrect usage of std::promise/std::future may throw a std::future_error. (c++11) The string conversion functions std::stoi, std::stol, std::stoll, std::stoul, std::stoull, std::stof, std::stod, and std::stold can throw both std::invalid_argument and std::out_of_range. (c++11) In the regex family, constructors and assign methods can throw std::regex_error. (I'm making this a CW answer, so if anyone can think of more such, please feel free to append them here.) Also, for the 3rd edition of The C++ Programming Language, Bjarne Stroustrup has a downloadable appendix about exception safety, which might be relevant.
2,843,948
2,843,971
map::lower_bound that returns a map
Is there a function that does the same thing as map::lower_bound except it returns a new sub-map and not an iterator? Edit: The function should return a sub-map which contains all the values for which the key is equal to, or greater than a certain value (which is given as input to the function).
Something like this? // Beware, brain-compiled code ahead! template< typename K, typename V > std::map<K,V> equal_or_greater(const std::map<K,V>& original, const K& k) { return std::map<K,V>( original.lower_bound(k), original.end() ); } Edit: It seems you actually want upper_bound() instead of lower_bound().
2,844,082
2,844,120
Scrollbar moves back after WM_VSCROLL
I have a window with its own H and V scrolling. I'm handling the event like this: case WM_VSCROLL: SetScrollPos(hWnd, SB_VERT, (int)HIWORD(wParam), TRUE); break; all I want is for the position of the scroll bar to stay once I release my mouse but what it's doing is just going back to the top after. What am I doing wrong? Thanks
The wParam parameter of the WM_VSCROLL message is either SB_TOP, SB_BOTTOM, SB_PAGEUP, SB_PAGEDOWN, SB_LINEUP, SB_LINEDOWN, SB_THUMBPOSITION, or SB_THUMBTRACK, where the names ought to explain themselves. SB_TOP and SB_BOTTOM means that the scrolling window is to go to the top or bottom, respectively. These messages can be sent by right-clicking a vertical scroll bar and selecting "Top" and "Bottom". (Look in Windows Notepad, Win XP+, for instance.) SB_PAGEUP and SB_PAGEDOWN means a page (screen) up or down. These are sent if you click somwhere on the scrollbar beside on the thumb or the up or down arrows, or if you use the scrollbar's right-click menu. SB_LINEUP and SB_LINEDOWN are sent when the user clicks the up and down buttons on the scrollbar, or selects the appropriate right-click menu commands. SB_THUMBTRACK is sent continuously when the user scrolls by dragging the thumb of the scrollbar. SB_THUMBPOSITION is sent when the user has released the thumb. See the MSDN article WM_VSCROLL for more information. So, when you receive a WM_VSCROLL message, you first need to do the scrolling itself. If, for instance, you are writing a text editor, then you need to redraw the text, but with a different row at the top of the window. Then you need to update the scrollbar to its new position, preferably by means of SetScrollInfo, but you can also use the old SetScrollPos function.
2,844,102
2,844,924
Where is the virtual function call overhead?
I'm trying to benchmark the difference between a function pointer call and a virtual function call. To do this, I have written two pieces of code, that do the same mathematical computation over an array. One variant uses an array of pointers to functions and calls those in a loop. The other variant uses an array of pointers to a base class and calls its virtual function, which is overloaded in the derived classes to do absolutely the same thing as the functions in the first variant. Then I print the time elapsed and use a simple shell script to run the benchmark many times and compute the average run time. Here is the code: #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; long long timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } void function_not( double *d ) { *d = sin(*d); } void function_and( double *d ) { *d = cos(*d); } void function_or( double *d ) { *d = tan(*d); } void function_xor( double *d ) { *d = sqrt(*d); } void ( * const function_table[4] )( double* ) = { &function_not, &function_and, &function_or, &function_xor }; int main(void) { srand(time(0)); void ( * index_array[100000] )( double * ); double array[100000]; for ( long int i = 0; i < 100000; ++i ) { index_array[i] = function_table[ rand() % 4 ]; array[i] = ( double )( rand() / 1000 ); } struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for ( long int i = 0; i < 100000; ++i ) { index_array[i]( &array[i] ); } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); unsigned long long time_elapsed = timespecDiff(&end, &start); cout << time_elapsed / 1000000000.0 << endl; } and here is the virtual function variant: #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; long long timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } class A { public: virtual void calculate( double *i ) = 0; }; class A1 : public A { public: void calculate( double *i ) { *i = sin(*i); } }; class A2 : public A { public: void calculate( double *i ) { *i = cos(*i); } }; class A3 : public A { public: void calculate( double *i ) { *i = tan(*i); } }; class A4 : public A { public: void calculate( double *i ) { *i = sqrt(*i); } }; int main(void) { srand(time(0)); A *base[100000]; double array[100000]; for ( long int i = 0; i < 100000; ++i ) { array[i] = ( double )( rand() / 1000 ); switch ( rand() % 4 ) { case 0: base[i] = new A1(); break; case 1: base[i] = new A2(); break; case 2: base[i] = new A3(); break; case 3: base[i] = new A4(); break; } } struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for ( int i = 0; i < 100000; ++i ) { base[i]->calculate( &array[i] ); } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); unsigned long long time_elapsed = timespecDiff(&end, &start); cout << time_elapsed / 1000000000.0 << endl; } My system is LInux, Fedora 13, gcc 4.4.2. The code is compiled it with g++ -O3. The first one is test1, the second is test2. Now I see this in console: [Ignat@localhost circuit_testing]$ ./test2 && ./test2 0.0153142 0.0153166 Well, more or less, I think. And then, this: [Ignat@localhost circuit_testing]$ ./test2 && ./test2 0.01531 0.0152476 Where are the 25% which should be visible? How can the first executable be even slower than the second one? I'm asking this because I'm doing a project which involves calling a lot of small functions in a row like this in order to compute the values of an array, and the code I've inherited does a very complex manipulation to avoid the virtual function call overhead. Now where is this famous call overhead?
I think you're seeing the difference, but it's just the function call overhead. Branch misprediction, memory access and the trig functions are the same in both cases. Compared to those, it's just not that big a deal, though the function pointer case was definitely a bit quicker when I tried it. If this is representative of your larger program, this is a good demonstration that this type of microoptimization is sometimes just a drop in the ocean, and at worst futile. But leaving that aside, for a clearer test, the functions should perform some simpler operation, that is different for each function: void function_not( double *d ) { *d = 1.0; } void function_and( double *d ) { *d = 2.0; } And so on, and similarly for the virtual functions. (Each function should do something different, so that they don't get elided and all end up with the same address; that would make the branch prediction work unrealistically well.) With these changes, the results are a bit different. Best of 4 runs in each case. (Not very scientific, but the numbers are broadly similar for larger numbers of runs.) All timings are in cycles, running on my laptop. Code was compiled with VC++ (only changed the timing) but gcc implements virtual function calls in the same way so the relative timings should be broadly similar even with different OS/x86 CPU/compiler. Function pointers: 2,052,770 Virtuals: 3,598,039 That difference seems a bit excessive! Sure enough, the two bits of code aren't quite the same in terms of their memory access behaviour. The second one should have a table of 4 A *s, used to fill in base, rather than new'ing up a new one for each entry. Both examples will then have similar behaviour (1 cache miss/N entries) when fetching the pointer to jump through. For example: A *tbl[4] = { new A1, new A2, new A3, new A4 }; for ( long int i = 0; i < 100000; ++i ) { array[i] = ( double )( rand() / 1000 ); base[i] = tbl[ rand() % 4 ]; } With this in place, still using the simplified functions: Virtuals (as suggested here): 2,487,699 So there's 20%, best case. Close enough? So perhaps your colleague was right to at least consider this, but I suspect that in any realistic program the call overhead won't be enough of a bottleneck to be worth jumping through hoops over.
2,844,199
2,844,212
How do C++ header files work?
When I include some function from a header file in a C++ program, does the entire header file code get copied to the final executable or only the machine code for the specific function is generated. For example, if I call std::sort from the <algorithm> header in C++, is the machine code generated only for the sort() function or for the entire <algorithm> header file. I think that a similar question exists somewhere on Stack Overflow, but I have tried my best to find it (I glanced over it once, but lost the link). If you can point me to that, it would be wonderful.
You're mixing two distinct issues here: Header files, handled by the preprocessor Selective linking of code by the C++ linker Header files These are simply copied verbatim by the preprocessor into the place that includes them. All the code of algorithm is copied into the .cpp file when you #include <algorithm>. Selective linking Most modern linkers won't link in functions that aren't getting called in your application. I.e. write a function foo and never call it - its code won't get into the executable. So if you #include <algorithm> and only use sort here's what happens: The preprocessor shoves the whole algorithm file into your source file You call only sort The linked analyzes this and only adds the source of sort (and functions it calls, if any) to the executable. The other algorithms' code isn't getting added That said, C++ templates complicate the matter a bit further. It's a complex issue to explain here, but in a nutshell - templates get expanded by the compiler for all the types that you're actually using. So if have a vector of int and a vector of string, the compiler will generate two copies of the whole code for the vector class in your code. Since you are using it (otherwise the compiler wouldn't generate it), the linker also places it into the executable.
2,844,339
2,844,385
C++ iterator and const_iterator problem for own container class
I'm writing an own container class and have run into a problem I can't get my head around. Here's the bare-bone sample that shows the problem. It consists of a container class and two test classes: one test class using a std:vector which compiles nicely and the second test class which tries to use my own container class in exact the same way but fails miserably to compile. #include <vector> #include <algorithm> #include <iterator> using namespace std; template <typename T> class MyContainer { public: class iterator { public: typedef iterator self_type; inline iterator() { } }; class const_iterator { public: typedef const_iterator self_type; inline const_iterator() { } }; iterator begin() { return iterator(); } const_iterator begin() const { return const_iterator(); } }; // This one compiles ok, using std::vector class TestClassVector { public: void test() { vector<int>::const_iterator I=myc.begin(); } private: vector<int> myc; }; // this one fails to compile. Why? class TestClassMyContainer { public: void test(){ MyContainer<int>::const_iterator I=myc.begin(); } private: MyContainer<int> myc; }; int main(int argc, char ** argv) { return 0; } gcc tells me: test2.C: In member function ‘void TestClassMyContainer::test()’: test2.C:51: error: conversion from ‘MyContainer::iterator’ to non-scalar type ‘MyContainer::const_iterator’ requested I'm not sure where and why the compiler wants to convert an iterator to a const_iterator for my own class but not for the STL vector class. What am I doing wrong?
When you call begin() the compiler by default creates a call to the non-const begin(). Since myc isn't const, it has no way of knowing you mean to use the const begin() rather than the non-const begin(). The STL iterator contains a cast operator which allows an iterator to be silently converted to a const_iterator. If you want this to work you need to add one as well like so: class iterator { public: typedef iterator self_type; inline iterator() { } operator const_iterator() { return const_iterator(); } }; or allow const_iterator to be constructed from an iterator like so: class const_iterator { public: typedef const_iterator self_type; const_iterator(iterator& ) {} inline const_iterator() { } };
2,844,446
2,844,493
Shall I optimize or let compiler to do that?
What is the preferred method of writing loops according to efficiency: Way a) /*here I'm hoping that compiler will optimize this code and won't be calling size every time it iterates through this loop*/ for (unsigned i = firstString.size(); i < anotherString.size(), ++i) { //do something } or maybe should I do it this way: Way b) unsigned first = firstString.size(); unsigned second = anotherString.size(); and now I can write: for (unsigned i = first; i < second, ++i) { //do something } the second way seems to me like worse option for two reasons: scope polluting and verbosity but it has the advantage of being sure that size() will be invoked once for each object. Looking forward to your answers.
I usually write this code as: /* i and size are local to the loop */ for (size_t i = firstString.size(), size = anotherString.size(); i < size; ++i) { // do something } This way I do not pollute the parent scope and avoid calling anotherString.size() for each loop iteration. It is especially useful with iterators: for(some_generic_type<T>::forward_iterator it = container.begin(), end = container.end(); it != end; ++it) { // do something with *it } Since C++ 11 the code can be shortened even more by writing a range-based for loop: for(const auto& item : container) { // do something with item } or for(auto item : container) { // do something with item }
2,844,448
2,844,576
Overinclusion of libraries C++
I'm reading about how to put a makefile together, but no-one seems to mention what to do if your files require different sets of libraries, they all seem to use the same set of libraries for each file. Since it seems unlikely that every single file has the same libraries, I take it the list they use must amalgamate all of the libraries required across the project. I just wanted to know if there's any downside to including too many libraries, or if the compiler works out which ones are needed and ignores the rest? Thanks
If there's any downside to including too many libraries? Hardly any. If the compiler works out which ones are needed and ignores the rest? Almost exactly right: it's the linker that examines each library and pulls only the object code that it needs. The one downside to including a very large number of libraries is that it can be hard to get them in the right order. Recent versions of the GNU linker have some special options that can help with the libraries-out-of-order problem (and it's about time too), but such options remain nonportable. On the other hand, if you include libraries that aren't actually needed, it's not going to matter what order they appear in, because the linker will carefully examine each one and decide that none of its contents are needed. For all those people out there who are looking for projects, here's one I'd love to have: give me a tool that takes a list of libraries and does a topological sort on the interlibrary dependencies, then tells me an order I can put them on the command line so that there are no gratuitously undefined symbols.
2,844,466
2,844,572
Can 'iterator' type just subclass 'const_iterator'?
After another question about iterators I'm having some doubts about custom containers. In my container, iterator is a subclass of const_iterator, so that I get conversion from non-const to const "for free". But is this allowed or are there any drawbacks or non-working scenarios for such a setup?
Yes, this is fine. This is how VC10's implementation of the iterators for vector are structured, for example. See _Vector_iterator and _Vector_const_iterator in <vector>. By the way, writing iterators is hard. It's worth your time to learn and use the boost::iterator library.
2,844,607
2,844,618
What C++0x feature will have the most impact?
What will day to day C++ development be like in a few years? What C++0x features will change C++ development the most? In what order should I concentrate learning these new features?
Lambdas, because they finally introduce reasonable means of harnessing the benefits of functional programming.
2,844,623
3,756,666
SFML Plasma Sprite Effect?
Is there a way to create a plasma effect in SFML that doesn't slow my framerate to a crawl?
1) Manipulate the image bits directly in memory as a byte (or int/whatever depending on your target colour depth) array. Don't use anything which GetsPixel() from an image each time. 2) Minimise your maths. For plasma effects you'll usually be using a lot of trig functions which are fairly slow when you're doing them (heightwidthframerate) times per second. Either use a fast dedicated maths library for your calucations or, better yet, cache the calculations at the start and use a look-up table during the effect to cut the math out of each frame entirely. 3) One of the things which made old-school plasma effects run so fast was palette cycling. I'm not aware of any way to replicate this (or palettes in general) with SFML directly but you can use GLSL shaders to get the same kind of result without a big performance hit. Something like this: float4 PS_ColorShift(float2 Tex : TEXCOORD0) : COLOR0 { float4 color = tex2D(colorMap, Tex); color.r = color.r+sin(colorshift_timer+0.01f); color.g = color.g+sin(colorshift_timer+0.02f); color.b = color.b+sin(colorshift_timer+0.03f); color.a = 1.0f; saturate(color); return color; }
2,844,676
2,845,242
typedef and operator overloading in C++
Suppose I typedef an integer or integer array or any known type: typedef int int2 Then I overload operator * for int2 pairs, now if I initialize variables a and b as int. Then will my * between a and b be the overloaded * ? How do I achieve overloading an int and yet also use * for int the way they are. Should I create a new type?
What you need is a Strong Typedef. Boost offered version that should work for you, or at least help you resolve your need : http://www.boost.org/doc/libs/1_42_0/boost/strong_typedef.hpp
2,844,817
2,845,275
How do I check if a C++ string is an int?
When I use getline, I would input a bunch of strings or numbers, but I only want the while loop to output the "word" if it is not a number. So is there any way to check if "word" is a number or not? I know I could use atoi() for C-strings but how about for strings of the string class? int main () { stringstream ss (stringstream::in | stringstream::out); string word; string str; getline(cin,str); ss<<str; while(ss>>word) { //if( ) cout<<word<<endl; } }
Another version... Use strtol, wrapping it inside a simple function to hide its complexity : inline bool isInteger(const std::string & s) { if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false; char * p; strtol(s.c_str(), &p, 10); return (*p == 0); } Why strtol ? As far as I love C++, sometimes the C API is the best answer as far as I am concerned: using exceptions is overkill for a test that is authorized to fail the temporary stream object creation by the lexical cast is overkill and over-inefficient when the C standard library has a little known dedicated function that does the job. How does it work ? strtol seems quite raw at first glance, so an explanation will make the code simpler to read : strtol will parse the string, stopping at the first character that cannot be considered part of an integer. If you provide p (as I did above), it sets p right at this first non-integer character. My reasoning is that if p is not set to the end of the string (the 0 character), then there is a non-integer character in the string s, meaning s is not a correct integer. The first tests are there to eliminate corner cases (leading spaces, empty string, etc.). This function should be, of course, customized to your needs (are leading spaces an error? etc.). Sources : See the description of strtol at: http://en.cppreference.com/w/cpp/string/byte/strtol. See, too, the description of strtol's sister functions (strtod, strtoul, etc.).
2,844,947
2,845,001
Solve equation from string to result in C
I would like to know if anyone has info or experience on how to do something which sounds simple but doesn't look like it when trying to program it. The idea is : give a string containing an equation, such as : "2*x = 10" for example (this is simple, but it could get very complex, such as sqrt(54)*35=x^2; and so on....) and the program would return x = 5 and possibly give a log of how he got there. Is this doable ? If so, does anyone have a lead ? For info there is this site (http://www.numberempire.com/equationsolver.php) which does the same thing in PHP, but isn't open source. Thanks for any help !
This is called "parsing", and although computer science has already solved this problem it isn't simple at all until you understand it thoroughly. There's an entire computer-science discipline that describes how to solve this problem. In C you must define the grammar of your input (possibly with precedence rules in it), then perform lexical analysis on your input, then parse the result and finally evaluate your parse tree. In languages such as Ruby, however, because you have such thorough support for string manipulation and because you have such tremendous runtime power you can solve your problem with a single line of code like so: puts(eval($_)) while gets Yes, that will cover more than what you ask for.
2,844,986
2,845,116
CString a = "Hello " + "World!"; Is it possible?
I'm making my own string class and I'd like to ensure that CString a = "Hello " + "World!"; works (i.e. does not give a compiler error such as: cannot add 2 pointers). My string class automatically converts to char* when needed and thus writing printf(a) would not break the code. Is there any way to replace the compiler behavior around characters ? (i.e. between inverted commas, "abc"). Or, alternatively, to change the behavior of the + operator to handle strings?
The right answer No. You cannot overload operators for built-ins, such as pointers. James McNellis already answered the question, so I won't elaborate. A possible alternative... (I use std::string because I have no info on your in-house string) Using a typedef will add some sugar to your syntax: typedef std::string S_ ; int main(int argc, char* argv[]) { std::string s = S_("Hello") + S_(" World") ; std::cout << "s : " << s << std::endl ; return 0 ; } But then, I wouldn't pollute the global namespace with a two-characters symbol just for a little sugar... And as far as I know, the code is inefficient (two string objects created, plus one temporary, without guarantee the compiler will optimize it all away...) For curiosity's sake... As a curiosity, by wrapping the string into a thin class, you can "add" those two pointers. First, let's create the wrapper : class StringThinWrapper { public : StringThinWrapper(const char * p) : m_p(p) {} operator const char * () const { return m_p ; } private : const char * const m_p ; } ; As you can see, it's both inlined, and will do nothing... Still, it's able to cast itself into a const char * pointer (this kind of hack is dangerous, so be sure it's what you want to do). Then, for this wrapper, let's overload the addition operator : inline std::string operator + (const StringThinWrapper & lhs, const StringThinWrapper & rhs) { std::string s(lhs) ; s += rhs ; return s ; } And now, let's write a main function using the wrapper, typedefed for ease of use : typedef StringThinWrapper S_ ; int main(int argc, char* argv[]) { std::string s = S_("Hello") + S_(" World") ; std::cout << "s : " << s << std::endl ; return 0 ; } Which compiles and gives the following result : s : Hello World Disclaimer: I just wanted to play with the idea your question gave me, and share it with you. Don't apply this kind of code just because you can. Indeed, this code should be refined to cover all cases efficiently before even being used, and even then, a simple typedef std::string S_ ; would be better IMHO. AFAIK, I wouldn't use it because I'm happy with the current STL API. And what about C++0x ? In C++0x, you'll be able to create your own literals. The code will be kinda like : std::string operator "str"(const char * p) { return std::string(p); } And you'll use it so : int main(int argc, char * argv[]) { std::string s = "Hello"str + " World"str ; std::cout << "s : " << s << std::endl ; return 0 ; } For more information, see the following SO question: What new capabilities do user-defined literals add to C++?.
2,845,091
2,845,104
Boost ForEach Question
Trying to use something like the below with a char array but it doesn't compile. But the example with short[] works fine. Any idea why? :) char someChars[] = {'s','h','e','r','r','y'}; BOOST_FOREACH(char& currentChar, someChars) { } short array_short[] = { 1, 2, 3 }; BOOST_FOREACH( short & i, array_short ) { ++i; }
If you go to the line in <boost/foreach.hpp> that raises the compilation error, you will see the following comment: // **** READ THIS IF YOUR COMPILE BREAKS HERE **** // // There is an ambiguity about how to iterate over arrays of char and wchar_t. // Should the last array element be treated as a null terminator to be skipped, or // is it just like any other element in the array? To fix the problem, you must // say which behavior you want. // // To treat the container as a null-terminated string, merely cast it to a // char const *, as in BOOST_FOREACH( char ch, (char const *)"hello" ) ... // // To treat the container as an array, use boost::as_array() in <boost/range/as_array.hpp>, // as in BOOST_FOREACH( char ch, boost::as_array("hello") ) ... Using boost::as_array(someChars) as shown in the comment should fix your compilation error.
2,845,372
2,845,489
Is this overly clever or unsafe?
I was working on some code recently and decided to work on my operator overloading in c++, because I've never really implemented it before. So I overloaded the comparison operators for my matrix class using a compare function that returned 0 if LHS was less than RHS, 1 if LHS was greater than RHS and 2 if they were equal. Then I exploited the properties of logical not in c++ on integers, to get all of my compares in one line: inline bool Matrix::operator<(Matrix &RHS){ return ! (compare(*this,RHS)); } inline bool Matrix::operator>(Matrix &RHS){ return ! (compare((*this),RHS)-1); } inline bool Matrix::operator>=(Matrix &RHS){ return compare((*this),RHS); } inline bool Matrix::operator<=(Matrix &RHS){ return compare((*this),RHS)-1; } inline bool Matrix::operator!=(Matrix &RHS){ return compare((*this),RHS)-2; } inline bool Matrix::operator==(Matrix &RHS){ return !(compare((*this),RHS)-2); } Obviously I should be passing RHS as a const, I'm just probably not going to use this matrix class again and I didn't feel like writing another function that wasn't a reference to get the array index values solely for the comparator operation. As per suggestion here is the code if Compare returns -1 for less, 0 for equal and 1 for positive. inline bool Matrix::operator<(Matrix &RHS){ return ! (compare(*this,RHS)+1); } inline bool Matrix::operator>(Matrix &RHS){ return ! (compare((*this),RHS)-1); } inline bool Matrix::operator>=(Matrix &RHS){ return compare((*this),RHS)+1; } inline bool Matrix::operator<=(Matrix &RHS){ return compare((*this),RHS)-1; } inline bool Matrix::operator!=(Matrix &RHS){ return compare((*this),RHS); } inline bool Matrix::operator==(Matrix &RHS){ return !(compare((*this),RHS)); } I don't know that this really increases the readability though.
As far as I can see it's safe, but it does take looking twice for everybody reading the code. Why would you want to do this? Anyway, for comparison, all you ever need is < and either == or !=, the rest is canonical and I write it mostly by muscle memory. Also, binary operators treating their operands equally (they leave them alone) should IMO be implemented as non-members. Given this, plus using the sane comparison function (-1, 0, +1) and adding the necessary const, I come to this: // doing real work inline bool operator<(const Matrix& l, const Matrix &r) { return -1 == compare(l,r); } inline bool operator==(const Matrix& l, const Matrix &r) { return 0 == compare(l,r); } // canonical inline bool operator> (const Matrix& l, const Matrix &r) {return r < l;} inline bool operator>=(const Matrix& l, const Matrix &r) {return !(l < r);} inline bool operator<=(const Matrix& l, const Matrix &r) {return !(r < l);} inline bool operator!=(const Matrix& l, const Matrix &r) {return !(l == r);} The comparisons might not be as clever as yours, but everyone who's ever seen strcmp() knows immediately what they do. Note that I even added 0 != compare(...), which is completely unnecessary - for the compiler. For humans IMO it makes it more clear what's going on than the implicit cast to bool. Plus it emphasizes the symmetry to operator<'s implementation.
2,845,429
2,845,555
calling a function from a set of overloads depending on the dynamic type of an object
I feel like the answer to this question is really simple, but I really am having trouble finding it. So here goes: Suppose you have the following classes: class Base; class Child : public Base; class Displayer { public: Displayer(Base* element); Displayer(Child* element); } Additionally, I have a Base* object which might point to either an instance of the class Base or an instance of the class Child. Now I want to create a Displayer based on the element pointed to by object, however, I want to pick the right version of the constructor. As I currently have it, this would accomplish just that (I am being a bit fuzzy with my C++ here, but I think this the clearest way) object->createDisplayer(); virtual void Base::createDisplayer() { new Displayer(this); } virtual void Child::createDisplayer() { new Displayer(this); } This works, however, there is a problem with this: Base and Child are part of the application system, while Displayer is part of the GUI system. I want to build the GUI system independently of the Application system, so that it is easy to replace the GUI. This means that Base and Child should not know about Displayer. However, I do not know how I can achieve this without letting the Application classes know about the GUI. Am I missing something very obvious or am I trying something that is not possible? Edit: I missed a part of the problem in my original question. This is all happening quite deep in the GUI code, providing functionality that is unique to this one GUI. This means that I want the Base and Child classes not to know about the call at all - not just hide from them to what the call is
It seems a classic scenario for double dispatch. The only way to avoid the double dispatch is switching over types (if( typeid(*object) == typeid(base) ) ...) which you should avoid. What you can do is to make the callback mechanism generic, so that the application doesn't have to know of the GUI: class app_callback { public: // sprinkle const where appropriate... virtual void call(base&) = 0; virtual void call(derived&) = 0; }; class Base { public: virtual void call_me_back(app_callback& cb) {cb.call(*this);} }; class Child : public Base { public: virtual void call_me_back(app_callback& cb) {cb.call(*this);} }; You could then use this machinery like this: class display_callback : public app_callback { public: // sprinkle const where appropriate... virtual void call(base& obj) { displayer = new Displayer(obj); } virtual void call(derived& obj) { displayer = new Displayer(obj); } Displayer* displayer; }; Displayer* create_displayer(Base& obj) { display_callback dcb; obj.call_me_back(dcb); return dcb.displayer; } You will have to have one app_callback::call() function for each class in the hierarchy and you will have to add one to each callback every time you add a class to the hierarchy. Since in your case calling with just a base& is possible, too, the compiler won't throw an error when you forget to overload one of these functions in a callback class. It will simply call the one taking a base&. That's bad. If you want, you could move the identical code of call_me_back() for each class into a privately inherited class template using the CRTP. But if you just have half a dozen classes it doesn't really add all that much clarity and it requires readers to understand the CRTP.
2,845,533
2,845,620
How can I know whether my C++ string variable is a number or not
I have a string of class string string str; how can I check if it is a number or not, str can only have 3 possible types described below like abcd or a number like 123.4 or a number with a parenthesis attach to the end it for example 456) note the parenthesis at the end of "str" is the only possible combination of number and none number where the bottom two are considered valid numbers, I know I could use lexical_cast if only the first 2 cases occur, but how about considering all 3 possible cases to occur? I don't need to do anything fancy with str, I just need to know whether it is a valid number as I described
The C++ solution for parsing strings manually is string streams. Put your string into a std::istringstream and read from that. What you could do to parse this is to try to read an (unsigned) int from the string. If this fails, it is a string not starting with digits. If it works, peek at the next character. If that's a . you have a floating point number, if it's a ), you have an integer number. (Otherwise you have a reading error.) Something along the lines of void read(const std::string& str) { std::istringstream iss(str); int i; if( !(iss>>i) ) { // str contains "abcd" } else { switch( iss.peek() ) { case ')': // i contains '456' break; case '.' { double d; if( !(iss>>d) ) throw "dammit!"; d += i; // d contains floating point value break; default: throw "what?!"; } // ... } Does this make sense?
2,845,537
2,845,616
Union struct produces garbage and general question about struct nomenclature
I read about unions the other day( today ) and tried the sample functions that came with them. Easy enough, but the result was clear and utter garbage. The first example is: union Test { int Int; struct { char byte1; char byte2; char byte3; char byte4; } Bytes; }; where an int is assumed to have 32 bits. After I set a value Test t; t.Int = 7; and then cout cout << t.Bytes.byte1 << etc... the individual bytes, there is nothing displayed, but my computer beeps. Which is fairly odd I guess. The second example gave me even worse results. union SwitchEndian { unsigned short word; struct { unsigned char hi; unsigned char lo; } data; } Switcher; Looks a little wonky in my opinion. Anyway, from the description it says, this should automatically store the result in a high/little endian format when I set the value like Switcher.word = 7656; and calling with cout << Switcher.data.hi << endl The result of this were symbols not even defined in the ASCII chart. Not sure why those are showing up. Finally, I had an error when I tried correcting the example by, instead of placing Bytes at the end of the struct, positioning it right next to it. So instead of struct {} Bytes; I wanted to write struct Bytes {}; This tossed me a big ol' error. What's the difference between these? Since C++ cannot have unnamed structs it seemed, at the time, pretty obvious that the Bytes positioned at the beginning and at the end are the things that name it. Except no, that's not the entire answer I guess. What is it then?
Note that, technically, reading from a member of a union other than the member that was last written to results in undefined behavior, so if you last assigned a value to Int, you cannot read a value from Bytes (there's some discussion of this on StackOverflow, for example, in this answer to another question). Chris Schmich gives a good explanation of why you are hearing beeps and seeing control characters, so I won't repeat that. For your final question, struct {} Bytes; declares an instance named Bytes of an unnamed struct. It is similar to saying: struct BytesType {}; BytesType Bytes; except that you cannot refer to BytesType elsewhere. struct Bytes {}; defines a struct named Bytes but declares no instances of it.
2,845,596
2,846,417
How to connect/disconnect from a server?
I am using the latest version of boost and boost.asio. I have this class: enum IPVersion { IPv4, IPv6 }; template <IPVersion version = IPv4> class Connection { private: boost::asio::io_service io_service; boost::asio::ip::tcp::resolver resolver; boost::asio::ip::tcp::resolver::query query; boost::asio::ip::tcp::resolver::iterator iterator; public: Connection(std::string host, std::string port); virtual void connect() { iterator = resolver.resolve(query); } // Is this the moment where the client actually connects? virtual void disconnect() { /* what goes in here? */ } }; Should I call io_service::stop() and then on my Connection::connect() call io_service::reset() first before I resolve the query?
Generally, once you've made a call to io_service::run, there's often few reasons to call io_service::stop or io_service::reset. In your code above, the connect method is not going to actively establish a connection - tcp::resolver::resolve merely turns a query (such as a hostname, or an IP address, etc.) into a TCP endpoint which can be used to connect a socket. You typically need to dereference an iterator returned by resolver::resolve and pass it to a boost::asio::ip::tcp::socket object's connect method (or one of the asynchronous varieties) to connect an endpoint. The Asio tutorials have a good example of this. See the first synchronous TCP daytime server example here: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime1.html. Note that the code first runs: tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); to turn a query object into a TCP endpoint, and then: socket.connect(*endpoint_iterator++, error); to connect a socket object on that endpoint. As for what should go in your disconnect method, that's entirely dependent on the application. But usually you'll need to keep track of an active connection by encapsulating a socket object, which you can close as necessary when you call disconnect. For an example of this, have a look at the tutorial titled "Daytime 3 - An Asynchronous TCP daytime server" here: http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/tutorial/tutdaytime3.html
2,845,600
2,845,623
C header file won't compile with C, but will with C++
I have the following chunk of a header file BKE_mesh.h: /* Connectivity data */ typedef struct IndexNode { struct IndexNode *next, *prev; int index; } IndexNode; void create_vert_face_map(ListBase **map, IndexNode **mem, const struct MFace *mface, const int totvert, const int totface); void create_vert_edge_map(ListBase **map, IndexNode **mem, const struct MEdge *medge, const int totvert, const int totedge); Note that the header file was prepared for the possibility of being used in a C++ file, as it had: #ifdef __cplusplus extern "C" { #endif at the top of the file, and the needed finish at the bottom. But the class implementing it was written in C. Next, whenever I try to #include the header file, I get an odd error. If the file has a .cpp extension, it compiles just fine, no complaints whatsoever. However, if I do: #include "BKE_mesh.h" inside of a file with a .c extension, I get the following errors: expected ')' before '*' token for the two last functions, in specific, the variable: ListBase **map in both classes. (Note that earlier in the header file, it declared, but not defined ListBase). So, my question is: why is this valid C++ code, but not C code? Thank you.
In C++ you can refer to struct names directly but in C you need to prepend the keyword struct. void create_vert_face_map(struct ListBase **map, ... ); You could get around this by adding a typedef. Then you wouldn't have to modify the function declaration. typedef struct ListBase ListBase;
2,845,704
2,845,837
How to interrupt a waiting C++0x thread?
I'm considering to use C++0x threads in my application instead of Boost threads. However, I'm not sure how to reimplement what I have with standard C++0x threads since they don't seem to have an interrupt() method. My current setup is: a master thread that manages work; several worker threads that carry out master's commands. Workers call wait() on at least two different condition variables. Master has a "timed out" state: in this case it tells all workers to stop and give whatever result they got by then. With Boost threads master just uses interrupt_all() on a thread group, which causes workers to stop waiting. In case they are not waiting at the moment, master also sets a bool flag which workers check periodically. However, in C++0x std::thread I don't see any replacement for interrupt(). Do I miss something? If not, how can I implement the above scheme so that workers cannot just sleep forever?
Unfortunately I don't see another way than polling, instead of using wait use a timed wait and a variable to state the interruption has been done. void th(Interruptor& interruptor) { try { ... while (cnd1.timed_wait(d)==false) { interruptor.check_interruption_point(); } ... } catch (interrupted_exception &) {} } The Interruptor class will maintain a boolean variable protected with a mutex or using atomic operations if you have them and two functions interrupt and check_interruption_point, which with throw a interrupted_exception if the boolean is true. The Mater thread will create an Interruptor variable that will be given to the concerned threads at creation time. The master has the the possibility to interrupt at once all the threads that depends on this interruptor. You can of course create an interruptor for each thread if you want to explicitly interrupt one thread at a time. Up to you to define the duration on the timed wait, so your threads are able to react as soon as your program require.
2,845,769
2,845,774
Can a std::string contain embedded nulls?
For regular C strings, a null character '\0' signifies the end of data. What about std::string, can I have a string with embedded null characters?
Yes you can have embedded nulls in your std::string. Example: std::string s; s.push_back('\0'); s.push_back('a'); assert(s.length() == 2); Note: std::string's c_str() member will always append a null character to the returned char buffer; However, std::string's data() member may or may not append a null character to the returned char buffer. Be careful of operator+= One thing to look out for is to not use operator+= with a char* on the RHS. It will only add up until the null character. For example: std::string s = "hello"; s += "\0world"; assert(s.length() == 5); The correct way: std::string s = "hello"; s += std::string("\0world", 6); assert(s.length() == 11); Storing binary data more common to use std::vector Generally it's more common to use std::vector to store arbitrary binary data. std::vector<char> buf; buf.resize(1024); char *p = &buf.front(); It is probably more common since std::string's data() and c_str() members return const pointers so the memory is not modifiable. with &buf.front() you are free to modify the contents of the buffer directly.
2,845,792
2,852,168
c# project cannot find c++ .dll?
I have a working c++ dll that works in one c# project that I am calling via the interop service. I have created another c# project and am trying to call the same .dll but keep getting a generic error message stating that the .dll cannot be found, both project are .net 2.0. What folder, and where do I specify in the project, should I put the .dll file in so that the project can find it? Think of it as a reminder for me... In the previous project I did not have a reference to it, I just had it in the /bin folder and doing the same thing for this project does not work. Thanks R.
Make sure all the DLLs that the DLL in question depends on, are also in the same directory as the exe that uses the DLL.
2,845,793
2,845,861
Build OpenGL model in parallel?
I have a program which draws some terrain and simulates water flowing over it (in a cheap and easy way). Updating the water was easy to parallelize using OpenMP, so I can do ~50 updates per second. The problem is that even with a small amounts of water, my draws per second are very very low (starts at 5 and drops to around 2 once there's a significant amount of water). It's not a problem with the video card because the terrain is more complicated and gets drawn so quickly that boost::timer tells me that I get infinity draws per second if I turn the water off. It may be related to memory bandwidth though (since I assume the model stays on the card and doesn't have to be transfered every time). What I'm concerned about is that on every draw, I'm calling glVertex3f() about a million times (max size is 450*600, 4 vertices each), and it's done entirely sequentially because Glut won't let me call anything in parallel. So.. is if there's some way of building the list in parallel and then passing it to OpenGL all at once? Or some other way of making it draw this faster? Am I using the wrong method (besides the obvious "use less vertices")?
Your approach to drawing in parallel is exactly the opposite of what you should be doing. Graphics hardware is inherently parallel and there isn't much use in trying to make as many calls to it as possible in a very short time. It is important to make single huge calls that send data to the hardware where the parallel processing can take place. All your glVertex() calls are exactly the opposite. As Georg pointed out: glVertexPointer() accompanied with glDrawElements() or glDrawArrays() are a good fit for your situation, if those aren't enough you should take the step up to Vertex Buffer Objects. Another would be to take calculations directly into the GPU with shaders. In all those methods you get parallism in the GPU nearly for free.
2,845,859
2,845,871
#include <string> adding ~43 KB to my exe
I'm using Code::Blocks to write my program and when I include <string> (or <iostream>) the size of my exe grows. My program is very simple and I need to keep it small <20kb. I'm pretty sure this is happening because of the C++ Standards Committee swapped the old .h versions for many new libraries without the .h. But how would I keep it from adding the ~43kb? Are there settings for Code::Blocks so that it wont add the extra kb or is there another native lib I can use?
If size is your #1 concern (and if you have to keep things < 20KB, then it probably is) then the standard C++ library is probably not the way to go. In fact, any C++ at all (RTTI, exceptions, etc) is probably a bad idea and you would be better off just sticking with straight C.
2,845,980
2,845,999
Thread safety with heap-allocated memory
I was reading this: http://en.wikipedia.org/wiki/Thread_safety Is the following function thread-safe? void foo(int y){ int * x = new int[50]; /*...do some stuff with the allocated memory...*/ delete [] x; } In the article it says that to be thread-safe you can only use variables from the stack. Really? Why? Wouldn't subsequent calls of the above function allocate memory elsewhere? Edit: Ah. Looks like I misread this part of the article: A subroutine is reentrant, and thus thread-safe, if the only variables it uses are from the stack (I took it to mean A subroutine is reentrant, and thus thread-safe, if and only if the only variables it uses are from the stack , which according to the answers below, is not the case)
If you are coding in an environment that supports multi-threading, then you can be pretty sure new is thread safe. Although the memory is on the heap, the pointer to it is on the stack. Only your thread has the pointer to this memory, and so there is no risk of concurrent modification - no other thread knows where the memory is to modify it. You would only get a problem with thread safety if you were to pass this pointer to another thread that would then concurrently modify this memory at the same time as your original (or another) thread.