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,774,934
2,774,961
Setting precision on std::cout in entire file scope - C++ iomanip
I'm doing some calculations, and the results are being save in a file. I have to output very precise results, near the precision of the double variable, and I'm using the iomanip setprecision(int) for that. The problem is that I have to put the setprecision everywhere in the output, like that: func1() { cout<<setprecision(12)<<value; cout<<setprecision(10)<<value2; } func2() { cout<<setprecision(17)<<value4; cout<<setprecision(3)<<value42; } And that is very cumbersome. Is there a way to set more generally the cout fixed modifier? Thanks
Are you looking for cout.precision ?
2,775,024
2,775,090
Name lookup for names not dependent on template parameter in VC++2008 Express. Is it a bug?
While experimenting a bit with C++ templates I managed to produce this simple code, for which the output is different, than I expected according to my understanding of C++ rules. void bar(double d) { std::cout << "bar(double) function called" << std::endl; } template <typename T> void foo(T t) { bar(3); } void bar(int i) { std::cout << "bar(int) function called" << std::endl; } int main() { foo(3); return 0; } When I compile this code in VC++2008 Express, function bar(int) gets called. That would be the behaviour, I would expect if bar(3);in the template body was dependent on the template parameter. But it's not. The rule I found here says "The C++ standard prescribes that all names that are not dependent on template parameters are bound to their present definitions when parsing a template function or class". Am I wrong, that "present definition" of bar when parsing the template function foo is the definition of void bar(double d);? Why it's not the case if I am wrong. There are no forward declarations of bar in this compilation unit.
It is indeed a bug in the compiler. The problem was known to exist in VS2005 and before (I use a Blogspot blog as a notebook for cases like this, see 1.3 here). Apparently it is present in VS2008 as well. You can test it with the following simple code int bar(double d) { return 0; } template <typename T> void foo(T t) { int i = bar(3); } void bar(int i); int main() { foo(3); } This code is well-formed (you can compile it with Comeau Online compiler), but I bet that VS will choke on it because VS implements the two-phase lookup incorrectly in this case.
2,775,109
2,775,270
Safe to cast pointer to a forward-declared class to its true base class in C++?
In one header file I have: #include "BaseClass.h" // a forward declaration of DerivedClass, which extends class BaseClass. class DerivedClass ; class Foo { DerivedClass *derived ; void someMethod() { // this is the cast I'm worried about. ((BaseClass*)derived)->baseClassMethod() ; } }; Now, DerivedClass is (in its own header file) derived from BaseClass, but the compiler doesn't know that at the time it's reading the definition above for class Foo. However, Foo refers to DerivedClass pointers and DerivedClass refers to Foo pointers, so they can't both know each other's declaration. First question is whether it's safe (according to C++ spec, not in any given compiler) to cast a derived class pointer to its base class pointer type in the absence of a full definition of the derived class. Second question is whether there's a better approach. I'm aware I could move someMethod()'s body out of the class definition, but in this case it's important that it be inlined (part of an actual, measured hotspot - I'm not guessing).
It may work, but the risk is huge. The problem is that most of the times Derived* and Base* will indeed have the same value under the hood (which you could print). However this is not true as soon as you have virtual inheritance and multi-inheritance and is certainly not guaranteed by the standard. When using static_cast the compiler performs the necessary arithmetic (since it knows the layout of the class) to adjust the pointer value. But this adjustment is not performed by reinterpret_cast or the C-style cast. Now, you could perfectly rework your code like so: // foo.h class Derived; class Foo { public: void someMethod(); private: Derived* mDerived; }; // foo.cpp #include "myProject/foo.h" #include "myProject/foo.cpp" void Foo::someMethod() { mDerived->baseClassMethod(); } Anyway: you are using a pointer to Derived, while it's okay there is a number of gotchas you should be aware of: notably if you intend to new an instance of the class it will be necessary for you to redefine the Copy Constructor, Assignment Operator and Destructor of the class to properly handle the pointer. Also make sure to initialize the pointer value in every Constructor (whether to NULL or to an instance of Derived). It's not impossible but document yourself.
2,775,236
2,775,250
functionality of cin in c++
I'm a bit confused by the results of the following function: int main() { string command; while(1) { cin >> command; if(command == "end") return 0; else cout << "Could you repeat the command?" << endl; } return 0; } First of all - the output line ("could you...") repeats once for each individual word in the input (stored in command). So far as I can see, it should only be possible for it to happen once for each instance of the loop. Also, when the line 'if(command == "end")' is changed to 'if(command == "that's all")' it never triggers. A little testing suggested that all of the whitespace was removed from the command. Could someone explain to me what's going on here? Thanks
The formatted input operator >>() reads space separated tokens from input. If you want to read whole lines, use the getline() function: string command; getline( cin, command );
2,775,248
2,775,441
How to bundle C/C++ code with C-shell-script?
I have a C shell script that calls two C programs - one after the another with some file handling before, in-between and afterwards. Now, as such I have three different files - one C shell script and 2 .c files. I need to give this script to other users. The problem is that I have to distribute three files - which the users must keep in the same folder and then execute the script. Is there some better way to do this? [I know I can make one C code file out of those two... but I will still be left with a shell script and a C code. Actually, the two C codes do entirely different things... so I want them to be separate]
Sounds like you're worried that your users aren't savy enough to figure out how to resolve issues like command not found errors and the like. If absolutely MUST hide "complexity" of a collection of files you could have your script create the other files. In most other circumstances I would suggest that this approach is only going to increase your support workload since semi-experienced users are less likely to know how to troubleshoot the process. If you choose to rely on the presence of a compiler on the system that you are running on you can store the C code as a collection of cat $STRING >> file.c commands to to create your two C files, which you then compile and use. If you would want to use pre-compiled programsn instead then the same basic process can be used except instead use xxd to both generate the strings in your script and reverse the conversion process to give you working binaries. Note: Remember to chmod the binary so that it is executable.
2,775,277
2,775,295
Can a single argument constructor with a default value be subject to implicit type conversion
I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument constructor, or with a constructor that has multiple arguments of which only the first does not have a default value. However, I was wondering, does a single argument constructor with a default value behave the same as one without a default value when it comes to implicit conversions?
The existence of a default value does not stop the single-argument ctor from being used for implicit conversion: you do need to add explicit if you want to stop that. For example...: #include <iostream> struct X { int i; X(int j=23): i(j) {} }; void f(struct X x) { std::cout << x.i << std::endl; } int main() { f(15); return 0; } compiles and runs correctly: $ g++ -Wall -pedantic a.cc $ ./a.out 15 $ correctly, that is, if you want an int to become a struct X implicitly. The =23 part, i.e. the default value for the one argument to the constructor, does not block this.
2,775,469
2,775,505
Calling a function that uses object members without giving the object
void CVisualStudioDemoDoc::updateLine(void) { int newln = GetLineNumber(p_buf); reinterpret_cast<CVisualStudioDemoView *>(m_viewList.GetHead())->SetCurrentLineNumber(ln, newln); ln = newln; } I want to call this function from another part of my code without having to give the object pointer and include headers. I want to call it just like a normal void function. if (changementLigne == true) { currentLine = prog; // TODO : appeler le callback de X2 updateLine(); Suspendre(); changementLigne = false; } I dont know if it's possible, since the CVisualStudioDemoDoc class is an MFC class, I didn't find a pointer I can use.
You can't do this. If a member function refers to member variables, it needs a valid this pointer. If you don't include the header file that declares the function, the compiler can't know what you're referring to. How can it know that updateLine() is a function unless you tell it? If you're trying to call a C++ member function from C code then you need to write a wrapper. Something like the following (not tested): .h file: extern "C" { CallUpdateLine(void* data); } .cpp file: extern "C" { CallUpdateLine(void* data) { CVisualStudioDemoDoc* ptr = static_cast<CVisualStudioDemoDoc*>(data); ptr->updateLine(); } } There are other questions that might be helpful as well.
2,775,578
2,775,658
Biased Random Number Generator
I am looking for a random number generator that can be biased. For instance, say I want a random number between 1-5, with the probability being: 1: Comes up 20% of the time 2: Comes up 10% of the time 3: Comes up 40% of the time 4: Comes up 25% of the time 5: Comes up 5% of the time Is there anything in the standard library, or other libraries out there that would do this? Alternatively, is there an efficient way to do this myself?
The Boost random number library provides the ability to specify different shaped distributions for your generator. It's a great library - see http://www.boost.org/doc/libs/1_42_0/libs/random/index.html.
2,775,602
2,775,636
im counting the number of characters in a file but i want to count the number of words that are less than 5 and 6 or greater
i want to do this: reads the words in the file one at a time. (Use a string to do this) Counts three things: how many single-character words are in the file, how many short (2 to 5 characters) words are in the file, and how many long (6 or more characters) words are in the file. HELP HERE im not sure on how about reading file into a string. i know i have to something like this but i dont understand the rest. HELP HERE ifstream infile; //char mystring[6]; //char mystring[20]; int main() { infile.open("file.txt"); if(infile.fail()) { cout << " Error " << endl; } int numb_char=0; char letter; while(!infile.eof()) { infile.get(letter); cout << letter; numb_char++; break; } cout << " the number of characters is :" << numb_char << endl; infile.close(); return 0;
I'm not quite sure where to start... Your loop: while(!infile.eof()) { infile.get(letter); cout << letter; numb_char++; break; } Would only execute once due to the extra break; Also this code looks like it is trying to read the number of characters in a file, and not count up the number of words that are 5 letters or greater than 6 letters. Try something like: ifstream infile; int main(){ infile.open("file.txt"); if(!infile.good()){ cout << " Error " << endl; return 1; } int shortCount = 0; int mediumCount = 0; int longCount = 0; int charCount = 0; char letter; while(!infile.eof()){ infile >> letter; if(letter == ' ' || char == EOF){ // end of word or file. if(charCount == 1) shortCount++; else if(charCount < 6) mediumCount++; else longCount++; charCount = 0; }else{ charCount++; } } cout << "Short Words: " << shortCount << endl; cout << "Medium Words: " << mediumWords << endl; cout << "Long Words: " << longWords << endl; infile.close(); return 0; }
2,775,854
2,775,952
Map a 32 bit float to a 32 bit integer
Is there a way to map floats to ints or unsigned ints so that with the exception of NaN, order is preserved? So if a and b are floats, and F is the mapping function, a < b implies F(a) < F(b) and a == b implies F(a) == F(b)
Hm, just out of the DawsonCompare routine in Game Programming Gems 6, it's a normal bit-cast followed by a sign flip (since negative floats order opposite then negative integers). I'll borrow that idea. You have: // utility template <typename R, typename T> R& bit_cast(T& pX) { return reinterpret_cast<R&>(pX); } // int32_t defined in <boost/cstdint.hpp>. boost::int32_t float_to_int_bits(float pX) { boost::int32_t x = bit_cast<boost::int32_t>(pX); if (x < 0) x = 0x80000000 - x; return x; } If you can guarantee your int is 32 bits, you can just use that. Fun fact: The book goes on to use this (note, not with the exact code I present, since I stripped out the float-to-int part) to compare floating point values with tolerance: bool DawsonCompare(float pX, float pY, int pDiff) { int x = float_to_int_bits(pX); int y = float_to_int_bits(pY); int diff = x - y; return abs(diff) < pDiff; } This compares floats as true if their integer representations are within a certain range. (He uses 1000 as a good default.) A branch-less version called the LomontCompare is presented with the same idea, but you have to buy the book for that. :)
2,776,313
2,776,328
Foo f = Foo(); // no matching function for call to 'Foo::Foo(Foo)' ... huh?
class Foo { public: explicit Foo() {} explicit Foo(Foo&) {} }; Foo d = Foo(); error: no matching function for call to 'Foo::Foo(Foo)' I tried changing Foo(Foo&) to Foo(Foo) as the error suggests, which AFAIK is not a valid constructor, and sure enough I get: error: invalid constructor; you probably meant ‘Foo (const Foo&)’ What gives? How do I resolve this? (This is on GCC by the way)
There are two questionable things that you have in your copy constructor. First, you've made the copy-constructor explicit (which is a questionable thing to do), so you would (in theory) need to do: Foo d( (Foo()) ); Second, your copy constructor takes a reference and not a const reference which means that you can't use it with a temporary Foo. Personally, I'd just remove explicit from the copy-constructor and make it take a const reference if possible. Note that the explicit on your default constructor has no effect.[*] explicit only has an effect on constructors that can be called with a single parameter. It prevents them being used for implicit conversions. For constructors that take only zero or only two or more parameters, it has no effect. [Note: there can be a difference between: Foo d; and Foo d = Foo(); but in this case you have a user-declared default constructor so this doesn't apply.] Edit: [*] I've just double checked this and 12.3.1 [class.conv.ctor] says that you can make a default constructor explicit. In this case the constructor will be used to perform default-initialization or value-initialization. To be honest, I don't understand the value of this as if you have a user-declared constructor then it's a non-POD type and even local objects of non-POD type are default-initialized if they don't have an initializer which this clause says can be done by an explicit default constructor. Perhaps someone can point out a corner case where it does make a difference but for now I don't see what effect explicit has on a default constructor.
2,776,381
2,776,393
What Does an OS Actually Do?
What exactly does an operating system do? I know that operating systems can be programmed, in, for example, C++, but I previously believed that C++ programs must be run under an operating system? Can somebody please explain and give links? thanks in advance, ell
An operating system is a layer between your code (user code) and the hardware. The OS is responsible for managing the physical components and giving you a simple (hopefully) API off of which to build. It handles which programs run, when, who goes first, how memory is handled, who gets memory, video drawing, and all that good stuff. For example, when making a GUI, instead of you sending each bit to the monitor, you tell the OS (or window manager) to make a window. You then tell it to place a button in your window. The OS then handles drawing the window, moving the window, moving the button (but keeping it where it should be in the window). Now, you can program an operating system in C++, but it's not easy. You have to develop your kernel and whatnot, find a way to interface with the hardware, then expose that interface to your users and their programs. So, essentially, an OS handles software-to-hardware interfacing and manages your physical resources. C++ programs can be run in an OS or, with enough work, run by themselves or even be an OS.
2,776,389
2,776,457
Operator+ for a subtype of a template class
I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<int>::subtype operator+(const c<int>::subtype& left, // const c<int>::subtype& right) // { return c<int>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?
Your suspicion is correct. The compiler doesn't know what other_type is. It can't deduce it from the arguments. Such forms often are too loose to provide the needed informations. Consider template<typename other_type> struct c { c(other_type v) : cs(v) {} typedef int subtype; }; If you were to pass an int, then any of c<T> would fit the bill because all of them have type int. In the specific case of nested classes, it may be possible, but even then it's not unique. Imagine that in c<float> you could put a typedef c<int> subtype;, then both c<float>::subtype and c<int>::subtype would fit the bill. Back in pre-standard time, there existed a list of template-issues that in particular John Spicer did go through and invented reasonable solutions. That was one such problem, and it was found that it's not worth the trouble. You always explicitly need to provide the argument - it's never deduced. You could change your code to this template<typename other_type> struct subtype { subtype(other_type v) : val(v) {} other_type val; }; template<typename other_type> struct c { c(other_type v) : cs(v) {} subtype<other_type> cs; }; template<typename other_type> subtype<other_type> operator+(const subtype<other_type>& left, const subtype<other_type>& right) { return subtype<other_type>(left.val + right.val); } Or to this template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; /* note: don't forget friend! */ friend subtype operator+(const subtype& left, const subtype& right) { return subtype(left.val + right.val); } } cs; };
2,776,608
2,776,650
How to demonstrate memory error using arrays in C++
I'm trying to think of a method demonstrating a kind of memory error using Arrays and C++, that is hard to detect. The purpose is to motivate the usage of STL vector<> in combination with iterators. Edit: The accepted answer is the answer i used to explain the advantages / disadvantages. I also used: this
A memory leak? IMO, vector in combination with iterators doesn't particularly protect you from errors, such as going out of bounds or generally using an invalidated iterator (unless you have VC++ with iterator debugging); rather it is convenient because it implements a dynamically resizable array for you and takes care of memory management (NB! helps make your code more exception-safe). void foo(const char* zzz) { int* arr = new int[size]; std::string s = zzz; //... delete[] arr; } Above can leak if an exception occurs (e.g when creating the string). Not with a vector. Vector also makes it easier to reason about code because of its value semantics. int* arr = new int[size]; int* second_ref = arr; //... delete [] arr; arr = 0; //play it safe :) //... second_ref[x] = y; //... delete [] second_ref; But perhaps a vector doesn't automatically satisfy 100% of dynamic array use cases. (For example, there's also boost::shared_array and the to-be std::unique_ptr<T[]>)
2,776,775
2,777,040
Question on Virtual Methods
IF both methods are declared as virtual, shouldn't both instances of Method1() that are called be the derived class's Method1()? I am seeing BASE then DERIVED called each time. I am doing some review for an interview and I want to make sure I have this straight. xD class BaseClass { public: virtual void Method1() { cout << "Method 1 BASE" << endl; } }; class DerClass: public BaseClass { public: virtual void Method1() { cout << "Method 1 DERVIED" << endl; } }; DerClass myClass; ((BaseClass)myClass).Method1(); myClass.Method1(); Method 1 BASE Method 1 DERVIED
What you are seeing here is called "slicing". Casting an object of the derived class to the base class "slices off" everything that is not in the base class. In C++ virtual functions work correctly only for pointers or references. For your example to work right, you have to do the following: DerClass myClass; ((BaseClass *) &myClass)->Method1(); Or you could do BaseClass *pBase = new DerClass; pBase->Method1();
2,776,872
2,777,026
QGLWidget + QGraphicsScene + QGraphicsView problem
I would like to create a simple thumbnail viewer using QGLWidget, QGraphicsScene and QGraphicsView. And I have a problem with placing QGLWidget on QGraphicsScene. The code is similar to this: QGraphicsScene *testScene = new QGraphicsScene (0, 0, 400, 400, 0); QGLWidget *testWidget1 = new QGLWidget(); testWidget1->renderText("Test text1"); QGLWidget *testWidget2 = new QGLWidget(); testWidget2->renderText("Test text2"); testScene->addWidget(testWidget1); testScene->addWidget(testWidget2); QGraphicsView *testView = new QGraphicsView(); testView->setScene(testScene); testView->show() It is possible to place few QGLWidgets on QGraphicsScene/QGraphicsView? Where I doing something wrong? Is there any other component on which I could embed QGLWidgets and show them on the screen? Thanks for help
The QGraphicsScene::addWidget documentation states that QGLWidget is not a supported widget type. Parenting a QGLWidget onto the viewport of the QGraphicsView doesn't seem to work either. Edit: Actually parenting a QGLWidget to the viewport does work provided I put the renderText call within the paintGL method of my test GL widget.
2,777,003
2,777,052
c++ problem, maybe with types
I have a little problem in my code. The variables don't want to change their values. Can you say why? Here is my code: vector<coordinate> rocks(N); double angle; double x, y; // other code while (x > 1.0 || x < -1.0 || y > 1.0 || y < -1.0) { angle = rand() * 2.0 * M_PI; cout << angle << endl; cout << rocks[i - 1].x << endl; cout << rocks[i - 1].y << endl; x = rocks[i-1].x + r0 * cos(angle); y = rocks[i-1].y + r0 * sin(angle); cout << x << endl; cout << y << endl << endl; } // other code And the result on the console is: 6.65627e+09 0.99347 0.984713 1.09347 0.984713 1.16964e+09 0.99347 0.984713 1.09347 0.984713 As you see the values of x, y variables doesn't change and this while be an infinity loop. What's the problem? What do you think?
Why are you expeciting x and y to change? You assign to them the value of a calculation that doesn't change? rand() * 2.0 * M_PI is always a multiple of 2 * pi (as far as a double can represent) so cos(angle) will be 1 and sin(angle) will be 0.
2,777,104
2,777,172
Compile C++ from VS08/10 without Run Time Library / MFC
Are there settings I can adjust in Visual Studio so that it does not compile with any run time library or MFC. I started learning C++ to get away from C#'s .Net, and this is just as bad. When I execute the program in a Windows XP virtual machine I get an error. I can compile without the dependencies in Code::Blocks, but I'm more familiar with VS, and prefer many of it's features over those of Code::Blocks. If you know of to get past this, it would be greatly appreciated. Thanks.
You can simply link to the static version of the CRT; just go into the project properties and specify, for the Release configuration, the "Multithreaded (/MT)" CRT instead of the "Multithreaded DLL (/MD)" (you can leave the debug configuration alone, since you'll run it just on your machine anyway). In this way your executable will depend just from "safe" system dlls; obviously this will make your executable grow quite a bit (for example, a small console application that I needed to work without dependencies grew from ~32 KB to ~200 KB). If you, instead, just want to go without any standard library, you'll have to enable the "Ignore default libraries" option (or something like that, among the linker options), but keep in mind that in this way you won't have almost any facility.
2,777,177
2,777,210
Can I use MFC objects in STL containers?
The following code doesn't compile for me in MSVC2005: std::vector<CMenu> vec(10); CMenu is an MFC menu object (such as a context menu). Through some testing I learned that CMenu does not have a public copy constructor. To do what I wanted to do, I needed to use a dynamic array. CMenu* menus = new CMenu[10]; // ... delete [] menus; Of course, now I've lost all the benefits of using an STL container. Do I have any other options?
You could use pointer containers or containers of smart pointers, e.g. using shared_ptr from Boost or TR1: std::vector<shared_ptr<CMenu> > vec; vec.push_back(make_shared<CMenu>());
2,777,241
2,777,254
Function calculating the probability of a letter in an sentence
I have a function that is supposed to calculate the number of times a letter occurs in a sentence, and based on that, calculate the probability of it occurring in the sentence. To accomplish this, I have a sentence: The Washington Metropolitan Area is the most educated and affluent metropolitan area in the United States. An array of structures, containing the letter, the number of times it occurs, and the probability of it occurring, with one structure for each letter character and an additional structure for punctuation and spaces: struct letters { char letter; int occur; double prob; }box[53]; This is the function itself: void probability(letters box[53], int sum { cout<<sum<<endl<<endl; for(int c8=0;c8<26;c8++) { box[c8].prob = (box[c8].occur/sum); cout<<box[c8].letter<<endl; cout<<box[c8].occur<<endl; cout<<box[c8].prob<<endl<<endl; } } It correctly identifies that there are 90 letters in the sentence in the first line, prints out the uppercase letter as per the structure in the second line of the for loop, and prints out the number of times it occurs. It continually prints 0 for the probability. What am I doing wrong?
When you divide occur by sum, you are dividing an int by an int, which truncates (to 0 in this case). It doesn't matter that you are assigning the result to a double. To fix this, cast occur to a double before the division: box[c8].prob = ((double)box[c8].occur)/sum;
2,777,248
2,777,925
How does GetGlyphOutline function work? (WinAPI)
Basically I want to get bezier control points from a ttf font and then draw them. I was basically wondering 2 things. Does it return an array of points or is it more complex? How can you tell the points of 1 contour from another ex: the letter O which has 2 contours? Thanks
Found it: The native buffer returned by GetGlyphOutline when GGO_NATIVE is specified is a glyph outline. A glyph outline is returned as a series of one or more contours defined by a TTPOLYGONHEADER structure followed by one or more curves. Each curve in the contour is defined by a TTPOLYCURVE structure followed by a number of POINTFX data points. POINTFX points are absolute positions, not relative moves. The starting point of a contour is given by the pfxStart member of the TTPOLYGONHEADER structure. The starting point of each curve is the last point of the previous curve or the starting point of the contour. The count of data points in a curve is stored in the cpfx member of TTPOLYCURVE structure. The size of each contour in the buffer, in bytes, is stored in the cb member of TTPOLYGONHEADER structure. Additional curve definitions are packed into the buffer following preceding curves and additional contours are packed into the buffer following preceding contours. The buffer contains as many contours as fit within the buffer returned by GetGlyphOutline.
2,777,360
3,669,586
Only Integrating Box2D collision detection in my 2d engine?
I have integrated box2d in my engine, ( Debug Draw, etc. ) and with a world I can throw in some 2d squares/rectangles etc. I saw this post, where the user is basically not using a world for collision detection, however the user doesn't explain anything about how he's using the manifold (b2Manifold), etc. Another post, is in the cocos2d forum, ( scroll down to the user Lam in the third reply ) Could anyone help me a bit with this?, basically want to add collision detection without the need of using b2World ,etc etc. Thanks a lot!
Is there any reason you can't use a b2World? Just because you use it, doesn't mean you have to use the physics simulations, unless you're severely performance limited. See this example on using Box2D for collision only in Cocos2d. Maybe you can apply something similar to your project: http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone
2,777,372
2,777,433
Constructors with inheritance in c++
If you have 3 classes, with arrows going from parent to child classes (i.e. "A -> B" means "B inherits from A": shape -> 2d shape -> circle +----> 3d shape -> sphere When you write your constructor for the circle class, would you ever just initialize the grandparent Shape object and then your current object, skipping the middle class? It seems to me you could have x,y coordinates for Shape and initialize those in the constructor, and initialize a radius in the circle or sphere class, but in 2d or 3d shape classes, I wouldn't know what to put in the constructor since it seems like it would be identical to shape. So is something like this valid Circle::Circle(int x, int y, int r) : Shape(x, y), r(r) {} I get a compile error of: illegal member initialization: 'Shape' is not a base or member So I wasn't sure if my code was legal or best practice even. Or if instead you'd have the middle class just do what the top level Shape class does TwoDimensionalShape::TwoDimensionalShape(int x, int y) : Shape (x, y) {} and then in the Circle class Circle::Circle(int x, int y, int r) : TwoDimensionalShape(x, y), r(r) {}
Yes, as you pointed out at the end of the post, you class constructor can only call its immediate parent's constructor, you can't "skip" classes and initialise your parent's parent.
2,777,375
2,777,392
C++ increment operator
How to differentiate between overloading the 2 versions of operator ++ ? const T& operator ++(const T& rhs) which one? i++; ++i;
These operators are unary, i.e., they do not take a right hand side parameter. As for your question, if you really must overload these operators, for the preincrement use the signature const T& operator ++(), and for the postincrement, const T& operator(int). The int parameter is a dummy.
2,777,527
2,777,995
Stopping a runaway Lua subprocess
I have embedded Lua in an Objective-C application using LuaObjCBridge. I need to know how to stop the Lua process if it taking too much time (infinite loop?). Would running it in a separate thread help?
The usual way to do this is to use lua_sethook to schedule a callback every count VM instructions; when the callback lua_Hook function occurs after a excessive time your hook function can raise an error forcing control to your protected call.
2,777,541
2,777,558
Static const double in c++
Is this the proper way to use a static const variable? In my top level class (Shape) #ifndef SHAPE_H #define SHAPE_H class Shape { public: static const double pi; private: double originX; double originY; }; const double Shape::pi = 3.14159265; #endif And then later in a class that extends Shape, I use Shape::pi. I get a linker error. I moved the const double Shape::pi = 3.14... to the Shape.cpp file and my program then compiles. Why does that happen? thanks.
Because const double Shape::pi = 3.14159265; is the definition of Shape::pi and C++ only allows a single definition of a symbol (called the one-definition-rule which you may see in it's acronym form ODR). When the definition is in the header file, each translation unit gets it's own definition which breaks that rule. By moving it into the source file, you get only a single definition.
2,777,707
2,778,752
Performance considerations when mixing C++ and Objective-C in same file
I have some high-performance C++ that I need to interface with Objective-C, is there any performance penalty to just dumping this code into a .mm file that contains my Objective-C code vs. leaving this code in a separate .cpp file and extern-ing all the functions I need to call from the .mm file?
There are a handful of issues here. (1) if your C++ engine code is running in isolation -- if the Objective-C is acting as the front-end that triggers the underlying engine -- then there is no penalty at all. The C++ bits in ObjC++ compile just like regular C++. (2) If you are calling into Objective-C from within the calculation engine, then you might have a performance issue on your hands. There is overhead in calling an Objective-C method -- objc_msgSend() isn't free (but close to it) -- but generally not enough to be a problem in comparison to, say, a function call. However, in highly optimized C++, the compiler there may be optimizations that eliminate, even, function call overhead (it gets complex) to a large extent. An Objective-C method call cannot be inlined or optimized away. (3) If you haven't measured it and discovered a performance problem, don't worry about it...
2,777,751
2,777,760
Convert integer to formatted LPCWSTR. C++
I have a direct3d project that uses D3DXCreateTextureFromFile() to load some images. This function takes a LPCWSTR for the path to file. I want to load a series of textures that are numbered consecutively (ie. MyImage0001.jpg, MyImage0002.jpg, etc) But c++'s crazy strings confuse me. How do i: for(int i=0; i < 3;i++) { //How do I convert i into a string path i can use with D3DXCreateTextureFromFile? } Edit: I should mention I am using Visual Studio 2008's compiler
One option is std::swprintf: wchar_t buffer[256]; std::swprintf(buffer, sizeof(buffer) / sizeof(*buffer), L"MyImage%04d.jpg", i); You could also use a std::wstringstream: std::wstringstream ws; ws << L"MyImage" << std::setw(4) << std::setfill(L'0') << i << L".jpg"; ws.str().c_str(); // get the underlying text array
2,777,873
2,777,889
c++ exceptions and program execution logic
I have been thru a few questions but did not find an answer. I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress? For example, I want to process exceptions at four stages of the program and know that exception happened at that specific stage: 1. Initialization 2. Script processing 3. Computation 4. Wrap-up. At this point, I tried this: int main (...) { ... // start logging system try { ... } catch (exception &e) { cerr << "Error: " << e.what() << endl; cerr << "Could not start the logging system. Application terminated!\n"; return -1; } catch(...) { cerr << "Unknown error occured.\n"; cerr << "Could not start the logging system. Application terminated!\n"; return -2; } // open script file and acquire data try { ... } catch (exception &e) { cerr << "Error: " << e.what() << endl; cerr << "Could not acquire input parameters. Application terminated!\n"; return -1; } catch(...) { cerr << "Unknown error occured.\n"; cerr << "Could not acquire input parameters. Application terminated!\n"; return -2; } // computation try { ... } ... This is definitely not centralized and seems stupid. Or maybe it is not a good concept at all?
You could keep a global variable containing the state of the program, and print it out in the catch block. Then you would only need two catch blocks, one for std::exception and one for everything else.
2,777,937
2,777,991
How to wrap two unmanaged C++ functions into two managed C# functions?
I've got two unmanaged C++ functions, Compress and Decompress. The arguments and returns go as followed: unsigned char* Compress (unsigned char*,int) unsigned char* Decompress (unsigned char*,int) Where all uchars are arrays of uchars. Could someone please help me lay out a way to convert these into managed C# code using the Byte[] array instead of unsigned char*? Thank you very much!
You should be able to pass the unsigned char* parameter in as a byte[] and standard P/Invoke marshaller should handle that. You will have to marshal the output unsigned char* yourself, but that should just be a call to Marshall.Copy(). See below for an example of what I think will work. Two big questions: How does the caller know the size of data stored in the return unsigned char* buffer? How is the memory allocated for the return unsigned char* buffer? Do you have to free it and how will you free it from C# if you need to? Sample: [DllImport("Name.dll")] private static extern IntPtr Compress([MarshalAs(UnmanagedType.LPArray)]byte[] buffer, int size); [DllImport("Name.dll")] private static extern IntPtr Decompress([MarshalAs(UnmanagedType.LPArray)]byte[] buffer, int size); public static byte[] Compress(byte[] buffer) { IntPtr output = Compress(buffer, buffer.Length); /* Does output need to be freed? */ byte[] outputBuffer = new byte[/*some size?*/]; Marshal.Copy(output, outputBuffer, 0, outputBuffer.Length); return outputBuffer; } public static byte[] Decompress(byte[] buffer) { IntPtr output = Decompress(buffer, buffer.Length); /* Does output need to be freed? */ byte[] outputBuffer = new byte[/*some size?*/]; Marshal.Copy(output, outputBuffer, 0, outputBuffer.Length); return outputBuffer; }
2,778,193
4,714,939
segfault during __cxa_allocate_exception in SWIG wrapped library
While developing a SWIG wrapped C++ library for Ruby, we came across an unexplained crash during exception handling inside the C++ code. I'm not sure of the specific circumstances to recreate the issue, but it happened first during a call to std::uncaught_exception, then after a some code changes, moved to __cxa_allocate_exception during exception construction. Neither GDB nor valgrind provided any insight into the cause of the crash. I've found several references to similar problems, including: http://wiki.fifengine.de/Segfault_in_cxa_allocate_exception http://forums.fifengine.de/index.php?topic=30.0 http://code.google.com/p/osgswig/issues/detail?id=17 https://bugs.launchpad.net/ubuntu/+source/libavg/+bug/241808 The overriding theme seems to be a combination of circumstances: A C application is linked to more than one C++ library More than one version of libstdc++ was used during compilation Generally the second version of C++ used comes from a binary-only implementation of libGL The problem does not occur when linking your library with a C++ application, only with a C application The "solution" is to explicitly link your library with libstdc++ and possibly also with libGL, forcing the order of linking. After trying many combinations with my code, the only solution that I found that works is the LD_PRELOAD="libGL.so libstdc++.so.6" ruby scriptname option. That is, none of the compile-time linking solutions made any difference. My understanding of the issue is that the C++ runtime is not being properly initialized. By forcing the order of linking you bootstrap the initialization process and it works. The problem occurs only with C applications calling C++ libraries because the C application is not itself linking to libstdc++ and is not initializing the C++ runtime. Because using SWIG (or boost::python) is a common way of calling a C++ library from a C application, that is why SWIG often comes up when researching the problem. Is anyone out there able to give more insight into this problem? Is there an actual solution or do only workarounds exist? Thanks.
Following Michael Dorgan's suggestion, I'm copying my comment into an answer: Found the real cause of the problem. Hopefully this will help someone else encountering this bug. You probably have some static data somewhere that is not being properly initialized. We did, and the solution was in boost-log for our code base. https://sourceforge.net/projects/boost-log/forums/forum/710022/topic/3706109. The real problem is the delay loaded library (plus statics), not the potentially multiple versions of C++ from different libraries. For more info: http://parashift.com/c++-faq-lite/ctors.html#faq-10.13 Since encountering this problem and its solution, I've learned that it's important to understand how statics are shared or not shared between your statically and dynamically linked libraries. On Windows this requires explicitly exporting the symbols for the shared statics (including things like singletons meant to be accessed across different libraries). The behavior is subtly different between each of the major platforms.
2,778,271
2,778,288
compiling a c++ program including mysql
I'm new to gcc, and trying to compile a c++ program which includes mysql.h using the command: g++ -o test test.cpp -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql It works without issue, but I was wondering if someone could explain the arguments to me. I don't like using commands I don't understand. Thanks
-o test means the output file is to be named "test". test.cpp is your source file, of course. -L/usr/include/mysql means to look for libraries in /usr/include/mysql, as well as in the usual link path. (It probably isn't finding any libraries here; my libmysqlclient.a is in the standard library directory /usr/lib. So I don't think you need this option.) -lmysqlclient means to link with the mysqlclient library (actually named libmysqlclient.a) -I/usr/include/mysql means to look for #include files in /usr/include/mysql, as well as in the usual include path.
2,778,289
2,778,337
struct size is different from typedef version?
I have the following struct declaration and typedef in my code: struct blockHeaderStruct { bool allocated; unsigned int length; }; typedef struct blockHeaderStruct blockHeader; When I do sizeof(blockheader), I get the value of 4 bytes back, but when I do sizeof(struct blockHeaderStruct), I get 8 bytes. Why is this happening? Why am I not getting 5 back instead?
Looking at the definition of your struct, you have 1 byte value followed by 4 byte Integer. This integer needs to be allocated on 4 byte boundary, which will force compiler to insert a 3 byte padding after your 1 byte bool. Which makes the size of struct to 8 byte. To avoid this you can change order of elements in the struct. Also for two sizeof calls returning different values, are you sure you do not have a typo here and you are not taking size of pointer or different type or some integer variable.
2,778,352
2,778,357
Template Child Class Overriding a Parent Class's Virtual Function
The below code compiles with gcc v4.3.3 and the templated child class seems to be overriding a virtual function in the parent, but doesn't that break the rule that you cannot have a virtual template function? Or is something else happening that I don't understand? class BaseClass { public: virtual void Func(int var) { std::cout<<"Base int "<<var<<std::endl; } virtual void Func(double var) { std::cout<<"Base double "<<var<<std::endl; } }; template <class TT> class TemplateClass : public BaseClass { public: using BaseClass::Func; virtual void Func(TT var) { std::cout<<"Child TT "<<var<<std::endl; } }; int main(int argc, char **argv) { BaseClass a; TemplateClass<int> b; BaseClass *c = new TemplateClass<int>; int intVar = 3; double doubleVar = 5.5; a.Func(intVar); a.Func(doubleVar); b.Func(intVar); b.Func(doubleVar); c->Func(intVar); c->Func(doubleVar); delete c; } This then outputs: Base int 3 Base double 5.5 Child TT 3 Base double 5.5 Child TT 3 Base double 5.5 as I hoped, but I'm not sure why it works.
A class template may have virtual member functions. A member function template cannot be virtual. That is, the following is invalid: class C { public: template <typename T> virtual void f(); }; In addition, if a derived class has a member function template with the same name as a virtual function in a base class, it does not override the virtual function. So, if TemplateClass::Func had been a member function template, e.g., template <typename T> void Func(T var) { /* ... */ } it would not have overridden BaseClass::Func.
2,778,578
2,778,731
What are pointers to class members used for?
I have read about pointers to class members, but I have never seen them being used in any practical applications. Can someone explain what are the use cases of such pointers? Is it really necessary to have such pointers? Eg. class abc { public: int a; abc(int val) { a = val; } }; int main() { int abc::*data; abc obj(5); data = &abc::a; cout << "Value of a is " << obj.*data << endl; return 0; } In the above eg. why is the value of 'a' accessed in this manner? What is the advantage of using pointers to class members?
The biggest advantage of a pointer-to-member or pointer-to-member-function is that you don't have to bind to a specific instance right away don't need to place any restrictions on the member names, only the type has to match. This can be used for e.g. call-backs or abstract algorithms: std::map<int,int> m; m.insert(std::make_pair(1,2)); m.insert(std::make_pair(3,4)); m.insert(std::make_pair(5,6)); std::ptrdiff_t s = std::count_if(m.begin(), m.end(), boost::bind(&std::map<int,int>::value_type::first, _1) > 2); std::cout << s << std::endl; // 2 Note that Boost.Bind, Boost.Function and their TR1 equivalents already encapsulate that nicely for you. To a certain degree the current standard also includes tools like std::mem_fun in <functional>.
2,778,621
2,778,640
Can I use C++/CLI (.NET Winforms/WPF ) to provide GUI for app written in native C & C++
I've an app written C & C++. Now, I need to provide a GUI for this app. MFC is the best option for me. But I'm not familiar with MFC. So can I use .NET to build GUI for this? If so, How? Please be clear. If I can use .NET I guess I can use WPF too right?
You can technically write a GUI in C++/CLI, but I would highly discourage it. C++/CLI is good for writing .NET wrappers around native C++ and exposing it to other .NET languages, but not much else. In your case, if you're really set on using WinForms/WPF, then I would suggest using C++/CLI to create a wrapper around your C++ code and then building the actual GUI in C#. Otherwise, a C++ library like Qt or wxWidgets would also suffice for doing a "native" C++ GUI. Here's a quick introduction to C++/CLI. This is a quick-start guide for getting started with C++/CLI. Once you build a C++/CLI DLL, you can just add it as a reference to your C# project and It Just Works(tm).
2,778,889
2,778,951
Difference in behaviour (GCC and Visual C++)
Consider the following code. #include <stdio.h> #include <vector> #include <iostream> struct XYZ { int X,Y,Z; }; std::vector<XYZ> A; int rec(int idx) { int i = A.size(); A.push_back(XYZ()); if (idx >= 5) return i; A[i].X = rec(idx+1); return i; } int main(){ A.clear(); rec(0); puts("FINISH!"); } I couldn't figure out the reason why the code gives a segmentation fault on Linux (IDE used: Code::Blocks) whereas on Windows (IDE used: Visual C++) it doesn't. When I used Valgrind just to check what actually the problem was, I got this output. I got Invalid write of size 4 at four different places. Then why didn't the code crash when I used Visual C++? Am I missing something?
The recursive call to rec() might modify the vector while you're assigning a value to it. What happens if you replace A[i].X = rec(idx+1); with int tmp = rec(idx+1); A[i].X = tmp; ? Also, just to summarize the useful comments: the operand evaluation order of a = operation is unspecified and since the vector wasn't preallocated, several resizes can occur during a recursive call to rec(), thus invalidating any iterator to values in the vector.
2,779,155
2,779,191
template; Point<2, double>; Point<3, double>
I want to create my own Point struct it is only for purposes of learning C++. I have the following code: template <int dims, typename T> struct Point { T X[dims]; Point(){} Point( T X0, T X1 ) { X[0] = X0; X[1] = X1; } Point( T X0, T X1, T X2 ) { X[0] = X0; X[1] = X1; X[2] = X2; } Point<dims, int> toint() { //how to distinguish between 2D and 3D ??? Point<dims, int> ret = Point<dims, int>( (int)X[0], (int)X[1]); return ret; } std::string str(){ //how to distinguish between 2D and 3D ??? std::stringstream s; s << "{ X0: " << X[0] << " | X1: " << X[1] << " }"; return s.str(); } }; int main(void) { Point<2, double> p2d = Point<2, double>( 12.3, 45.6 ); Point<3, double> p3d = Point<3, double>( 12.3, 45.6, 78.9 ); Point<2, int> p2i = p2d.toint(); //OK Point<3, int> p3i = p3d.toint(); //m??? std::cout << p2d.str() << std::endl; //OK std::cout << p3d.str() << std::endl; //m??? std::cout << p2i.str() << std::endl; //m??? std::cout << p3i.str() << std::endl; //m??? char c; std::cin >> c; return 0; } of couse until now the output is not what I want. my questions is: how to take care of the dimensions of the Point (2D or 3D) in member functions of the Point? many thanks in advance Oops
Your dimensions are fixed at compile time, by the template arguemnt dims, so you can iterate over them: std::string str(){ //how to distinguish between 2D and 3D ??? std::stringstream s; s << "{ "; std::copy( X, X+dims, std::ostream_iterator<T>( s, "|") ); s << " }"; return s.str(); } Also, you can provide a constructor in terms of the dims: Point( const T (&c) [dims] ){ std::copy( c, c+dims, X ); } This allows for code like double[] d={1,2,3}; Point<3,double> p(d);, which puts the decision on the number of arguments elsewhere. For the 'cast-to-point-of-ints' constructor you just can use Point as the argument: Point<dims,int> toint() const { Point<dims,int> result; std::copy( X, X+dims, result.X ); return result; }
2,779,294
2,785,413
Scaling a CBitmap - what am I doing wrong?
I've written the following code, which attempts to take a 32x32 bitmap (loaded through MFC's Resource system) and turn it into a 16x16 bitmap, so they can be used as the big and small CImageLists for a CListCtrl. However, when I open the CListCtrl, all the icons are black (in both small and large view). Before I started playing with resizing, everything worked perfectly in Large View. What am I doing wrong? // Create the CImageLists if (!m_imageListL.Create(32,32,ILC_COLOR24, 1, 1)) { throw std::exception("Failed to create CImageList"); } if (!m_imageListS.Create(16,16,ILC_COLOR24, 1, 1)) { throw std::exception("Failed to create CImageList"); } // Fill the CImageLists with items loaded from ResourceIDs int i = 0; for (std::vector<UINT>::iterator it = vec.begin(); it != vec.end(); it++, i++) { CBitmap* bmpBig = new CBitmap(); bmpBig->LoadBitmap(*it); CDC bigDC; bigDC.CreateCompatibleDC(m_itemList.GetDC()); bigDC.SelectObject(bmpBig); CBitmap* bmpSmall = new CBitmap(); bmpSmall->CreateBitmap(16, 16, 1, 24, 0); CDC smallDC; smallDC.CreateCompatibleDC(&bigDC); smallDC.SelectObject(bmpSmall); smallDC.StretchBlt(0, 0, 32, 32, &bigDC, 0, 0, 16, 16, SRCCOPY); m_imageListL.Add(bmpBig, RGB(0,0,0)); m_imageListS.Add(bmpSmall, RGB(0,0,0)); } m_itemList.SetImageList(&m_imageListS, LVSIL_SMALL); m_itemList.SetImageList(&m_imageListL, LVSIL_NORMAL);
Make sure you deselect the CBitmaps after using them: // Select the objects CBitmap* ret1 = bigDC.SelectObject(bmpBig); CBitmap* ret2 = smallDC.SelectObject(bmpSmall); ... // Do the painting ... // Deselect bigDC.SelectObject(ret1); smallDC.SelectObject(ret2);
2,779,316
2,779,452
behaviour of the implicit copy constructor / assignment operator
I have a question regarding the C++ Standard. Suppose you have a base class with user defined copy constructor and assignment operator. The derived class uses the implicit one generated by the compiler. Does copying / assignment of the derived class call the user defined copy constructor / assignment operator? Or do you need to implement user defined versions that call the base class? Thank you for your help.
If a derived class does not declare a copy constructor, and implicit one will be declared (12.8/4 "Copying class objects") - even if the base class has a user-delcared and defined copy constructor. If the base class has a user-defined copy constructor in this case, that base class sub-object is copied using that user-defined copy ctor (12.8/8). Similarly for copy assignment operators (12.8/10 and 12.8.13). So you do not necessarily need to implement user defined versions that call the base class if the derived class doesn't need a user-defined copy ctor or copy assignment operator for 'its own stuff'. However, if the derived class does declare and define its own copy ctor/copy assignment operator, then those user-defined implementations are responsible for doing the right thing as far as the base class sub-object is concerned - that is no longer handled by the compiler automatically.
2,779,345
2,779,363
C++ stack in Objective-C++
I'd like to use a C++ stack type in Objective-C, but I'm running into some issues. Here's a sample of what I would like to do: #import <stack> #import <UIKit/UIKit.h> @interface A : NSObject { stack<SEL> selectorStack; } @end Unfortunately, this doesn't compile. After messing around with the code for a while and trying different things, I can't seem to find a way to accomplish this. Can somebody tell me the best way to use a C++ stack within an Objective-C object or if it's even possible? Thanks. UPDATE: Well, KennyTM's answer worked on my example file, but for some reason when I tried to rename the class it quit working. Here's the code I have right now: #import <stack> #import <UIKit/UIKit.h> @interface MenuLayer : NSObject { std::stack<SEL> selectorStack; } @end The compiler spits out the following errors: stack: No such file or directory expected specifier-qualifier-list before 'std'
Have you tried @interface A : NSObject { std::stack<SEL> selectorStack; }
2,779,469
5,054,690
Can I use dtsearch in C++ under linux, if yes what APIshould i use?
I want to use dtsearch in my desktop application written in C++ and Gtkmm. Can i have any API or link to the API to do my thing.
If you are talking about dtSearch Desktop, the Windows end-user product, it is not intended or licensed to be used via the API. The dtSearch Engine for Linux (x32 or x64) on the other hand is a developer product and has C++ and Java APIs; it includes file filters for all popular file types, can search multiple indexes at the same time, each holding over 1 Tbyte. Features natural language as well as complex Boolean searching and regular expression searching. At $2500 for a three-server license (includes one year of technical support) it is probably overkill if you just have a single Desktop application to run, but for heavy duty searching inside a datacentre it's a no brainer. Fully functional evaluation downloads at www.dtsearch.com
2,779,543
2,797,924
How to create GIF file from other format file in C++
I want to create 2 bits per pixel GIF files in VC environment from a TIFF file. Is there any free library or maybe source that could help me? Or how can I do it myself?
You can use either OpenIL ( http://openil.sourceforge.net/ ), which is a C library, or if you really want a C++ only solution, Magick++ ( http://www.imagemagick.org/www/Magick++/ )
2,779,570
2,780,482
How did it happen that "static" denotes a function/variable without external linkage in C and C++?
In C static can mean either a local variable or a global function/variable without external linkage. In C++ it can also mean a per-class member variable or member function. Is there any reference to how it happened that the static keyword that seems totally irrelevant to lack of external linkage is used to denote lack of external linkage?
static is a storage specifier. The word "static" means unchanging. "Storage" refers to where the object is in memory, i.e. its address. An object with static storage resides at a constant address. It just so happens that an object with extern storage also has a constant address. Due to the way C and C++ programs are linked, it's a necessity. And because extern happens to be the least surprising behavior, it's also the default. If you think about it in terms of extern being an extra feature on top of static, I think it makes a bit more sense. It is a bit stupid to declare a function static, since there's no alternative in any fully-compiled language, but the address of a function is static even if it's not externally visible. The really inconsistent part, then, is that class members which get shared between different compilation units must be declared static, not extern…
2,779,804
2,779,866
Input accepting char when it should be string?
I am new to C++ and am making a simple text RPG, anyway, The scenario is I have a "welcome" screen with choices 1-3, and have a simple IF statement to check them, here: int choice; std::cout << "--> "; std::cin >> choice; if(choice == 1) { //.. That works fine, but if someone enters a letter as selection (instead of 1, 2 or 3) it'll become "-392493492"or something and crash the program. So I came up with: char choice; std::cout << "--> "; std::cin >> choice; if(choice == 1) { //.. This works kinda fine, but when I enter a number it seems to skip the IF statements completely.. Is the char "1" the same as the number 1? I get a compiler error with this (ISO-CPP or something): if(choice == "1") So how on earth do I see if they entered 1-3 correctly!?
Unfortunately 1 and '1' are not the same. Look up your favorite ASCII table to know the integer value that represents the character "1" and you'll see it for yourself: '1' is mapped to 49. There is another issue with this code "" denotes a C-string (const char*) whereas '' denotes a single character. Here is your code reworked: char choice = 0; if (cin >> choice) // check success { switch(choice) // choose { case '1': { /**/ break; } case '2': { /**/ break; } case '3': { /**/ break; } default: cout << choice << " is not a valid choice, please press 1, 2 or 3 and Enter" << endl; } } I switched to switch because it's more natural than a chain of else-if for generic enumeration.
2,779,901
2,783,661
Asynchronous event loop design and issues
I'm designing event loop for asynchronous socket IO using epoll/devpoll/kqueue/poll/select (including windows-select). I have two options of performing, IO operation: Non-blocking mode, poll on EAGAIN Set socket to non-blocking mode. Read/Write to socket. If operation succeeds, post completion notification to event loop. If I get EAGAIN, add socket to "select list" and poll socket. Polling mode: poll and then execute Add socket to select list and poll it. Wait for notification that it is readable writable read/write Post completion notification to event loop of sucseeds To me it looks like first would require less system calls when using in normal mode, especially for writing to socket (buffers are quite big). Also it looks like that it would be possible to reduce the overhead over number of "select" executions, especially it is nice when you do not have something that scales well as epoll/devpoll/kqueue. Questions: Are there any advantages of the second approach? Are there any portability issues with non-blocking operations on sockets/file descriptors over numerous operating systems: Linux, FreeBSD, Solaris, MacOSX, Windows. Notes: Please do not suggest using existing event-loop/socket-api implementations
I'm not sure there's any cross-platform problem; at the most you would have to use Windows Sockets API, but with the same results. Otherwise, you seem to be polling in either case (avoiding blocking waits), so both approaches are fine. As long as you don't put yourself in a position to block (ex. read when there's no data, write when buffer's full), it makes no difference at all. Maybe the first approach is easier to code/understand; so, go with that. It might be of interest to you to check out the documentation of libev and the c10k problem for interesting ideas/approaches on this topic.
2,780,301
2,780,456
Why would you use umask?
I am reading some source code and I found this statement at the very beginning of the main routine: umask(077); What could be the reason for that? The man page (man 2 umask) states: umask -- set file creation mode mask This clearing allows each user to restrict the default access to his files But is not clear to me why would anyone do that? as a shortcut ?
Setting umask(077) ensures that any files created by the program will only be accessible to their owner (0 in first position = all permissions potentially available) and nobody else (7 in second/third position = all permissions disallowed to group/other).
2,780,302
2,787,195
Deny access to run certain installed software for users
I have a list of installed software, obtained from WMI class select * from Win32_Product. I'd like to deny execution rights for some users on certain software like so: find the path to installed software recursively remove execution rights I find the path to installed software from Win32_Product InstallLocation column. But the PROBLEM is that not all rows in Win32_Product have a value for InstallLocation. What can I do to overcome this? Is there somewhere in registry where I can find this path?
In general, no. The extreme edge case is a Firefox installation on an USB disk. It will leave no trace in the registry or Win32_Product InstallLocation. The root cause is that Win32_Product InstallLocation has no location when the path is not in the registry. They're essentially 2 views on the same data. There's also the specialized problem that a certain product might not even need execution rights. For instance, if an application is written in Perl, the installed "executable" might be a .pl file. Yet the Win32 process created will the executable registered for the .pl extension, i.e. the Perl interpreter.
2,780,304
2,780,641
How to Track Emitted Signals in QT?
Is there any way to observe all signals which are emitted? PS. Of course we can write slots for all signals, but that is not I want.
What do you mean by observing? Do you need real time feedback on console, or is logging to file on program exit enough? If you need real time feedback on console, you can check then implementation of QTest. There is a -vs command line switch (Qt doc) which enables all signals printout on console (or you can just run your QTest tests with -vs switch, if you need the signals info only in tests, not in actual application). The other way is to use QSignalSpy class. It's not ideal however, because you need one spy per every signal, and you have to print the observed signals periodically (there are no notifications in QSignalSpy). Edit : The links were archived, but still accessible there : Qt Doc : http://web.archive.org/web/20120624024828/http://qt-project.org/doc/qt-4.8/qtestlib-manual.html QsignalSpy : http://web.archive.org/web/20141224031214/http://qt-project.org/doc/qt-4.8/qsignalspy.html Newer versions of these documents respectively for newer versions of QT on their official site.
2,780,314
2,780,362
Why are gettimeofday() intervals occasionally negative?
I have an experimental library whose performance I'm trying to measure. To do this, I've written the following: struct timeval begin; gettimeofday(&begin, NULL); { // Experiment! } struct timeval end; gettimeofday(&end, NULL); // Print the time it took! std::cout << "Time: " << 100000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl; Occasionally, my results include negative timings, some of which are nonsensical. For instance: Time: 226762 Time: 220222 Time: 210883 Time: -688976 What's going on?
You've got a typo. Corrected last line (note the number of 0s): std::cout << "Time: " << 1000000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl; BTW, timersub is a built in method to get the difference between two timevals.
2,780,365
2,780,397
Using read() directly into a C++ std:vector
I'm wrapping up user space linux socket functionality in some C++ for an embedded system (yes, this is probably reinventing the wheel again). I want to offer a read and write implementation using a vector. Doing the write is pretty easy, I can just pass &myvec[0] and avoid unnecessary copying. I'd like to do the same and read directly into a vector, rather than reading into a char buffer then copying all that into a newly created vector. Now, I know how much data I want to read, and I can allocate appropriately (vec.reserve()). I can also read into &myvec[0], though this is probably a VERY BAD IDEA. Obviously doing this doesn't allow myvec.size to return anything sensible. Is there any way of doing this that: Doesn't completely feel yucky from a safety/C++ perspective Doesn't involve two copies of the data block - once from kernel to user space and once from a C char * style buffer into a C++ vector.
Use resize() instead of reserve(). This will set the vector's size correctly -- and after that, &myvec[0] is, as usual, guaranteed to point to a continguous block of memory. Edit: Using &myvec[0] as a pointer to the underlying array for both reading and writing is safe and guaranteed to work by the C++ standard. Here's what Herb Sutter has to say: So why do people continually ask whether the elements of a std::vector (or std::array) are stored contiguously? The most likely reason is that they want to know if they can cough up pointers to the internals to share the data, either to read or to write, with other code that deals in C arrays. That’s a valid use, and one important enough to guarantee in the standard.
2,780,612
2,781,565
Outlook Add-in. How to manage Items Events
I'm doing an add-in for Outlook 2007 in C++. I need to capture the events like create, change or delete from the Outlook Items (Contact, Appointment, Tasks and Notes) but the only information/examples I've found are for Visual Basic so I don't know how to connect the event handler. Here is some information related: http://msdn.microsoft.com/en-us/library/bb208390(v=office.12).aspx Any help is welcome :) Thanks Update Sorry for taking this long to update, I've been out of town. I have some doubts/problems that you may know how to help. In my case, I'm taking this project that was started so I'm a bit confused about all this. I have the class OutlookAddin that derives from IDTExtensibility2. I also have this other class, called AutoSync, were I'd like to do all the methods when the event fires and so. An object of this class is initialized in OutlookAddin.cpp OnStartupComplete. According to your post MyClass should extends from IDispEventSimpleImpl<1 /*N*/, MyClass, &__uuidof(Outlook::ItemsEvents)> but which one of them? OutlookAddin or AutoSync ? Where I should put this code also? CComPtr<Outlook::MAPIFolder> folder; // get the folder you're interested in CComPtr<Outlook::_Items> items; hr = folder->get_Items(&items); hr = MyItemEvents::DispEventAdvise(items, &__uuidof(Outlook::ItemsEvents)); typedef IDispEventSimpleImpl<1 /*N*/, MyClass, &__uuidof(Outlook::ItemsEvents)> MyItemEvents; I've read the links you posted but still having these doubts... Update 2 This is more complicated to understand than I though in a first instance. So I have like this: OutlookAddin.h class OutlookAddin : public IDTExtensibility2, public IDispEventSimpleImpl<1, OutlookAddin, &__uuidof(Outlook::ItemEvents)> ... BEGIN_SINK_MAP(OutlookAddin) SINK_ENTRY_INFO(1, __uuidof(Outlook::ItemEvents), 0xf002, OutlookAddin::OnItemChange, &OnSimpleEventInfo) END_SINK_MAP() ... void __stdcall OnItemChange(); 'OnSimpleEventInfo' is defined like: extern _ATL_FUNC_INFO OnSimpleEventInfo; _ATL_FUNC_INFO OnSimpleEventInfo = {CC_STDCALL,VT_EMPTY,0}; then in OutlookAddin.cpp, OnConnection method: CComPtr<Outlook::MAPIFolder> folder; CComPtr<Outlook::_Items> items; OutlookWorker::GetInstance()->GetNameSpacePtr()->GetDefaultFolder(olFolderContacts, &folder); folder->get_Items(&items); DispEventAdvise(items, &__uuidof(Outlook::ItemsEvents)); being 'OutlookWorker::GetInstance()->GetNameSpacePtr()' the _NameSpacePtr where all the environment is kept. The expected behaviour here is to fire the function 'OnItemChange' from OutlookAddin class when an ContactItem is created/edited/deleted but that's not happening... I changed a little bit the structure to everything is in the main class OutlookAddin. Then on the function 'OnItemChange' I'll start the object of 'AutoSync' that I told you before. Anyway I'm following the articles you gave me, really useful, thank you. Do you still have any other suggestion for me? Thanks your patience.
Its been a while, but you should get these item events by advising for Folder.Items: CComPtr<Outlook::MAPIFolder> folder; // get the folder you're interested in CComPtr<Outlook::_Items> items; hr = folder->get_Items(&items); hr = MyItemEvents::DispEventAdvise(items, &__uuidof(Outlook::ItemsEvents)); Where your class MyClass derives from: IDispEventSimpleImpl<1 /*N*/, MyClass, &__uuidof(Outlook::ItemsEvents)> And MyItemEvents is: typedef IDispEventSimpleImpl<1 /*N*/, MyClass, &__uuidof(Outlook::ItemsEvents)> MyItemEvents; N identifies your sink here. Then there is the joy of the remaining macros to setup and the handler functions to implement - i refer you to this and this article for examples and to the dispinterface ItemsEvents that you can look up in oleview.exe. Regarding update 1: If you want to receive the events in AutoSync, implement the interface there - you are not required to sink the events to any specific instance. However, you know your design best :) I'd just personally keep as much logic out of the central addin class as possible. The registration code would go into some method of the class implementing the events then and called whenever it should start to receive events, while the typedef would be e.g. well placed in the class' declaration. Regarding update 2: From a quick glance it looks mostly right, but OnItemChange() takes one parameter - an IDispatch: _ATL_FUNC_INFO AtlCallDispatch = {CC_STDCALL, VT_EMPTY, 1, {VT_DISPATCH}};
2,780,868
2,781,520
How to hook for particular windows message without subclassing?
Is there a way to hook for a particular windows message without subclassing the window. There is WH_GETMESSAGE but that seems create performance issues. Any other solutions apart from these which doesn't deteriorate performance?
AFAIK there's no better solution than what you mentioned. And, of course, subclassing the window is better than hooking all the messages of the thread. Let's think which path the message passes up until it's handled by the window: The message is either posted or sent to the window, either by explicit call to PostMessage/SendMessage or implicitly by the OS. Posted messages only: eventually the thread pops this message from the message queue (by calling GetMessage or similar), and then calls DispatchMessage. The OS invokes the window's procedure by calling CallWindowProc (or similar). The CallWindowProc identifies the window procedore associated with the window (via GetClassLong/GetWindowLong) The above procedure is called. Subclassing - means replacing the window procedure for the target window. This seems to be the best variant. Installing hook with WH_GETMESSAGE flag will monitor all the messages posted to the message queue. This is bad because of the following: Performance reasons. You'll get notified only for windows created in the specific thread You'll get notified only for posted messages (sent messages will not be seen) A "posted" message doesn't necessarily means "delivered". That is, it may be filtered by the message loop (thrown away without calling DispatchMessage). You can't see what the actual window does and returns for that message. So that subclassing seems much better. One more solution - in case your specific message is posted (rather than sent) you may override the message loop, and for every retrieved message you may do some pre/post-processing
2,781,015
2,781,088
value of enum members, when some members have user-defined values
enum ABC{ A, B, C=5, D, E }; Are D and E guaranteed to be greater than 5 ? Are A and B guaranteed to be smaller than 5 (if possible)? edit: What would happen if i say C=1
It is guaranteed by C++ Standard 7.2/1: The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are required. An enumerator-definition with = gives the associated enumerator the value indicated by the constant-expression. The constant-expression shall be of integral or enumeration type. If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.
2,781,089
2,781,149
Is there a convention for organizing the include/exports in a large C++ project?
In a large C++ solution, is there a best/standard way to separate the include files necessary to build an intermediary DLL and the include files which will be used by the DLL clients ? We have grouped all the include files in a folder called Interface (for DLL interface), but there the customers have to either include the Interface folder as a default include folder or type the full name as: #include "ProjectName/Interface/myinterface.h" Wouldn't it be better to create a separate folder called exports where I would create a folder called ProjectName and put the include files there ? So that the customers would be typing: #include "ProjectName/myinterface.h" If I do the thing right above, then should I keep the files within the solution and produce a post build event (I use Visual Studio 2k5) to copy the files into the "export" folder (/ProjectName/) ? Or is it better to just include directly the files from this folder within my project (this is more direct and has less chances to cause maintenance issues ? I am more looking for advice than for a definite solution. Thank you for reading this ! Anthony
If an interface could consist of more than one header, #include "ProjectName/Interface/header1.h" seems better to me.
2,781,323
2,781,338
Factory Method and Cyclic Dependency
Edit: Thanks folks, now I see my mistake. If I'm not wrong, because of its nature in factory method there is cyclic dependency: Base class needs to know subclasses because it creates them, and subclasses need to know base class. Having cyclic dependency is bad programming practice, is not it? Practically I implemented a factory, I have problem above, even I added #ifndef MYCLASS_H #define MYCLASS_H #endif I'm still getting Compiler Error C2504 'class' : base class undefined And this error disappers when I remove subclass include from base class header.
Solution 1: don't #include the derived class headers in the base class header, only in the base class cpp. The declaration of the factory method should not use the type of concrete classes returned, only the base type. Solution 2: use a separate factory class (or a factory method within a separate class) to create your objects. Then the cyclic dependency is totally eliminated. This is the preferred way.
2,781,339
2,781,537
Global qualification in a class declarations class-head
We found something similar to the following (don't ask ...): namespace N { struct A { struct B; }; } struct A { struct B; }; using namespace N; struct ::A::B {}; // <- point of interest Interestingly, this compiles fine with VS2005, icc 11.1 and Comeau (online), but fails with GCC: global qualification of class name is invalid before '{' token From C++03, Annex A, it seems to me like GCC is right: the class-head can consist of nested-name-specifier and identifier nested-name-specifier can't begin with a global qualification (::) obviously, neither can identifier ... or am i overlooking something?
I think you are getting it right: GCC implements the standard to the letter in this case, while the others implement it less strict (have a look at issue #355). You could do the following to work-around the limitation of the syntax struct identity< ::A >::type::B {}; Or you use an explicit named typedef typedef ::A AHidden; struct AHidden::B { }; Or, of course, you exchange the order of using namespace and the nested class definition. Notice that Annex A is informative only. The normative text is at clauses 5.1/7 and 9.
2,781,425
2,781,912
what is required to get intellisense for Gtkmm using editor Geany!
i want to get the intellisense in GTkmm application, similarly as we get in dot net under windows. However this time i am using Linux, C++, Gtkmm and Geany as my editor. Please guide how to get the intellisense. Moreover, if any kind of editor supports the property of intellisense, please mention that also. Thanks and Regards Owais Masood
Geany automatically indexes your open files for auto-completion, but if you want it to index some library or API, you have to create a global tags file like it describes here in the documentation. I have had mixed results getting this to work completely and correctly though. I used to use Geany on Linux, but I have moved to QtCreator. Even though it has an emphasis on Qt, you can use it on any C or C++ project (you just have to specify your own build process or do it outside the IDE). The editor is one of the best I've used on Linux and the autocompletion works great without a whole lot of configuration. Also check out my answer here on how to set the include paths. Anything in the include paths will be indexed for autocompletion automatically.
2,781,486
2,781,805
C++ calculation evaluated to 0
I'm parsing a file and trying to decode coordinates to the right unit. What happens is that this code is evaluated to 0. If I type it into gdb the result is correct. int pLat = (int)( (argv[6].data() == "plus" ? 1 : -1) * ( atoi(argv[7].data()) + atoi(argv[8].data()) / 60. + atoi(argv[9].data()) / 36000.) * 2.145767 * 0.0001); I'm doing a (degrees, minutes, tenth seconds) conversion to wgs. Is there something wrong with this code?
Assuming you're trying to convert degrees to WGS84 coordinates, there are two errors: The conversion factor is out by a factor of 10 (180/223 is approximately 2.145767*10-5, and you have 2.145767*10-4) You are multiplying by the conversion factor when you should be dividing by it. This will give you a very small number, and the cast to int will give zero.
2,781,798
2,781,846
const TypedeffedIntPointer not equal to const int *
I have the following C++ code: typedef int* IntPtr; const int* cip = new int; const IntPtr ctip4 = cip; I compile this with Visual Studio 2008 and get the following error: error C2440: 'initializing' : cannot convert from 'const int *' to 'const IntPtr' Clearly my understanding of typedefs is not what is should be. The reason I'm asking, I'm storing a pointer type in a STL map. I have a function that returns a const pointer which I would like to use to search in the map (using map::find(const key_type&). Since const MyType* and const map<MyType*, somedata>::key_type is incompatible, I'm having problems. Regards Dirk
When you write const IntPtr ctip4, you are declaring a const-pointer-to-int, whereas const int * cip declares a pointer-to-const-int. These are not the same, hence the conversion is impossible. You need to change the declaration/initialization of cip to int * const cip = new int; To resolve this issue in your example, you need to either change the key type of the map to const MyType * (whether or not it makes sense depends on your application, but I think that changing a MyType object via a pointer used as key in the map is unlikely), or fall back to const_casting the parameter to find: #include <map> int main() { const int * cpi = some_func(); std::map<const int *, int> const_int_ptr_map; const_int_ptr_map.find(cpi); //ok std::map<int *, int> int_ptr_map; int_ptr_map.find(const_cast<int *>(cpi)); //ok }
2,781,863
2,781,940
C++ Pass a hidden arg to a class constructor?
I would like to define a class that accept the pointer to it's parent class as an Argument, but would it be possible to somehow pass it without needing to pass it directly such as: class Child { public: Child(Parent* hiddenArg); }; class Parent { public: Child myChild; }; I know this is weird, but I am making my own Signal/Slot implementation and Child would be a signal defined, but I would like to get the parent so I can use it's Event Dispatcher...
You can't do it automatically, but all you need to do is construct myChild in the Parent constructor like this: Parent::Parent() : myChild(this) // passing pointer to parent to child constructor { } Note some compilers will emit a warning for that code: it thinks you're using the this pointer before the Parent class is fully constructed. As long as you only store the pointer in the Child constructor and don't use it, you're OK. You may legitimately want to disable the warning (try not to disable warnings project-wide though - just around the affected area).
2,781,899
2,781,916
How to find whether an element exists in std::map?
My use case: map<string, Car> cars; bool exists(const string& name) { // somehow I should find whether my MAP has a car // with the name provided return false; } Could you please suggest the best and the most elegant way to do it in C++? Thanks.
Sure, use an iterator map<string,Car>::const_iterator it = cars.find(name); return it!=cars.end();
2,782,092
2,782,127
Casting a container of shared_ptr
I have a method void foo(list<shared_ptr<Base>>& myList); Which I'm trying to call with a two different types of lists, one of DerivedClass1 and one of DerivedClass2 list<shared_ptr<DerivedClass1>> myList1; foo(myList1); list<shared_ptr<DerivedClass2>> myList2; foo(myList2); However this obviously generates a compiler error error: a reference of type "std::list<boost::shared_ptr<Base>, std::allocator<boost::shared_ptr<Base>>> &" (not const-qualified) cannot be initialized with a value of type "std::list<boost::shared_ptr<DerivedClass1>, std::allocator<boost::shared_ptr<DerivedClass1>>>" Is there any easy way to cast a container of shared_ptr? Of alternate containers that can accomplish this? Update: Thanks to everyone who responded. Working within the confines of the language, it seems the best way to go while keeping the method 'as-is' is to use a container of shared_ptr and pass exactly that in (creating a new list at the call site). I guess I pretty much already knew this, but I remembered reading about other parts of the boost library dealing with containers of shared_ptr and thought maybe it was solved more elegantly by someone else already. From my own further research however these seem to be geared more towards reducing overhead of shared_ptr in cases where a number of pointers are owned exclusively (therefore requiring a single lock per container rather than one per object in the container). Thanks again, you guys are all awesome!
You can't cast a container of one type to a container of another type. There are a few ways to create a new container from an existing container, if the type of object stored by the existing container is convertible to the type of object stored by the new container: You can use std::copy to do the conversion element-by-element: list<shared_ptr<Base> > baseList; list<shared_ptr<Derived> > derivedList; std::copy(derivedList.begin(), derivedList.end(), std::back_inserter(baseList)); You can also directly construct baseList using the begin and end iterators from derivedList: list<shared_ptr<Base> > baseList(derivedList.begin(), derivedList.end()); If your function can take a const reference instead, you can construct a temporary in the function call: typedef list<shared_ptr<Base> > BaseList; foo(BaseList(derivedList.begin(), derivedList.end()));
2,782,311
2,782,634
WM_NCHITTEST and secondary monitor to left of primary monitor
The described setup with 2nd monitor to left of primary causes WM_NCHITTEST to send negative values which is apparently not supported according to this post. I have a custom control written in win32 that is like a Group control. It has a small clickable area. No MOUSE events are coming to my control when the window containing the custom control lies on a second monitor to the left of the primary monitor. SPY++ shows WM_NCHITTEST messages but no Mouse messages. When window is moved to primary monitor or secondary monitor is positioned to right of primary (all points are positive) then everything works fine. Below is how the WM_NCHITTEST is handled in my custom control. In general I need it to return HTTRANSPARENT so as not to obscure other controls placed inside of it. Anybody have any suggestions what funky coordinate translation I need to do and what to return in response to WM_NCHITTEST to get Mouse messages translated and sent to my control in the case where it is on a 2nd monitor placed to the left of the primary monitor? case WM_NCHITTEST: { POINT Pt = {LOWORD(lP), HIWORD(lP)}; int i; ScreenToClient (hWnd, &Pt); if (PtInRect (&rClickableArea, Pt)) { return(DefWindowProc( hWnd, Msg, wP, lP )); } } lReturn = HTTRANSPARENT; break;
You must use GET_X_LPARAM and GET_Y_LPARAM macros to extract mouse coordinates. They will correctly return negative values, unlike LOWORD et al. which return unsigned values. POINT Pt = { GET_X_LPARAM(lP), GET_Y_LPARAM(lP) }; The rest of the code should be fine.
2,782,343
2,782,375
Customers angry, fighting unknown DLL dependencies
I'm a one man show developing a C++ Windows application for a customer. Over the past several months we've been running to the same problems with missing DLL dependencies on customer machines. Despite my best efforts something keeps going wrong and we get angry emails back. My boss and my boss's boss are angry with me and the customers aren't happy. I'm hoping you guys can help out and give suggestions/ideas on how to get the deliverables in order. Before some of the obvious: I have no test machine. That is, I can't replicate the customer environment nor attempt to install the app on a "clean" system to catch gotchas before shipping. I've tried using depends.exe to track down what versions of the DLLs my project is dependent upon. I'm shipping our code with the redistributables I've been able to find that way. After that it's an angry customer email waiting game. I do have access to a 64-bit machine and 32-bit machine to install new builds. It always works there. I'm required to use a third-party DLL which can not be registered (it's buggy as hell.) I'm not supposed to use Install Shield, any other automated installer, or write an install script. I provide written instructions on how to get the app installed (unzip, double click exe file.) I'm tired of taking heat for this stuff. What am I missing that I could be doing? What should I ask in terms of support from my employer? How should I ask for that support in a way that they'll provide it? Update: Virtual Machine torpedoed. They don't want me spending all of my times setting up and tearing down customer configurations. Instead, I'm now working with the customer to get a base configuration so that I know the exact machine set-up I'm supposed to target. If it's not up to that spec, I no longer have to care. At least something went somewhere... although I'd still like a test machine.
If you don't have a test machine, can you at least use a virtual machine with a clean Windows installation?
2,782,677
2,782,694
Unit testing a functions whose purposes is side effects
How would you unit test do_int_to_string_conversion? #include <string> #include <iostream> void do_int_to_string_conversion(int i, std::string& s) { switch(i) { case 1: s="1"; break; case 2: s="2"; break; default: s ="Nix"; } } int main(int argc, char** argv){ std::string little_s; do_int_to_string_conversion(1, little_s); do_int_to_string_conversion(2, little_s); do_int_to_string_conversion(3, little_s); }
I assume this is just an example. Why can't you assert on the value of little_s after each call? do_int_to_string_conversion(1, little_s); assert_are_equal("1", little_s);
2,782,725
2,782,742
Converting float values from big endian to little endian
Is it possible to convert floats from big to little endian? I have a big endian value from a PowerPC platform that I am sendING via TCP to a Windows process (little endian). This value is a float, but when I memcpy the value into a Win32 float type and then call _byteswap_ulongon that value, I always get 0.0000? What am I doing wrong?
simply reverse the four bytes works float ReverseFloat( const float inFloat ) { float retVal; char *floatToConvert = ( char* ) & inFloat; char *returnFloat = ( char* ) & retVal; // swap the bytes into a temporary buffer returnFloat[0] = floatToConvert[3]; returnFloat[1] = floatToConvert[2]; returnFloat[2] = floatToConvert[1]; returnFloat[3] = floatToConvert[0]; return retVal; }
2,782,915
2,782,968
What should I know about Structured Exceptions (SEH) in C++?
What important points about Structured Exceptions should every C++ developer know?
They are the Win32 equivalent to Unix signals, and let you catch CPU exceptions such as access violation, illegal instruction, divide by zero. With the right compiler options (/EHa for Visual C++), C++ exceptions use the same mechanism as stack unwinding works properly for both C++ (user) exceptions and SEH (OS) exceptions. Unlike C++ exceptions, SEH are not typed but all share the same data structure which has an exception code (the cause) and additional information on what code faulted and what the CPU registers held at the time of the fault. See GetExceptionCode and GetExceptionInformation for more details on this. Also, SEH has "first-chance" handling, which allows you to log or otherwise handle the exception before unwinding destroys all the local variables.
2,783,239
2,783,258
Increment and Decrement operators
How are the below valid and invalid as shown and what do they mean. When would such a situation arise to write this piece of code. ++x = 5; // legal --x = 5; // legal x++ = 5; // illegal x-- = 5; // illegal
The postfix (x++/x--) operators do not return an lvalue (a value you can assign into). They return a temporary value which is a copy of the value of the variable before the change The value is an rvalue, so you could write: y = x++ and get the old value of x
2,783,269
2,783,978
QSqlQuery UPDATE/INSERT DateTime with server's time (eg CURRENT_TIMESTAMP)
I am using QSqlQuery to insert data into a MySQL database. Currently all I care about is getting this to work with MySQL, but ideally I'd like to keep this as platform-independent as possible. What I'm after, in the context of MySQL, is to end up with code that effectively executes something like the following query: UPDATE table SET time_field=CURRENT_TIMESTAMP() WHERE id='5' The following code is what I have attempted, but it fails: QSqlQuery query; query.prepare("INSERT INTO table SET time_field=? WHERE id=?"); query.addBindValue("CURRENT_TIMESTAMP()"); query.addBindValue(5); query.exec(); The error I get is: Incorrect datetime value: 'CURRENT_TIMESTAMP()' for column 'time_field' at row 1 QMYSQL3: Unable to execute statement. I am not surprised as I assume Qt is doing some type checking when it binds values. I have dug through the Qt documentation as well as I know how, but I can't find anything in the API designed specifically for supporting MySQL's CURRENT_TIMESTAMP() function, or that of any other DBMS. Any suggestions?
I have no SQL server to test here, but addBindValue() binds Qt's data types. You should put the timestamp function direct into the query QSqlQuery query; query.prepare("INSERT INTO table SET time_field=CURRENT_TIMESTAMP() WHERE id=?"); query.addBindValue(5); query.exec(); should do the trick.
2,783,603
2,783,626
QT Creator simple application
I'm developping a very simple app on my Ubuntu using QtCreator. It's a console application and I want the user to enter its name, and then I display his name. Here is the code : #include <iostream> int main(int ArgC, char* ArgV[]) { char Name[1000]; std::cout << "Type your name : "; std::cin >> Name; std::cout << "Hello " << Name << "\n"; return 0; } When running this app with QtCreator, the string "Type your name :" is displayed in the 'Application Output' tab. But if I type some text and press the enter key, nothing is happening. What's wrong ?
Looks like "Application Output" tab doesn't support Input. Try to start your application in standalone console.
2,783,612
2,783,652
Listing C/C++ functions (Code analysis in Unix)
Whether we're maintaining unfamiliar code or checking out the implementation details of an Apache module it can help if we can quickly traverse the code and build up an overview of what we're looking at. Grep serves most of my daily needs but there are some cases where it just wont do. Here's a common example of how it can help. To find the definition of a PHP function I'm interested in I can type this at the command line: grep -r "function myfunc" . This could be adapted very quickly to C or C++ if we know the return type, but things become more complicated if, say, I want to list every method that my class provides: grep "function " ./src/mine.class.php Since there's no single keyword that denotes a function or method in C++ and because it's generally more complex syntax, I think I'd need some kind of static code analysis tool, smart use of the C Preprocessor or blind faith the coder followed strict code guidelines (# of whitespace, position of curlies etc) to get these sorts of results. What would you recommend?
Run it through doxygen. It will complain about lack of commenting , but it will still produce call graphs and list all the functions. Presented in HTML with links to follow code paths. doxygen
2,783,786
2,783,833
C++: Everytime I read in by fstream I got 1 extra character at the end
Everytime I read in by fstream I got 1 extra character at the end, How can I avoid this? EDIT: ifstream readfile(inputFile); ofstream writefile(outputFile); char c; while(!readfile.eof()){ readfile >> c; //c = shiftChar(c, RIGHT, shift); writefile << c; } readfile.close(); writefile.close();
This typically results from testing for the end of file incorrectly. You normally want to do something like: while (infile>>variable) ... or: while (std::getline(infile, whatever)) ... but NOT: while (infile.good()) ... or: while (!infile.eof()) ... The first two do a read, check whether it failed, and if so exit the loop. The latter two attempt a read, process what's now in the variable, and then exit the loop on the next iteration if the previous attempt failed. On the last iteration, what's in the variable after the failed read will normally be whatever was in it previously, so loops like either of the second two will typically appear to process the last item in the file twice. To copy one file to another easily, consider using something like this: // open the files: ifstream readfile(inputFile); ofstream writefile(outputFile); // do the copy: writefile << readfile.rdbuf(); This works well for small files, but can slow down substantially for a larger file. In such a case, you typically want to use a loop, reading from one file and writeing to the other. This also has possibilities for subtle errors as well. One way that's been tested and generally work reasonably well looks like this: std::ifstream input(in_filename, std::ios::binary); std::ofstream output(out_filename, std::ios::binary); const size_t buffer_size = 512 * 1024; char buffer[buffer_size]; std::size_t read_size; while (input.read(buffer, buffer_size), (read_size = input.gcount()) > 0) output.write(buffer, input.gcount());
2,783,814
2,784,176
C++ string sort like a human being?
I would like to sort alphanumeric strings the way a human being would sort them. I.e., "A2" comes before "A10", and "a" certainly comes before "Z"! Is there any way to do with without writing a mini-parser? Ideally it would also put "A1B1" before "A1B10". I see the question "Natural (human alpha-numeric) sort in Microsoft SQL 2005" with a possible answer, but it uses various library functions, as does "Sorting Strings for Humans with IComparer". Below is a test case that currently fails: #include <set> #include <iterator> #include <iostream> #include <vector> #include <cassert> template <typename T> struct LexicographicSort { inline bool operator() (const T& lhs, const T& rhs) const{ std::ostringstream s1,s2; s1 << toLower(lhs); s2 << toLower(rhs); bool less = s1.str() < s2.str(); //Answer: bool less = doj::alphanum_less<std::string>()(s1.str(), s2.str()); std::cout<<s1.str()<<" "<<s2.str()<<" "<<less<<"\n"; return less; } inline std::string toLower(const std::string& str) const { std::string newString(""); for (std::string::const_iterator charIt = str.begin(); charIt!=str.end();++charIt) { newString.push_back(std::tolower(*charIt)); } return newString; } }; int main(void) { const std::string reference[5] = {"ab","B","c1","c2","c10"}; std::vector<std::string> referenceStrings(&(reference[0]), &(reference[5])); //Insert in reverse order so we know they get sorted std::set<std::string,LexicographicSort<std::string> > strings(referenceStrings.rbegin(), referenceStrings.rend()); std::cout<<"Items:\n"; std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(std::cout, "\n")); std::vector<std::string> sortedStrings(strings.begin(), strings.end()); assert(sortedStrings == referenceStrings); }
Is there any way to do with without writing a mini-parser? Let someone else do that? I'm using this implementation: http://www.davekoelle.com/alphanum.html, I've modified it to support wchar_t, too.
2,784,262
2,784,304
Does a const reference class member prolong the life of a temporary?
Why does this: #include <string> #include <iostream> using namespace std; class Sandbox { public: Sandbox(const string& n) : member(n) {} const string& member; }; int main() { Sandbox sandbox(string("four")); cout << "The answer is: " << sandbox.member << endl; return 0; } Give output of: The answer is: Instead of: The answer is: four
Only local const references prolong the lifespan. The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor's argument n, and becomes invalid when the object n is bound to goes out of scope. The lifetime extension is not transitive through a function argument. §12.2/5 [class.temporary]: The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (§12.6.2 [class.base.init]) persists until the constructor exits. A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.
2,784,264
2,784,445
LocalAlloc and LocalRealloc usage
I have a Visual Studio 2008 C++ Windows Mobile 6 application where I'm using a FindFirst() / FindNext() style API to get a collection of items. I do not know how many items will be in the list ahead of time. So, I would like to dynamically allocate an array for these items. Normally, I would use a std::vector<>, but, for other reasons, that's not an option for this application. So, I'm using LocalAlloc() and LocalReAlloc(). What I'm not clear on is if this memory should be marked fixed or moveable. The application runs fine either way. I'm just wondering what's 'correct'. int count = 0; INFO_STRUCT* info = ( INFO_STRUCT* )LocalAlloc( LHND, sizeof( INFO_STRUCT ) ); while( S_OK == GetInfo( &info[ count ] ) { ++count; info = ( INFO_STRUCT* )LocalRealloc( info, sizeof( INFO_STRUCT ) * ( count + 1 ), LHND ); } if( count > 0 ) { // use the data in some interesting way... } LocalFree( info ); Thanks, PaulH Edit: Responders are (not unreasonably) getting hung up on the use of LocalAlloc() over other better options. So I will provide more context. This chunk of code is being executed from within a RAPI invokable DLL. So, in that context, it looks more like this: FOO_API int RapiInvokable_Foo( DWORD /*cbInput*/, BYTE* /*pInput*/, DWORD* pcbOutput, BYTE** ppOutput, IRAPIStream* /*pStream*/ ) { int count = 0; INFO_STRUCT* info = ( INFO_STRUCT* )LocalAlloc( LPTR, sizeof( INFO_STRUCT ) ); while( S_OK == GetInfo( &info[ count ] ) { ++count; info = ( INFO_STRUCT* )LocalRealloc( info, sizeof( INFO_STRUCT ) * ( count + 1 ), LHND ); } *ppOutput = ( BYTE* )info; *pcbOutput = sizeof( INFO_STRUCT ) * ( count + 1 ); return S_OK; } From the CeRapiInvoke() documentation: An application should allocate memory for the pInput parameter with the LocalAlloc function. The caller is responsible for freeing pInput. The system allocates memory for the ppOutput parameter. When the application is completed with the buffer, it should free the memory with the LocalFree function.
From what I can tell, LHND is not even a valid flag to use in the Windows Mobile version of LocalAlloc. When you call the non-mobile version of LocalAlloc with LMEM_MOVEABLE, the return type is not INFO_STRUCT*. The return type is HLOCAL — a handle to the memory that you've allocated. It's not a pointer itself, so it is incorrect to dereference it like a pointer. To get a pointer, you need to use LocalLock to tell the OS that it mustn't move the memory around for the time being. Consider what MSDN says about movable memory: The movable-memory flags LHND, LMEM_MOVABLE, and NONZEROLHND add unnecessary overhead and require locking to be used safely. They should be avoided unless documentation specifically states that they should be used. So, if you really must use LocalAlloc, then allocate fixed memory, not movable. That's the same behavior you'd get from calling plain old malloc. The LMEM_MOVEABLE flag means something different with LocalReAlloc. Whereas with LocalAlloc it specifies whether the memory is locked, with LocalReAlloc it specifies whether the function is allowed to move the memory in order to satisfy a request for a larger block of memory. If you don't include that flag with LocalReAlloc, then the function is restricted to changing the block's size in-place. If there's no room there, then the function will fail, even if there are larger blocks of memory available elsewhere in the heap. To get the effect of malloc, call LocalAlloc(LMEM_FIXED). To get the effect of realloc, call LocalReAlloc(LMEM_MOVEABLE). Include LMEM_ZEROINIT in either case if you wish. One thing to take away from all this seems to be that you should only use the flags that the documentation specifically says you can use for each function. For LocalAlloc, it doesn't mention LMEM_MOVEABLE, and for LocalReAlloc, it doesn't mention LPTR.
2,784,523
2,789,308
Is it possible to duplicate a GDI handle?
Or in my particular case a windows region (HRGN)? Updated: The problems is the following: I've a collection of objects, each of these objects can hold a HRGN. These region once acquired is released when the object is destroyed. Since some of those objects are stored in a std::vector I've to define an assignement operator. Until now I've just assigned those HRGN, but that is a bug. If I duplicate such objects each one of those will try to delete the same region, and one of those wil be using a non existent region.
Wrap each HRGN in a reference-counting object modeled after any smart pointer e.g. shared_ptr.
2,784,603
2,784,666
C++ fstream variable
please, what contains the fstream variable? A can find many tutorials on fstream, but no ona actually says what is the fstream file; declaration in the beginning. Thanks.
The fstream class is an object that handles file input and output. It is mostly equivalent to both an ifstream and ostream object in one, in that you can use it for both input and output. This tiny demonstration will create a file and write data to it. #include <fstream> using namespace std; int main() { fstream myFile; myFile.open("data.txt"); myFile << "This will appear in the file."; myFile.close(); } What is cool about fstream objects is that you can use them to read and write binary memory images to files (to protect your file's data from editing) and set various flags to control the way in which the fstream processes input and output. For example: This fstream is an output stream that clears fout.txt's data and writes in binary. fstream foutOne("fout.txt", ios::binary | ios::out | ios::trunc) This fstream is an output stream that does not clear fout.txt's data, but appends to the end of it instead, and writes in binary. fstream foutTwo("fout.txt", ios::binary | ios::out | ios::app) If I remember right, foutTwo will crash if fout.txt does not exist, while foutOne will not. You can (and should ALWAYS) check if the fstream loaded correctly immediately after opening a file like so: if(!foutTwo) { cout << "File open error!\n"; exit(EXIT_FAILURE); }
2,784,639
2,802,602
Boost timed_wait leap seconds problem
I am using the timed_wait from boost C++ library and I am getting a problem with leap seconds. Here is a quick test: #include <boost/thread.hpp> #include <stdio.h> #include <boost/date_time/posix_time/posix_time.hpp> int main(){ // Determine the absolute time for this timer. boost::system_time tAbsoluteTime = boost::get_system_time() + boost::posix_time::milliseconds(35000); bool done; boost::mutex m; boost::condition_variable cond; boost::unique_lock<boost::mutex> lk(m); while(!done) { if(!cond.timed_wait(lk,tAbsoluteTime)) { done = true; std::cout << "timed out"; } } return 1; } The timed_wait function is returning 24 seconds earlier than it should. 24 seconds is the current amount of leap seconds in UTC. So, boost is widely used but I could not find any info about this particular problem. Has anyone else experienced this problem? What are the possible causes and solutions? Notes: I am using boost 1.38 on a linux system. I've heard that this problem doesn't happen on MacOS. UPDATE: A little more info: This is happening on 2 redhat machines with kernel 2.6.9. I have executed the same code on an ubuntu machine with kernel 2.6.30 and the timer behaves as expected. So, what I think is that this is probably being caused by the OS or by some mis-set configuration on the redhat machines. I have coded a workaround that adjusts the time to UTC and than get the difference from this adjustment and add to the original time. This seens like a bad idea to me because if this code is executed on a machine without this problem, it might be 24s AHEAD. Still could not find the reason for this.
Ok, here is what I did. It's a workaround and I am not happy with it but it was the best I could come up with: int main(){ typedef boost::date_time::c_local_adjustor<boost::system_time> local_adj; // Determine the absolute time for this timer. boost::system_time tAbsoluteTime = boost::get_system_time() + boost::posix_time::milliseconds(25000); /* * A leap second is a positive or negative one-second adjustment to the Coordinated * Universal Time (UTC) time scale that keeps it close to mean solar time. * UTC, which is used as the basis for official time-of-day radio broadcasts for civil time, * is maintained using extremely precise atomic clocks. To keep the UTC time scale close to * mean solar time, UTC is occasionally corrected by an adjustment, or "leap", * of one second. */ boost::system_time tAbsoluteTimeUtc = local_adj::utc_to_local(tAbsoluteTime); // Calculate the local-to-utc difference. boost::posix_time::time_duration tLocalUtcDiff = tAbsoluteTime - tAbsoluteTimeUtc; // Get only the seconds from the difference. These are the leap seconds. tAbsoluteTime += boost::posix_time::seconds(tLocalUtcDiff.seconds()); bool done; boost::mutex m; boost::condition_variable cond; boost::unique_lock<boost::mutex> lk(m); while(!done) { if(!cond.timed_wait(lk,tAbsoluteTime)) { done = true; std::cout << "timed out"; } } return 1; } I've tested it on problematic and non-problematic machines and it worked as expected on both, so I'm keeping it as long as I can't found a better solution. Thank you all for your help.
2,784,742
2,787,632
What are the lengths/limits C preprocessor as a language creation tool? Where can I learn more about these?
In his FAQ, Bjarne Stroustrup says: To build [Cfront, the first C++ compiler], I first used C to write a "C with Classes"-to-C preprocessor. "C with Classes" was a C dialect that became the immediate ancestor to C++... I then wrote the first version of Cfront in "C with Classes". When I read this, it piqued my interest in the C preprocessor. I'd seen its macro capabilities as suitable for simplifying common expressions but hadn't thought about its ability to significantly add to syntax and semantics on the level that I imagine bringing classes to C took. So now I have some questions on my mind: Are there other examples of this approach to bootstrapping a language off of C? Is the source to Stroustrup's original work available anywhere? Where could I learn more about the specifics of utilizing this technique? What are the lengths/limits of that approach? Could one, say, create a set of preprocessor macros that let someone write in something significantly Lisp/Scheme like?
For an example of the kind of monstrosity of a "language" you can create using the C preprocessor, have a look at this header file: http://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh/mac.h It's from the source code of the original Unix shell written by Steve Bourne and it aims to turn C into an Algol like language. Here is an example of what a piece of code looks like when using it: http://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh/args.c That looks kind of bizarre but it is still C. It may look like a different language, but because it is implemented in the preprocessor, there's no syntactic support for it e.g. WHILE foo DO SWITCH .... ENDSW OD is all very fine and compiles nicely, but so does WHILE foo DO SWITCH .... OD ENDSW
2,784,811
2,784,817
How does the compiler know to call function once per static variable?
E.g foo1() { static const char* str = foo2(); } const char * foo2 () { ... } How does the compiler makes sure it calls foo2 just once.
foo2 is called at the initialisation of your program, just before main(). Edit: this is wrong! I assumed this as this is how normally static initialisation works. But in this case, they are called once at the start of the function. It must work with some kind of static boolean. Yep. At least in gcc, this: int test2() { static int bla = test(); } Compiles to: 8048616: b8 30 a0 04 08 mov $0x804a030,%eax 804861b: 0f b6 00 movzbl (%eax),%eax 804861e: 84 c0 test %al,%al 8048620: 75 52 jne 8048674 <_Z5test2v+0x67> ... 804863c: e8 b3 ff ff ff call 80485f4 <_Z4testv> ... 8048674: 83 c4 1c add $0x1c,%esp 8048677: 5b pop %ebx 8048678: 5e pop %esi 8048679: 5f pop %edi 804867a: 5d pop %ebp 804867b: c3 ret So it uses a hidden, function specific boolean (at $0x804a030) + some magic to protect against exceptions and multiple threads calling it at once.
2,785,183
2,788,079
best alternative to in-definition initialization of static class members? (for SVN keywords)
I'm storing expanded SVN keyword literals for .cpp files in 'static char const *const' class members and want to store the .h descriptions as similarly as possible. In short, I need to guarantee single instantiation of a static member (presumably in a .cpp file) to an auto-generated non-integer literal living in a potentially shared .h file. Unfortunately the language makes no attempt to resolve multiple instantiations resulting from assignments made outside class definitions and explicitly forbids non-integer inits inside class definitions. My best attempt (using static-wrapping internal classes) is not too dirty, but I'd really like to do better. Does anyone have a way to template the wrapper below or have an altogether superior approach? // Foo.h: class with .h/.cpp SVN info stored and logged statically class Foo { static Logger const verLog; struct hInfoWrap; public: static hInfoWrap const hInfo; static char const *const cInfo; }; // Would like to eliminate this per-class boilerplate. struct Foo::hInfoWrap { hInfoWrapper() : text("$Id$") { } char const *const text; }; ... // Foo.cpp: static inits called here Foo::hInfoWrap const Foo::hInfo; char const *const Foo::cInfo = "$Id$"; Logger const Foo::verLog(Foo::cInfo, Foo::hInfo.text); ... // Helper.h: output on construction, with no subsequent activity or stored fields class Logger { Logger(char const *info1, char const *info2) { cout << info0 << endl << info1 << endl; } }; Is there a way to get around the static linkage address issue for templating the hInfoWrap class on string literals? Extern char pointers assigned outside class definitions are linguistically valid but fail in essentially the same manner as direct member initializations. I get why the language shirks the whole resolution issue, but it'd be very convenient if an inverted extern member qualifier were provided, where the definition code was visible in class definitions to any caller but only actually invoked at the point of a single special declaration elsewhere. Anyway, I digress. What's the best solution for the language we've got, template or otherwise? Thanks!
probably, with a static function? // Foo.h: class Foo { static Logger const verLog; static char const*const getHInfo() { return "$Id$"; } public: static char const *const cInfo; }; // Foo.cpp: static inits called here char const *const Foo::cInfo = "$Id$"; Logger const Foo::verLog(Foo::cInfo, Foo::getHInfo());
2,785,206
2,785,468
The pImpl idiom and Testability
The pImpl idiom in c++ aims to hide the implementation details (=private members) of a class from the users of that class. However it also hides some of the dependencies of that class which is usually regarded bad from a testing point of view. For example if class A hides its implementation details in Class AImpl which is only accessible from A.cpp and AImpl depends on a lot of other classes, it becomes very difficult to unit test class A since the testing framework has no access to the methods of AImpl and also no way to inject dependency into AImpl. Has anyone come across this problem before? and have you found a solution? -- edit -- On a related topic, it seems that people suggest one should only test public methods exposed by the interface and not the internals. While I can conceptually understand that statement, I often find that I need to test private methods in isolation. For example when a public method calls a private helper method that contains some non trivial logic.
The idea behind pimpl is to not so much to hide implementation details from classes, (private members already do that) but to move implementation details out of the header. The problem is that in C++'s model of includes, changing the private methods/variables will force any file including this file to be recompiled. That is a pain, and that's why pimpl seeks to eliminate. It doesn't help with preventing dependencies on external libraries. Other techniques do that. Your unit tests shouldn't depend on the implementation of the class. They should verify that you class actually acts as it should. The only thing that really matter is how the object interacts with the outside world. Any behavior which your tests cannot detect must be internal to the object and thus irrelevant. Having said that, if you find too much complexity inside the internal implementation of a class, you may want to break out that logic into a separate object or function. Essentially, if your internal behavior is too complex to test indirectly, make it the external behavior of another object and test that. For example, suppose that I have a class which takes a string as a parameter to its constructor. The string is actual a little mini-language that specifies some of the behavior the object. (The string probably comes from a configuration file or something). In theory, I should be able to test the parsing of that string by constructing different objects and checking behavior. But if the mini-language is complex enough this will be hard. So, I define another function that takes the string and returns a representation of the context (like an associative array or something). Then I can test that parsing function separately from the main object.
2,785,257
2,785,393
OpenGL antialiasing not working
I'v been trying to anti alias with OGL. I found a code chunk that is supposed to do this but I see no antialiasing. I also reset my settings in Nvidia Control Panel but no luck. Does this code in fact antialias the cube? GLboolean polySmooth = GL_TRUE; static void init(void) { glCullFace (GL_BACK); glEnable (GL_CULL_FACE); glBlendFunc (GL_SRC_ALPHA_SATURATE, GL_ONE); glClearColor (0.0, 0.0, 0.0, 0.0); } #define NFACE 6 #define NVERT 8 void drawCube(GLdouble x0, GLdouble x1, GLdouble y0, GLdouble y1, GLdouble z0, GLdouble z1) { static GLfloat v[8][3]; static GLfloat c[8][4] = { {0.0, 0.0, 0.0, 1.0}, {1.0, 0.0, 0.0, 1.0}, {0.0, 1.0, 0.0, 1.0}, {1.0, 1.0, 0.0, 1.0}, {0.0, 0.0, 1.0, 1.0}, {1.0, 0.0, 1.0, 1.0}, {0.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0} }; /* indices of front, top, left, bottom, right, back faces */ static GLubyte indices[NFACE][4] = { {4, 5, 6, 7}, {2, 3, 7, 6}, {0, 4, 7, 3}, {0, 1, 5, 4}, {1, 5, 6, 2}, {0, 3, 2, 1} }; v[0][0] = v[3][0] = v[4][0] = v[7][0] = x0; v[1][0] = v[2][0] = v[5][0] = v[6][0] = x1; v[0][1] = v[1][1] = v[4][1] = v[5][1] = y0; v[2][1] = v[3][1] = v[6][1] = v[7][1] = y1; v[0][2] = v[1][2] = v[2][2] = v[3][2] = z0; v[4][2] = v[5][2] = v[6][2] = v[7][2] = z1; #ifdef GL_VERSION_1_1 glEnableClientState (GL_VERTEX_ARRAY); glEnableClientState (GL_COLOR_ARRAY); glVertexPointer (3, GL_FLOAT, 0, v); glColorPointer (4, GL_FLOAT, 0, c); glDrawElements(GL_QUADS, NFACE*4, GL_UNSIGNED_BYTE, indices); glDisableClientState (GL_VERTEX_ARRAY); glDisableClientState (GL_COLOR_ARRAY); #else printf ("If this is GL Version 1.0, "); printf ("vertex arrays are not supported.\n"); exit(1); #endif } /* Note: polygons must be drawn from front to back * for proper blending. */ void display(void) { if (polySmooth) { glClear (GL_COLOR_BUFFER_BIT); glEnable (GL_BLEND); glEnable (GL_POLYGON_SMOOTH); glDisable (GL_DEPTH_TEST); } else { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable (GL_BLEND); glDisable (GL_POLYGON_SMOOTH); glEnable (GL_DEPTH_TEST); } glPushMatrix (); glTranslatef (0.0, 0.0, -8.0); glRotatef (30.0, 1.0, 0.0, 0.0); glRotatef (60.0, 0.0, 1.0, 0.0); drawCube(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5); glPopMatrix (); glFlush (); } void reshape(int w, int h) { glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void keyboard(unsigned char key, int x, int y) { switch (key) { case 't': case 'T': polySmooth = !polySmooth; glutPostRedisplay(); break; case 27: exit(0); /* Escape key */ break; default: break; } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_ALPHA | GLUT_DEPTH); glutInitWindowSize(200, 200); glutCreateWindow(argv[0]); init (); glutReshapeFunc (reshape); glutKeyboardFunc (keyboard); glutDisplayFunc (display); glutMainLoop(); return 0; } Thanks
Have you tried to supply GLUT_MULTISAMPLE to the glutInitDisplayMode(..) call? It's not sure your glut implementation supports it though.
2,785,306
2,785,316
Calculating volume for sphere in C++
This is probably an easy one, but is the right way to calculate volume for a sphere in C++? My getArea() seems to be right, but when I call getVolume() it doesn't output the right amount. With a sphere of radius = 1, it gives me the answer of pi, which is incorrect: double Sphere::getArea() const { return 4 * Shape::pi * pow(getZ(), 2); } double Sphere::getVolume() const { return (4 / 3) * Shape::pi * pow(getZ(), 3); }
You're using integer division in (4 / 3). Instead, use floating point division: (4.0 / 3.0). 4/3 is 1, because integer division only produces integers. You can confirm this by test code: std::cout << (4/3) << std::endl;.
2,785,309
2,785,331
Accessing derived class members with a base class pointer
I am making a simple console game in C++ I would like to know if I can access members from the 'entPlayer' class while using a pointer that is pointing to the base class ( 'Entity' ): class Entity { public: void setId(int id) { Id = id; } int getId() { return Id; } protected: int Id; }; class entPlayer : public Entity { string Name; public: void setName(string name) { Name = name; } string getName() { return Name; } }; Entity *createEntity(string Type) { Entity *Ent = NULL; if (Type == "player") { Ent = new entPlayer; } return Ent; } void main() { Entity *ply = createEntity("player"); ply->setName("Test"); ply->setId(1); cout << ply->getName() << endl; cout << ply->getId() << endl; delete ply; } How would I be able to call ply->setName etc? OR If it's not possible that way, what would be a better way?
It is possible by using a cast. If you know for a fact that the base class pointer points to an object of the derived class, you can use static_cast: Entity* e = /* a pointer to an entPlayer object */; entPlayer* p = static_cast<entPlayer*>(e); p->setName("Test"); If you don't know for sure, then you need to use dynamic_cast and test the result to see that it is not null. Note that you can only use dynamic_cast if the base class has at least one virtual function. An example: Entity* e = /* a pointer to some entity */; entPlayer* p = dynamic_cast<entPlayer*>(e); if (p) { p->setName("Test"); } That said, it would be far better to encapsulate your class's functionality using polymorphism (i.e. virtual functions). Speaking of virtual functions, your class hierarchy as implement has undefined behavior: you can only delete an object of a derived type through a pointer to one of its base classes if the base class as a virtual destructor. So, you need to add a virtual destructor to the base class.
2,785,434
2,786,158
How to interact with checkbox actions ? (QTableView with QStandardItemModel)
I'm using QTableView and QStandardItemModel to show some data. For each row, there is a column which has a check Box, this check box is inserted by setItem, the code is as follows: int rowNum; QStandardItemModel *tableModel; QStandardItem* __tmpItem = new QStandardItem(); __tmpItem->setCheckable(true); __tmpItem->setCheckState(Qt::Unchecked); tableModel->setItem(rowNum,0,__tmpItem); Now I want to interact with the check box. If a check box changes its state by user (from checked to unchecked or vice versa), I want to do something on the corresponding data row. I know I can use signal-slot to catch the change of checkbox, but since there are lots of data row, I don't want to connect each row one by one. Is there anyway to interact with the check action more effectively? Thanks :)
handle the click event, there you will get the modelindex, get the data and modify the same if you are going to insert more than one text or icon, then you need to set the delegate for your listview
2,785,449
2,785,470
find window text and save txt to file named that wont work
my code wont work and idk why. the point of my code is to find the top window and save a text file with the name the same as the text on the top menu bar (task bar i think?). then save some data to that text file. but everytime i try to use it the write fails if i set the name of the text file before hand so it wont change it will write the data to the file. but if i don't set it before hand it will make the text doc but not write anything to it. or sometimes it will just write numbers for the name (i think it's the handle number) then it will write the data. :\ it's odd can anyone help? #include <iostream> #include <windows.h> #include <fstream> #include <string> #include <sstream> #include <time.h> using namespace std; string header_str = ("NULL"); #define DTTMFMT "%Y-%m-%d %H:%M:%S " #define DTTMSZ 21 char buff[DTTMSZ]; fstream filestr; string ff = ("C:\\System logs\\txst.txt"); TCHAR buf[255]; int main() { GetWindowText(GetForegroundWindow(), buf, 255); stringstream header(stringstream::in | stringstream::out); header.flush(); header << ("C:\\System logs\\"); header << buf; header << (".txt"); header_str = header.str(); ff = header_str; cout << header_str << "\n"; filestr.open (ff.c_str(), fstream::in | fstream::out | fstream::app | ios_base::binary | ios_base::out); filestr << "dfg"; filestr.close(); Sleep(10000); return 0; }
You are not sanitizing the name of your text file. There are quite a few illegal file names. Primarily, characters such as ":", "/" and "\" are not allowed in a filename.
2,785,601
2,785,605
C++ Numerical truncation error
sorry if dumb but could not find an answer. #include <iostream> using namespace std; int main() { double a(0); double b(0.001); cout << a - 0.0 << endl; for (;a<1.0;a+=b); cout << a - 1.0 << endl; for (;a<10.0;a+=b); cout << a - 10.0 << endl; cout << a - 10.0-b << endl; return 0; } Output: 0 6.66134e-16 0.001 -1.03583e-13 Tried compiling it with MSVC9, MSVC10, Borland C++ 2010. All of them arrive in the end to the error of about 1e-13. Is it normal to have such a significant error accumulation over only a 1000, 10000 increments?
Yes, this is normal numeric representation floating point error. It has to do with the fact that the hardware must approximate most floating point numbers, rather than storing them exactly. Thus, the compiler you use should not matter. What Every Computer Scientist Should Know About Floating-Point Arithmetic
2,785,612
2,785,639
C++, What does the colon after a constructor mean?
Possible Duplicates: Variables After the Colon in a Constructor C++ constructor syntax question (noob) I have some C++ code here: class demo { private: unsigned char len, *dat; public: demo(unsigned char le = 5, unsigned char default) : len(le) { dat = new char[len]; for (int i = 0; i <= le; i++) dat[i] = default; } void ~demo(void) { delete [] *dat; } }; class newdemo : public demo { private: int *dat1; public: newdemo(void) : demo(0, 0) { *dat1 = 0; return 0; } }; My question is, what are the : len(le) and : demo(0, 0) called? Is it something to do with inheritance?
As others have said, it's an initialisation list. You can use it for two things: Calling base class constructors Initialising member variables before the body of the constructor executes. For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class. For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const members. For instance, take a look at this situation, where I want to initialise m_val based on the constructor parameter: class Demo { Demo(int& val) { m_val = val; } private: const int& m_val; }; By the C++ specification, this is illegal. We cannot change the value of a const variable in the constructor, because it is marked as const. So you can use the initialisation list: class Demo { Demo(int& val) : m_val(val) { } private: const int& m_val; }; That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member. Outside of using it to initialise const member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
2,785,901
2,789,577
"Debug Assertion" Runtime Error on VS2008?
I'm writing a C++ MFC program on VS2008 and I'm getting this "Debug Assertion Error" when I first run the program sometimes. When I try to debug it, it takes me to this winhand.cpp file which is not part of the program I wrote so I'm not sure how to debug this. It takes the error to this place in winhand.cpp CObject* pTemp = LookupTemporary(h); if (pTemp != NULL) { // temporary objects must have correct handle values HANDLE* ph = (HANDLE*)((BYTE*)pTemp + m_nOffset); // after CObject ASSERT(ph[0] == h || ph[0] == NULL); if (m_nHandles == 2) ASSERT(ph[1] == h); } So why does this error happen? Why does it only happen sometimes (50% of the time)? How would I debug this? I'll provide some code if is needed. THANKS!
The code that is asserting is part of MFC's CHandleMap class. MFC deals with windows as CWnd objects, but Windows deals with them as HWND handles. the handle map allows MFC to 'convert' an HWND into a pointer to the MFC object representing that object. What the assertion seems to be doing is checking that when a lookup of the handle finds an MFC object, that the MFC object also thinks it's wrapping the same handle. If they're different, then you get the assertion. So it would appear that something is corrupting the handle map or the MFC object for that handle or you're doing something incorrect that gets these 2 data structures out of sync. Some things you might do to try to debug the problem is to determine: what MFC object is being found in the lookup (that's what's being pointed to by pObject) what the MFC object thinks it's wrapping (that's the handle ph[0] and/or ph[1] - I'm not sure why there can be 2 of them) what the handle is for (that's h) Do the handles look like handle values or do they look like garbage? Does pObject point to something that looks like an MFC object, or garbage? Do any of these these things seem related? The answers to these questions may point to what you need to do next (maybe set a debug write breakpoint on the item that looks like it's trashed).
2,785,969
2,785,988
Template Sort In C++
Hey all, I'm trying to write a sort function but am having trouble figuring out how to initialize a value, and making this function work as a generic template. The sort works by: Find a pair =(ii,jj)= with a minimum value = ii+jj = such at A[ii]>A[jj] If such a pair exists, then swap A[ii] and A[jj] else break; The function I have written is as follows: template <typename T> void sort(T *A, int size) { T min =453; T temp=0; bool swapper = false; int index1 = 0, index2 = 0; for (int ii = 0; ii < size-1; ii++){ for (int jj = ii + 1; jj < size; jj++){ if((min >= (A[ii]+A[jj])) && (A[ii] > A[jj])){ min = (A[ii]+A[jj]); index1 = ii; index2 = jj; swapper = true; } } } if (!swapper) return; else { temp = A[index1]; A[index1] = A[index2]; A[index2] = temp; sort(A,size); } } This function will successfully sort an array of integers, but not an array of chars. I do not know how to properly initialize the min value for the start of the comparison. I tried initializing the value by simply adding the first two elements of the array together (min = A[0] + A[1]), but it looks to me like for this algorithm it will fail. I know this is sort of a strange type of sort, but it is practice for a test, so thanks for any input.
most likely reason it fails, is because char = 453 does not produce 453 but rather different number, depending what char is (signed versus unsigned). your immediate solution would be to use numerical_limits, http://www.cplusplus.com/reference/std/limits/numeric_limits/ you may also need to think about design, because char has small range, you are likely to overflow often when adding two chars.
2,786,245
3,185,308
OCCI createEnvironment Blocks My Thread
I'm writing a multi-threaded application, where there is a main thread which distributes tasks to the worker threads. According to the task, a worker thread creates a connection, by using a global occi environment. When a worker thread completes its task, it closes the connection (I'm sure, there is no exception thrown while termination). My problem is that after a while(sometimes 5 mins, sometimes 5 hours) the threads cannot get connection from the environment, and they get blocked there. What can be the problem?
I guess I didn't identify the problem correctly. I thought the threads get blocked, but actually they didn't, they simply exited there unexpectedly :). Problem solved.
2,786,286
2,786,307
Advanced switch statement within while loop?
I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But.. Lets say I have the following scenario (theorietical code): while(1) { //Loop can be conditional or 1, I use it alot, for example in my game char something; std::cout << "Enter something\n -->"; std::cin >> something; //Switch to read "something" switch(something) { case 'a': cout << "You entered A, which is correct"; break; case 'b': cout << "..."; break; } } And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements? This obviously looks wrong: case 'a': cout << "You entered A, which is correct"; break; break; So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple? This would solve a lot of my problems that I have right now.
You could simply have the while loop check for a bool value that is set within one of your case statements. bool done = false; while(!done) { char something; std::cout << "Enter something\n -->"; std::cin >> something; //Switch to read "something" switch(something) { case 'a': cout << "You entered A, which is correct"; done = true; // exit condition here break; case 'b': cout << "..."; break; } }
2,786,417
2,786,432
Matrix Comparison algorithm
If you have 2 Matrices of dimensions N*M. what is the best way to get the difference Rect? Example: 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 4 5 4 3 2 3 <---> 2 3 2 3 2 3 2 3 2 3 4 5 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 | | \ / Rect([2,2] , [3,4]) 4 5 4 4 5 2-> A (2 x 3 Matrix) The best I could think of is to scan from Top-Left hit the point where there is difference. Then scan from Bottom Right and hit the point where there is a difference. But In worst case, this is O(N*M). is there a better efficient algorithm? Or is there something I could do with how I represent them, so that you can apply a more efficient algorithm? And mind you, this Matrix can be very big.
No, there isn't a more efficient algorithm. For identical matrixes, you must scan all elements, so the algorithm is necessarily O(n*m).
2,786,485
2,786,747
Question regarding C++ Lists
list dog; ............. ............ So I added many dog objects to it. If I call dog.pop_front(); Does memory automatically gets deallocated ? For the object that I popped out ? So If I call list<Dog*> dog2; dog2.push_back(dog.front()); and then I will call dog.pop_front() So this will work? I will assume Dog as type struct.
You keep asking about this sequence: list<Dog*> dog2; dog2.push_back(dog.front()); // time 1 dog.pop_front(); // time 2 At time1, both dog2 and dog have a pointer to the same object. At time2, the pointer to that object is removed from dog and is only in dog2. Assuming you originally created that object with new Dog, the object will not be freed until you explicitly free it by calling delete ptr
2,786,581
2,786,618
migrating C++ code from structures to classes
I am migrating some C++ code from structures to classes. I was using structures mainly for bit-field optimizations which I do not need any more (I am more worried about speed than saving space now). What are the general guidelines for doing this migration? I am still in the planning stage as this is a very big move affecting a major part of the code. I want to plan everything first before doing it. What are all the essential things I should keep in mind?
I can't name all the essential things, but I can name one: encapsulation. The only technical difference in C++ between struct and class is the default access. In a struct, everything is public by default; in a class, everything is private. I'm assuming that you're talking about POD structs here, where everything is public. What I would do is this: Change the struct keyword to class and see where calling code breaks. That would give you a clue about what parts of the type are used where. From that, determine which elements of the type should be public, which should be private. Write accessor functions for the public parts, and change calling code to use them. Move the code that needs access to private parts into the class itself.
2,786,785
2,786,825
Why does gprof tell me that a function that is called only once from main() is called 102 times?
I am a beginner, and wrote the following program for fun, to search through a directory and replace every occurrence of one word with another. I call the crt_ls_file() function once, and once only, but gprof tells me it is being called 102 times. I am wondering if anyone knows why this is. I have tried compiling the program will all and no optimizations. #include <iostream> #include <string> #include <cstdlib> #include <cassert> #include <fstream> using namespace std; void crt_ls_file(const string& output_f, const string& dir); void sed(const string& old_string, const string& new_string, const string& filename, const string& directory); int main(int argc, char* argv[]){ string out_f; if (argc <= 1) { cout << "Usage: " << argv[0] << " <Filename>" << endl; exit(EXIT_FAILURE); } else { out_f = ".sandr"; crt_ls_file(out_f, string(argv[1]) ); } ifstream out_fs( out_f.c_str() ); string line; getline(out_fs, line); while( !out_fs.eof() ){ sed(string("index_SYMBOL"), string("index1_SYMBOL"), line, string(argv[1]) ); getline(out_fs, line); } out_fs.close(); string f( "rm " + out_f ); system ( f.c_str() ); exit(EXIT_SUCCESS); } void crt_ls_file(const string& s, const string& a){ ofstream ls( s.c_str() ); ls.close(); string ls_output( "ls -1 " + a + " > ./" + string(s) ); system( ls_output.c_str() ); } void sed(const string& o, const string& n, const string& f, const string& d){ ofstream dummy(".temp"); dummy.close(); string sed_output( "sed 's/" + o + "/" + n + "/g' " + d + "/" + f + " > .temp" ); system( sed_output.c_str() ); string rp( "mv .temp " + d + "/" + f ); system ( rp.c_str() ); }
On my system gprof shows only one call to crt_ls_file as it should be: 0.00 0.00 0.00 1 0.00 0.00 crt_ls_file(std::string const&, std::string const&) So it seems you gprof is lying, which it sometimes does. If you really want to profile this program (there's little use), try callgrind and kcachegrind instead. They're much better and less arcane tools: $ valgrind --tool=callgrind ./my_program some_dir ... let it do its job ... $ kcachegrind
2,786,816
2,786,872
How to create C++ istringstream from a char array with null(0) characters?
I have a char array which contains null characters at random locations. I tried to create an iStringStream using this array (encodedData_arr) as below, I use this iStringStream to insert binary data(imagedata of Iplimage) to a MySQL database blob field(using MySQL Connector/C++'s setBlob(istream *is) ) it only stores the characters upto the first null character. Is there a way to create an iStringStream using a char array with null characters? unsigned char *encodedData_arr = new unsigned char[data_vector_uchar->size()]; // Assign the data of vector<unsigned char> to the encodedData_arr for (int i = 0; i < vec_size; ++i) { cout<< data_vector_uchar->at(i)<< " : "<< encodedData_arr[i]<<endl; } // Here the content of the encodedData_arr is same as the data_vector_uchar // So char array is initializing fine. istream *is = new istringstream((char*)encodedData_arr, istringstream::in || istringstream::binary); prepStmt_insertImage->setBlob(1, is); // Here only part of the data is stored in the database blob field (Upto the first null character)
There is nothing special about null characters in strings std::istringstream iss(std::string(data, N)); setBlob(&iss); Of course if you do std::istringstream iss("haha a null: \0"); It will interpret that as a C-style string converted to std::string, and thus will stop at the \0, not taking it as a real content byte. Telling std::string the size explicitly allows it to consume any null byte as real content data. If you want to read directly from a char array, you can use strstream std::istrstream iss(data, N); That will directly read from the data provided by data, up to N bytes. strstream is declared "deprecated" officially, but it's still going to be in C++0x, so you can use it. Or you create your own streambuf, if you really need to read from a raw char* like that. struct myrawr : std::streambuf { myrawr(char const *s, size_t n) { setg(const_cast<char*>(s), const_cast<char*>(s), const_cast<char*>(s + n)); } }; struct hasb { hasb(char const *s, size_t n) :m(s, n) { } myrawr m; }; // using base-from-member idiom struct myrawrs : private hasb, std::istream { myrawrs(char const *s, size_t n) :hasb(s, n), std::istream(&static_cast<hasb*>(this)->m) { } };
2,786,895
4,416,296
C++: why a self pointer of a struct automatically changes to void*
struct ptr{ int node; ptr *next; ptr(){} ptr(int _node, ptr *_next){ node=_node; next=_next; } }; struct list_t{ ptr *sht; int size; void push(int node){ size++; sht=new ptr(node,sht); } }shthead[100001], comp[200001], tree[200001]; The struct ptr is used as a linked list. But when I debug the code in gdb, I found that the ptr*'s were all converted to void*. GDB output: (gdb) pt ptr type = struct ptr { int node; void *next; public: ptr(void); ptr(int, void *); } However, I can still see the data of the struct if I covert them back to ptr* in gdb. What's the reason for this please? I'm using Arch Linux, GNOME, g++ 4.5.0, gdb 7.1. Without any compilation flags but a -g. This GDB was configured as "i686-pc-linux-gnu"
Maybe this: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45088 I need to thank Tom Tromey for telling me this.