question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,251,625
1,251,684
Non-destructive parsing and modifying of HTML elements in C++
I have a need to do some simple modifications to HTML in C++, preferably without completely rewriting the HTML, such as what happens when I use libxml2 or MSHTML. In particular I need to be able to read, and then (potentially) modify, the "src" attribute of all "img" elements. I need it to be robust enough to be able to do this with any valid HTML, but preferably without changing any of the other HTML in the process. Are there any libraries out there that would be able to handle this? Or is this something I can do with regular expressions? I'm not too savvy with regular expressions, and I've read a lot of questions here that say you shouldn't use them to parse HTML, but I'm not clear if that applies to something like this or if that principle applies primarily to parsing in the context of building a tree from the HTML.
Regular expressions aren't recommended for HTML because they don't handle nested tags well. They should be fine for this purpose.
1,252,011
1,253,100
Is there a generic way to iterate over a specific variable in a group of objects?
Lets say I have a linked list with a bunch of different data in it. class Node { public: Node* next; AAA dataA; BBB dataB; CCC dataC; }; Is there a way I make one iterator that would iterate over whatever variable I specify (rather than making three separate ones for each variable). I understand that the iterator could use templates to make it iterate over types AAA, BBB or CCC, but I don't know how I could specify which variable to return.
I think I've found a way to do pretty much what I want based on rstevens' suggestion. I looked up some stuff on class member pointers and was able to skip the middleman accessor class by doing this: template <typename T> class iterator { private: Node *current; T Node::*var; public: iterator() : current(NULL), var(NULL) {} iterator(Node *start, T Node::*var) : current(start), var(var) { } typename T &operator *() const { return current->*var; } bool end() const { return (current == NULL); } iterator &operator++() { if (current) current = current->next; return *this; } }; And then I modified Node to have convenience functions to make the iterators: class Node { public: Node* next; AAA dataA; BBB dataB; CCC dataC; typedef iterator<AAA> AIter; typedef iterator<BBB> BIter; typedef iterator<CCC> CIter; AIter getAIter() { return AIter(this, &Node::dataA); } BIter getBIter() { return BIter(this, &Node::dataB); } CIter getCIter() { return CIter(this, &Node::dataC); } }; So now I can do this to easily iterate over each data member of my class: for (Node::CIter iter = n1.getCIter(); !iter.end(); ++iter) { // tada! }
1,252,049
1,252,069
C++ LNK1120 and LNK2019 errors: "unresolved external symbol WinMain@16"
I'm trying to do another exercise from Deitel's book. The program calculates the monthly interest and prints the new balances for each of the savers. As the exercise is part of the chapter related to dynamic memory, I'm using "new" and "delete" operators. For some reason, I get these two errors: LNK2019: unresolved external symbol WinMain@16 referenced in function ___tmainCRTStartup fatal error LNK1120: 1 unresolved externals Here is class header file. //SavingsAccount.h //Header file for class SavingsAccount class SavingsAccount { public: static double annualInterestRate; SavingsAccount(double amount=0);//default constructor intialize //to 0 if no argument double getBalance() const;//returns pointer to current balance double calculateMonthlyInterest(); static void modifyInterestRate(double interestRate): ~SavingsAccount();//destructor private: double *savingsBalance; }; Cpp file with member function definitions //SavingsAccount class defintion #include "SavingsAccount.h" double SavingsAccount::annualInterestRate=0;//define and intialize static data //member at file scope SavingsAccount::SavingsAccount(double amount) :savingsBalance(new double(amount))//intialize savingsBalance to point to new object {//empty body }//end of constructor double SavingsAccount::getBalance()const { return *savingsBalance; } double SavingsAccount::calculateMonthlyInterest() { double monthlyInterest=((*savingsBalance)*annualInterestRate)/12; *savingsBalance=*savingsBalance+monthlyInterest; return monthlyInterest; } void SavingsAccount::modifyInterestRate(double interestRate) { annualInterestRate=interestRate; } SavingsAccount::~SavingsAccount() { delete savingsBalance; }//end of destructor End finally driver program : #include <iostream> #include "SavingsAccount.h" using namespace std; int main() { SavingsAccount saver1(2000.0); SavingsAccount saver2(3000.0); SavingsAccount::modifyInterestRate(0.03);//set interest rate to 3% cout<<"Saver1 monthly interest: "<<saver1.calculateMonthlyInterest()<<endl; cout<<"Saver2 monthly interest: "<<saver2.calculateMonthlyInterest()<<endl; cout<<"Saver1 balance: "<<saver2.getBalance()<<endl; cout<<"Saver1 balance: "<<saver2.getBalance()<<endl; return 0; } I have spent an hour trying to figure this out with no success.
Go to "Linker settings -> System". Change the field "Subsystem" from "Windows" to "Console".
1,252,117
1,252,137
How to avoid infinite recursion in C++ class templates
I have a matrix class with the size determined by template parameters. template <unsigned cRows, unsigned cCols> class Matrix { ... }; My program uses matrices of a few sizes, typically 2x2, 3x3, and 4x4. By setting the matrix size with template parameters rather than run-time parameters allows the compiler to do a lot of inlining and optimization. But now I need a member function that returns a new matrix that has one fewer row and one fewer column. Matrix<cRows - 1, cCols - 1> Reduced(unsigned row, unsigned col) const { ... } The idea is that that it will return a matrix with the specified row and column deleted. In practice, this will only ever be called with a matrix that has at least three rows and three columns, returning a 2x2 at the smallest. The compiler doesn't see the lower bound, so it gets stuck in an infinite recursion trying to instantiate the templates with ever decreasing sizes. I tried putting two clues in the function itself that these smaller sizes cannot occur: Matrix<cRows - 1, cCols - 1> Reduced(unsigned row, unsigned col) const { static_assert(cRows > 1 && cCols > 1); if (cRows <= 1 || cCols <= 1) throw std::domain_error(); Matrix<cRows - 1, cCols - 1> r; // ... initialize r ... return r; } Neither the static_assert nor the if-statement seems to be a strong enough clue to the compiler that a 0x0 matrix will never be generated. (Ironically, it does complain about the if-statement having a constant compile-time condition.) Does anyone have any suggestions on how to avoid this compile-time infinite recursion?
You need to provide a specialization for a Matrix that has no rows or no columns. E.g. template<unsigned cRows> class Matrix< cRows, 0 > { Matrix<cRows - 1, 0> Reduced() { return Matrix<cRows - 1, 0>(); } }; template<unsigned cCols> class Matrix< 0, cCols > { Matrix<0, cCols - 1> Reduced() { return Matrix<0, cCols - 1>(); } }; template<> class Matrix< 0, 0 > { Matrix<0, 0> Reduced() { return Matrix<0, 0>(); } }; The issue you have is that attempting to instantiate the Matrix Reduced function with a particular set of template parameters always required instantiating the Matrix template for a different set of parameters (cRows - 1, cCols -1). This recursion has to be stopped somewhere. If you are only ever dealing with square matrices, then you can get away with fewer specializations. Also, you can could stop the recursion with a completely empty class if you are never going to use, say, a 1x1 matrix, the result of reduce on a 2x2 matrix. template<> class Matrix< 1, 1 > {};
1,252,201
1,260,371
Any good C/C++ web toolkit?
I've been looking around and came across the WT toolkit, Is it stable? Any good? I was stumped on how to go about this in C++, given the lack of libraries and resources concerning web developement. (CGI/Apache) The purpose of my application is to populate some data from a Sybase ASE15 database running GNU/Linux & Apache Hence allow some user interactions. I am going to use Sybase open client library (libct) to retrieve columns from the Server, feed this data back to wt model/view. My requests: Is there any more practical solution rather than using other scripting languages? I mean by practical, an interface with ODBC retrieving, and MVC mechanism? If not available in C++, any alternative in Java?
Give this one a look. I never much liked Wt's design. But then, I'm kind of an anti-framework guy. http://cppcms.sourceforge.net/wikipp/en/page/main
1,252,224
1,252,268
Using boost::tokenizer with string delimiters
I've been looking boost::tokenizer, and I've found that the documentation is very thin. Is it possible to make it tokenize a string such as "dolphin--monkey--baboon" and make every word a token, as well as every double dash a token? From the examples I've only seen single character delimiters being allowed. Is the library not advanced enough for more complicated delimiters?
It looks like you will need to write your own TokenizerFunction to do what you want.
1,252,333
1,252,341
Constructor with references not properly assigning?
I'm trying to write a simple color class that's supposed to be as versatile as possible. Here's what it looks like: class MyColor { private: uint8 v[4]; public: uint8 &r, &g, &b, &a; MyColor() : r(v[0]), g(v[1]), b(v[2]), a(v[3]) {} MyColor(uint8 red, uint8 green, uint8 blue, uint8 alpha = 255) : r(v[0]), g(v[1]), b(v[2]), a(v[3]) { printf("%d, %d, %d, %d\n", red, green, blue, alpha); r = red; g = green; b = blue; a = alpha; } MyColor(uint8 vec[]) : r(v[0]), g(v[1]), b(v[2]), a(v[3]) { MyColor(vec[0], vec[1], vec[2], vec[3]); } uint8 operator [](int i) { return v[i]; } operator const GLubyte*() { return v; } }; And here's the code I'm trying: uint8 tmp[] = {1,2,3,4}; MyColor c(tmp); printf("%d, %d, %d, %d\n", c.r, c.g, c.b, c.a); (I would have liked it if I could have done MyColor c = {1,2,3,4} but I'm not sure that's possible in the current spec?) Anyway, it outputs this: 1, 2, 3, 4 112, 22, 104, 89 So the values it gets in the 2nd constructor are correct, but when it returns... those values are random?? r = red should set both r and v[0] to red shouldn't it? Since r is just a reference to v[0] they are actually share the same value, no? I'm not doing some weird reassigning of the reference to somewhere in space am I?
Unfortunately, you can't do constructor forwarding at the moment in C++. The issue is here: MyColor(uint8 vec[]) : r(v[0]), g(v[1]), b(v[2]), a(v[3]) { MyColor(vec[0], vec[1], vec[2], vec[3]); } What this actually does is to bind the references to the member vector v and then in the body of the constructor create a temporary MyColor value which is then thrown away. The second line in your output is printing the garbage initial values of the member vector v of the constructed MyColor. I'd recommend breaking out the value assign part of the constructor taking 4 uint8s and calling that from both constructors. void AssignColorValues( uint8 red, uint8 green, uint8 blue, uint8 alpha) { printf("%d, %d, %d, %d\n", red, green, blue, alpha); r = red; g = green; b = blue; a = alpha; } MyColor(uint8 red, uint8 green, uint8 blue, uint8 alpha = 255) : r(v[0]), g(v[1]), b(v[2]), a(v[3]) { AssignColorValues( red, green, blue, alpha ); } MyColor(uint8 vec[]) : r(v[0]), g(v[1]), b(v[2]), a(v[3]) { AssignColorValues(vec[0], vec[1], vec[2], vec[3]); }
1,252,362
1,253,218
Is it safe to read past the end of an array?
Let's say I have a constructor like this: MyColor(uint8 vec[]) { r = vec[0]; g = vec[1]; b = vec[2]; a = vec[3]; } But I call it like this (3 elements instead of 4): uint8 tmp[] = {1,2,3}; MyColor c(tmp); But now vec[3] is undefined... is it safe to assign this value to a? If not, there's no nice workaround to check if vec[3] is set is there?
if you dont want to use vector try this... MyColor(uint8 (&vec)[3]) { r = vec[0]; g = vec[1]; b = vec[2]; } MyColor(uint8 (&vec)[4]) { //... } uint8 a1[] = {1,2,3}; MyColor c1(a1); uint8 a2[] = {1,2,3,4}; MyColor c2(a2); uint8 a3[] = {1,2,3,4,5}; MyColor c3(a3); // error you dont have to include the array's size explicitly and if you try to pass an array with wrong number of elements, compile error will be generated,
1,252,680
1,252,703
OpenGL Windowing Library for 2009
Trying to decide on a library for creating a window and capturing user input for my OpenGL app, but there are just way too many choices: GLUT (win32) FreeGLUT OpenGLUT SFML GLFW SDL FLTK OGLWFW Clutter Qt Others? GLUT is simply outdated. I liked GLFW but it seems you can't set the window position before displaying it (I wanted it centered, is that so much to ask?) so you see it appear and then shift over, which bothers me. Plus development seems to have stopped on it too. SFML has some nice features, but it uses event polling rather than callbacks which I prefer for decoupling. I don't think I need all the GUI features of FLTK. SDL is slow (doesn't seem to take advantage of the GPU). And the other 3 I don't know much about (FreeGLUT, OpenGLUT, OGLWFW). So which is the lesser of the evils? Are there others I haven't heard about? I'm just trying to make a simple 2D game. I'm familiar enough with OpenGL that I don't really need drawing routines, but I probably wouldn't complain about other functions that might be useful if they are implemented properly.
I'd go for Qt. Nice general purpose library + opengl support
1,252,712
1,252,721
About fork system call and global variables
I have this program in C++ that forks two new processes: #include <pthread.h> #include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdlib> using namespace std; int shared; void func(){ extern int shared; for (int i=0; i<10;i++) shared++; cout<<"Process "<<getpid()<<", shared " <<shared<<", &shared " <<&shared<<endl; } int main(){ extern int shared; pid_t p1,p2; int status; shared=0; if ((p1=fork())==0) {func();exit(0);}; if ((p2=fork())==0) {func();exit(0);}; for(int i=0;i<10;i++) shared++; waitpid(p1,&status,0); waitpid(p2,&status,0);; cout<<"shared variable is: "<<shared<<endl; cout<<"Process "<<getpid()<<", shared " <<shared<<", &shared " <<&shared<<endl; } The two forked processes make an increment on the shared variables and the parent process does the same. As the variable belongs to the data segment of each process, the final value is 10 because the increment is independent. However, the memory address of the shared variables is the same, you can try compiling and watching the output of the program. How can that be explained ? I cannot understand that, I thought I knew how the fork() works, but this seems very odd.. I need an explanation on why the address is the same, although they are separate variables.
The OS is using virtual memory and similar techniques to ensure that each process sees different memory cells (virtual or read) at the same addresses; only memory that's explicitly shared (e.g. via shm) is shared, all memory by default is separate among separate processes.
1,252,786
1,252,798
How to know a certain disk's format(is FAT32 or NTFS)
I am programing under windows, c++, mfc How can I know disk's format by path such as "c:\". Does windows provide such APIs?
The Win32API function ::GetVolumeInformation is what you are looking for. From MSDN: GetVolumeInformation Function BOOL WINAPI GetVolumeInformation( __in_opt LPCTSTR lpRootPathName, __out LPTSTR lpVolumeNameBuffer, __in DWORD nVolumeNameSize, __out_opt LPDWORD lpVolumeSerialNumber, __out_opt LPDWORD lpMaximumComponentLength, __out_opt LPDWORD lpFileSystemFlags, __out LPTSTR lpFileSystemNameBuffer, // Here __in DWORD nFileSystemNameSize ); Example: TCHAR fs [MAX_PATH+1]; ::GetVolumeInformation(_T("C:\\"), NULL, 0, NULL, NULL, NULL, &fs, MAX_PATH+1); // Result is in (TCHAR*) fs
1,252,976
1,252,996
How to handle multiple keypresses at once with SDL?
been getting myself familiar with OpenGL programming using SDL on Ubuntu using c++. After some looking around and experimenting I am starting to understand. I need advice on keyboard event handling with SDL. I have a 1st person camera, and can walk fwd, back, strafe left and right and use the mouse to look around which is great. Here is my processEvents function: void processEvents() { int mid_x = screen_width >> 1; int mid_y = screen_height >> 1; int mpx = event.motion.x; int mpy = event.motion.y; float angle_y = 0.0f; float angle_z = 0.0f; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: quit = true; break; case SDLK_w: objCamera.Move_Camera( CAMERASPEED); break; case SDLK_s: objCamera.Move_Camera(-CAMERASPEED); break; case SDLK_d: objCamera.Strafe_Camera( CAMERASPEED); break; case SDLK_a: objCamera.Strafe_Camera(-CAMERASPEED); break; default: break; } break; case SDL_MOUSEMOTION: if( (mpx == mid_x) && (mpy == mid_y) ) return; SDL_WarpMouse(mid_x, mid_y); // Get the direction from the mouse cursor, set a resonable maneuvering speed angle_y = (float)( (mid_x - mpx) ) / 1000; angle_z = (float)( (mid_y - mpy) ) / 1000; // The higher the value is the faster the camera looks around. objCamera.mView.y += angle_z * 2; // limit the rotation around the x-axis if((objCamera.mView.y - objCamera.mPos.y) > 8) objCamera.mView.y = objCamera.mPos.y + 8; if((objCamera.mView.y - objCamera.mPos.y) <-8) objCamera.mView.y = objCamera.mPos.y - 8; objCamera.Rotate_View(-angle_y); break; case SDL_QUIT: quit = true; break; case SDL_VIDEORESIZE: screen = SDL_SetVideoMode( event.resize.w, event.resize.h, screen_bpp, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE ); screen_width = event.resize.w; screen_height = event.resize.h; init_opengl(); std::cout << "Resized to width: " << event.resize.w << " height: " << event.resize.h << std::endl; break; default: break; } } } now while this is working, it has some limitations. The biggest one and the purpose of my question is that it seems to only process the latest key that was pressed. So if I am holding 's' to walk backwards and I press 'd' to strafe right, I end up strafing right but not going backwards. Can someone point me in the right direction for better keyboard handling with SDL, support for multiple keypresses at once, etc? Thanks
A good approach will be to write a keyboard ("input") handler that will process input events and keep the event's state in some sort of a structure (associative array sounds good - key[keyCode]). Every time the keyboard handler receives a 'key pressed' event, it sets the key as enabled (true) and when it gets a key down event, it sets it as disabled (false). Then you can check multiple keys at once without pulling events directly, and you will be able to re-use the keyboard across the entire frame without passing it around to subroutines. Some fast pseudo code: class KeyboardHandler { handleKeyboardEvent(SDL Event) { keyState[event.code] = event.state; } bool isPressed(keyCode) { return (keyState[keyCode] == PRESSED); } bool isReleased(keyCode) { return (keyState[keyCode] == RELEASED); } keyState[]; } ... while(SDL Pull events) { switch(event.type) { case SDL_KEYDOWN: case SDL_KEYUP: keyHandler.handleKeyboardEvent(event); break; case SDL_ANOTHER_EVENT: ... break; } } // When you need to use it: if(keyHandler.isPressed(SOME_KEY) && keyHandler.isPressed(SOME_OTHER_KEY)) doStuff(TM);
1,252,992
1,253,004
How to escape a string for use in Boost Regex
I'm just getting my head around regular expressions, and I'm using the Boost Regex library. I have a need to use a regex that includes a specific URL, and it chokes because obviously there are characters in the URL that are reserved for regex and need to be escaped. Is there any function or method in the Boost library to escape a string for this kind of usage? I know there are such methods in most other regex implementations, but I don't see one in Boost. Alternatively, is there a list of all characters that would need to be escaped?
. ^ $ | ( ) [ ] { } * + ? \ Ironically, you could use a regex to escape your URL so that it can be inserted into a regex. const boost::regex esc("[.^$|()\\[\\]{}*+?\\\\]"); const std::string rep("\\\\&"); std::string result = regex_replace(url_to_escape, esc, rep, boost::match_default | boost::format_sed); (The flag boost::format_sed specifies to use the replacement string format of sed. In sed, an escape & will output whatever matched by the whole expression) Or if you are not comfortable with sed's replacement string format, just change the flag to boost::format_perl, and you can use the familiar $& to refer to whatever matched by the whole expression. const std::string rep("\\\\$&"); std::string result = regex_replace(url_to_escape, esc, rep, boost::match_default | boost::format_perl);
1,253,245
1,254,562
Installing Libboost 1.38 on Ubuntu 8.10
Is there a way to Install Libboost 1.38 on Ubuntu 8.10? The highest version in my repositories is 1.35. It has been suggested that there may be some repositories I could add to accomplish this, but my searches haven't yielded anything. Do I have to resort to source code? If so, what is the best way to accomplish this? Thanks
You can either Upgrade to Jaunty (Ubuntu 9.04) which has 1.37. You can even incrementally upgrade to just its boost libraries (google for apt-pinning) use a more advanced method I often use: download the Debian package sources from Debian unstable (currently 1.38 with 1.39 in the NEW queue and available "real soon now") and rebuild those locally. You may want to google Debian package building -- and rest assured it is easy as the work has been done, you are merely building local variants from existing sources. This way you stay inside the package management system and are forward-compatible with upgrades if everything else fails, build from source.
1,253,307
1,253,472
Creating planar shadows with 4x3 matrices?
Was just wondering how I would go about creating a planar shadow from a 4x3 matrix, all online demos I've seen use 4x4 matrices instead.
I guess that this is done by projecting a 3D object onto a plane, which essentially needs a fourth coordinate to represent infinity. If you only use 3 coordinates, you can only represent |R^3. However, for projections like shadows you will need full 3-space, thus including infinity - so you need the fourth coordinate. I guess you can solve this with trigonometry and not matrices at all. What is it you are trying to accomplish?
1,253,398
1,253,416
Pass Bitmap object to unmanaged code
I have the following function in C++ managed (ref) class: public static void Transform(Bitmap^ img); I want to call it from C# managed code. What I do is this: Bitmap image = new Bitmap(100, 100); MyClass.Transform(image); Is this correct, or do I need to use fixed statement? If so, then how? Thank you.
You need to lock the bitmap's backing memory as shown here.
1,253,610
1,253,746
Floating point addition: loss-of-precision issues
In short: how can I execute a+b such that any loss-of-precision due to truncation is away from zero rather than toward zero? The Long Story I'm computing the sum of a long series of floating point values for the purpose of computing the sample mean and variance of the set. Since Var(X) = E(X2) - E(X)2, it suffices to maintain running count of all numbers, the sum of all numbers so far, and the sum of the squares of all numbers so far. So far so good. However, it's absolutely required that E(X2) > E(X)2, which due to floating point accuracy isn't always the case. In pseudo-code, the problem is this: int count; double sum, sumOfSquares; ... double value = <current-value>; double sqrVal = value*value; count++; sum += value; //slightly rounded down since value is truncated to fit into sum sumOfSquares += sqrVal; //rounded down MORE since the order-of-magnitude //difference between sqrVal and sumOfSquares is twice that between value and sum; For variable sequences, this isn't a big issue - you end up slightly under-estimating the variance, but it's often not a big issue. However, for constant or almost-constant sets with a non-zero mean, it can mean that E(X2) < E(X)2, resulting in a negative computed variance, which violates expectations of consuming code. Now, I know about Kahan Summation, which isn't an attractive solution. Firstly, it makes the code susceptible to optimization vagaries (depending on optimization flags, code may or may not exhibit this problem), and secondly, the problem isn't really due to the precision - which is good enough - it's because addition introduces systematic error towards zero. If I could execute the line sumOfSquares += sqrVal; in such a way as to ensure that sqrVal is rounded up, not down, into the precision of sumOfSquares, I'd have a numerically reasonable solution. But how can I achieve that? Edit: Finished question - why does pressing enter in the drop-down-list in the tag field submit the question anyhow?
There's another single-pass algorithm which rearranges the calculation a bit. In pseudocode: n = 0 mean = 0 M2 = 0 for x in data: n = n + 1 delta = x - mean mean = mean + delta/n M2 = M2 + delta*(x - mean) # This expression uses the new value of mean variance_n = M2/n # Sample variance variance = M2/(n - 1) # Unbiased estimate of population variance (Source: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance ) This seems better behaved with respect to the issues you pointed out with the usual algorithm.
1,253,670
1,253,686
Why do round() and ceil() not return an integer?
Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer: int rounded = (int) floor(value); Why do all rounding functions (ceil(), floor()) return a floating number, and not an integer? I find this pretty non-intuitive, and would love to have some explanations!
The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type. from the ceil(3) Linux man page.
1,253,856
1,254,190
Using CreateCompatibleDC with mapping modes other than MM_TEXT
I have a visual C++ application that uses a CView derived class to render its display, which is primarily 3d vector data and true type text. The mapping mode used is either MM_ANISOTROPIC or MM_LOMETRIC. I can't use MM_TEXT as I use the same code for printing and plotting of the data and also have to overcome non-square screen pixel issues. The drawing code currently draws directly onto the screen using the CViews OnDraw method and the CDC object provided. I am trying to replace this with drawing to a bitmap and blitting the bitmap to screen, using a CreateCompatibleDC / CreateCompatibleBitmap combination, as described in the MS documentation and elsewhere. The problem is that the DCs are not compatible for mapping modes other than MM_TEXT, such that my view is rendered upside down and at the wrong scale. Investigation shows the following; void CMyView::OnDraw(CDC *pDC) { CDC MyDC = CreateCompatibleDC(pDC); // Create a new memory DC; int a = pDC->GetMapMode(),b = MyDC.GetMapMode(); ' ' ' } a = 2 b = 1 Calling a SetMapMode on MyDC causes the display to be drawn entirely in black. Do I have to rewrite my code to suit MM_TEXT for drawing to a bitmap, or is there another way to overcome this problem.
You probably need to also call SetWindowExt and SetViewportExt. I have definitely used MM_ISOTROPIC with bitmap DCs before and it worked OK (don't have the code to hand as it was since ported to GDI+)
1,253,859
1,253,882
Can virtual functions be used in return values?
I was a little surprised that the following code did not work as expected: #include "stdio.h" class RetA { public: virtual void PrintMe () { printf ("Return class A\n"); } }; class A { public: virtual RetA GetValue () { return RetA (); } }; class RetB : public RetA { public: virtual void PrintMe () { printf ("Return class B\n"); } }; class B : public A { public: virtual RetA GetValue () { return RetB (); } }; int main (int argc, char *argv[]) { A instance_A; B instance_B; RetA ret; printf ("Test instance A: "); ret = instance_A.GetValue (); ret.PrintMe (); // Expected result: "Return class A" printf ("Test instance B: "); ret = instance_B.GetValue (); ret.PrintMe (); // Expected result: "Return class B" return 0; } So, does virtual methods not work when returning a value? Should I revert to allocating the return class on the heap, or is there a better way? (In reality I want to do this to let some different classes that inherits from a container class to return different iterator class instances depending on class ...)
Polymorphic behavior does not work by value, you need to return pointers or references for this to work. If you return by value you get what is known as "slicing" which means that only the parent part of the object gets returned, so you've successfully striped a child object into a parent object, this is not safe at all. Take a look at: What is object slicing?
1,253,928
1,276,199
Extracting Glyph Kerning Information C++
After asking my previous question about Uniscribe glyph kerning, and not yet receiving an answer, plus further reading on google etc, it seems Uniscribe may not support extracting glyph kerning information from a font. I therefore have a simple followup question - are there any good examples (preferably with some C++ code) of extracting glyph kerning information for a specified string from a font? It's mentioned in various places that either Pango, QT or ICU are capable of doing this, but documentation is a bit thin on the ground and I'm struggling to know where to get started. Any help pointing me in the right direction gratefully received. I already have code in place to render the glyphs in the desired way, I am simply after the extended kerning information, so I can position the glyphs a little nicer. Thanks,
OpenType fonts have two different ways to specify kerning information, both of which are optional: The kern table, inherited from TrueType. This table supplies kerning pair information (i.e. how much you should horizontally offset a particular pair of characters). Microsoft provides specs for this table and also supplies some Windows API functions such as GetKerningPair() and GetFontData() that could help you extract values. The GPOS table, an OpenType table which apparently handles every conceivable form of glyph positioning. Microsoft also has some specs for this table, but honestly I don't even know where you'd begin... You'd probably want to look at how ICU handles this sort of stuff. I haven't found much in the way of code samples for any of this, though I'd imagine getting kerning values from the kern table is far simpler than the GPOS table.
1,254,056
1,254,103
What are the available methods in C++ std library, where can I see/read them?
Where can I see all the available methods in std library ? Since, I can include vector,algorithm in my program, can I see header/source files for this library to see how it is implemented ? eg. I know we can use push_back() method in vector, but where can I see all the methods for vector, and similarly for others library ? Is there any documentation for it ? I am using ubuntu, if this helps.
If you want to check the source out, have a look into /usr/include/c++/x.x/vector you'll probable need to redirect your research in this directory (depeding on the class you are looking at): /usr/include/c++/x.x/bits For instance, string class is a typedef, and the underlying type is basic_string you will find in /usr/include/c++/x.x/bits/basic_string
1,254,116
1,255,174
Building a call table to template functions in C++
I have a template function where the template parameter is an integer. In my program I need to call the function with a small integer that is determined at run time. By hand I can make a table, for example: void (*f_table[3])(void) = {f<0>,f<1>,f<2>}; and call my function with f_table[i](); Now, the question is if there is some automatic way to build this table to arbitrary order. The best I can come up with is to use a macro #define TEMPLATE_TAB(n) {n<0>,n<1>,n<2>} which at leasts avoids repeating the function name over and over (my real functions have longer names than "f"). However, the maximum allowed order is still hard coded. Ideally the table size should only be determined by a single parameter in the code. Would it be possible to solve this problem using templates?
You can create a template that initializes a lookup table by using recursion; then you can call the i-th function by looking up the function in the table: #include <iostream> // recursive template function to fill up dispatch table template< int i > bool dispatch_init( fpointer* pTable ) { pTable[ i ] = &function<i>; return dispatch_init< i - 1 >( pTable ); } // edge case of recursion template<> bool dispatch_init<-1>() { return true; } // call the recursive function const bool initialized = dispatch_init< _countof(ftable) >( ftable ); // the template function to be dispatched template< int i > void function() { std::cout << i; } // dispatch functionality: a table and a function typedef void (*fpointer)(); fpointer ftable[100]; void dispatch( int i ){ return (ftable[i])(); } int main() { dispatch( 10 ); }
1,254,196
1,254,212
How to delete folder into recycle bin
I am programing under C++, MFC, windows. I want to delete a folder into recycle bin. How can I do this? CString filePath = directorytoBeDeletePath; TCHAR ToBuf[MAX_PATH + 10]; TCHAR FromBuf[MAX_PATH + 10]; ZeroMemory(ToBuf, sizeof(ToBuf)); ZeroMemory(FromBuf, sizeof(FromBuf)); lstrcpy(FromBuf, filePath); SHFILEOPSTRUCT FileOp; FileOp.hwnd = NULL FileOp.wFunc=FO_DELETE; FileOp.pFrom=FromBuf; FileOp.pTo = NULL; FileOp.fFlags=FOF_ALLOWUNDO|FOF_NOCONFIRMATION; FileOp.hNameMappings=NULL; bRet=SHFileOperation(&FileOp); Any thing wrong with the code above? It always failed. I found the problem: filePath should be : "c:\abc" not "c:\abc\"
The return value from SHFileOperation is an int, and should specify the error code. What do you get?
1,254,244
1,255,558
Need access to "NtSetUuidSeed" from a non-LocalSystem process
I was trying to get a Uuid via NtAllocateUuids or simply calling UuidCreateSequential, but Windows wasn't able to get an Ethernet or token-ring hardware address for my laptop. And so, when the system is booting, windows sets the UuidSeed to a random number instead of a given MAC. --> uniqueness is guaranteed only until the system is next restarted. I was trying to manual set the UuidSeed with NtSetUuidSeed but i was getting a STATUS_ACCESS_DENIED error. "Windows NT/2000 Native API Reference" has following remarks: --The token of the calling thread must have an AuthenticationId of SYSTEM_LUID Is there any way to achieve this from a process, running as Administrator? Something like ImpersonateLoggedOnUser() could work but afaik this is also only accessible as LocalSystem :/ Thx ;)
ImpersonateLoggedOnUser worked fine with a token handle returned from: HANDLE GetLSAToken() //duplicate a system token from the "System" process or BOOL CreatePureSystemToken(HANDLE &hToken) //create a new system token http://www.codeproject.com/KB/system/RunUser.aspx CoreCode.cpp
1,254,335
1,254,376
Where to download GNU C++ compiler
Can anyone suggest me where to download a GNU c++ compiler, which I can use in Ubuntu and also on Windows with Netbeans IDE, and also GNU tools.
If you are using any Linux/Unix/Solaris OS it is available unless you have explicitly not installed. That said, if you still wish to install GNU C++ compiler, use this command sudo aptitude install build-essential and if you wish to download it on your windows, steps are here on Minimalist GNU for Windows
1,254,433
1,254,580
Mixing Objective-C and C++ code
I have an Objective-C/C++ application which uses functionality that is provided by a C++ library. One of the C++ classes includes an enum like this: class TheClass { public: [...] enum TheEnum { YES, NO, }; [...] }; Including (using #import -if that matters-) a header file with the above class declaration in an Objective-C/C++ source file (*.mm) will make the compile fail since the preprocessor will replace "YES" by the term "(BOOL) 1" (and likewise "NO" by "(BOOL) 0"). Is there a way to fix that without renaming the values of the enum?
YES and NO are predefined constants in Objective-C, declared in the objc.h header. You should be able to prevent the preprocessor to expand the "YES" and "NO" macro's. This can be done by locally #undeffing them. But technically, if you're using a language keyword as an identifier, you can expect trouble. You won't write a class containing a member called MAX_PATH, would you?
1,254,777
1,254,793
static cast versus dynamic cast
Possible Duplicate: Regular cast vs. static_cast vs. dynamic_cast I don't quite get when to use static cast and when dynamic. Any explanation please?
Use dynamic_cast when casting from a base class type to a derived class type. It checks that the object being cast is actually of the derived class type and returns a null pointer if the object is not of the desired type (unless you're casting to a reference type -- then it throws a bad_cast exception). Use static_cast if this extra check is not necessary. As Arkaitz said, since dynamic_cast performs the extra check, it requires RTTI information and thus has a greater runtime overhead, whereas static_cast is performed at compile-time.
1,254,840
1,254,998
Should I remove QDebug header for release?
I have a Qt Application and I use qDebug message for my application. However I have gotten lazy and left in a load of: #include <QDebug> in my header files. Should I remove them for a production deployment and what benefit will it give?
You shouldn't remove the header inclusion. If you do so, every statement involving qDebug might give a compiler error. Instead, define the symbol QT_NO_DEBUG_OUTPUT when compiling for release. qDebug will do nothing when that symbol is defined and (hopefully) the compiler will optimize away the calls to a function that does nothing.
1,255,087
1,255,138
Is there a C++ Almanac?
some of you may know the Java Almanac : http://www.exampledepot.com/ where a lot of code snippets exist for a day-to-day use.(like reading a file etc.) I'm currently using C++ and i was just curios if there exists something similar ?
There are some good examples and tutorials on the Josuttis site. The examples are from the The C++ Standard Library - A Tutorial and Reference book.
1,255,157
1,255,197
char array assignment and management
I'm supposed to write a library in c++ that should handle the connections to the kad network. I'm trying to build a packet accordant to those used by aMule&co. And I really can't understand the difference between this code: buffer = "\xe4\x20\x02"; and, for example, this code: char p_buffer[36]; p_buffer[0] = 0xe4; p_buffer[1] = 0x20; p_buffer[2] = 0x02; buffer = p_buffer; (buffer is a private attribute of the class, while p_buffer is a local variable) capturing the packets with wireshark gives me different results (the first one is right as I wanted, the second one not), like I was doing something wrong with little endian / big endian notations, I guess... and why in the constructor of a class can't I modify a [private] "char* buffer" like this: buffer[0] = 0xe4; ? (it does not work, exits without any trace back error) (if it can matter, I'm using crypto++ and boost libraries) thanks in advance for any help_
Your first code sample is roughly equivalent to: static const char buffer_internal[4] = { 0xe4, 0x20, 0x02, 0x00 }; buffer = buffer_internal; The two differences here are: The buffer is null-terminated The buffer is unmodifiable. Attempting to modify it is likely to crash. Your second sample allocates a 36-byte modifiable buffer. However said buffer will also be discarded when it goes out of scope - be very careful here that it's not used after being freed. As for the third sample, have you initialized 'buffer', if it is a pointer? You've not given enough information to really diagnose your error - the full class declaration and constructor would be helpful.
1,255,249
1,255,308
I cant find any documentation for g_io_channel_win32_make_pollfd
Is there a documentation available for g_io_channel_win32_make_pollfd? I want to use this function to create FDs on Windows for IPC between the main thread and a separate thread. It is only briefly mentioned here and doesn't really explain how to use it.
Here's the source code, and there's also a testcase that uses it. Documentation is available in the header it's declared in. If that documentation doesn't appear in the manual, you might want to file a bug with the glib people - it's probably being excluded from the documentation generator due to a bug of some sort.
1,255,366
1,255,377
How can I append data to a std::string in hex format?
I have an existing std::string and an int. I'd like to concatenate the ASCII (string literal) hexadecimal representation of the integer to the std::string. For example: std::string msg = "Your Id Number is: "; unsigned int num = 0xdeadc0de; //3735929054 Desired string: std::string output = "Your Id Number is: 0xdeadc0de"; Normally, I'd just use printf, but I can't do this with a std::string (can I?) Any suggestions as to how to do this?
Use a stringstream. You can use it as any other output stream, so you can equally insert std::hex into it. Then extract it's stringstream::str() function. std::stringstream ss; ss << "your id is " << std::hex << 0x0daffa0; const std::string s = ss.str();
1,255,430
1,255,801
How can I provide access to this buffer with CSingleLock?
I have these two methods for thread-exclusive access to a CMyBuffer object: Header: class CSomeClass { //... public: CMyBuffer & LockBuffer(); void ReleaseBuffer(); private: CMyBuffer m_buffer; CCriticalSection m_bufferLock; //... } Implementation: CMyBuffer & CSomeClass::LockBuffer() { m_bufferLock.Lock(); return m_buffer; } void CSomeClass::ReleaseBuffer() { m_bufferLock.Unlock(); } Usage: void someFunction(CSomeClass & sc) { CMyBuffer & buffer = sc.LockBuffer(); // access buffer sc.ReleaseBuffer(); } What I like about this is, that the user has to make only one function call and can only access the buffer after having locked it. What I don't like is that the user has to release explicitly. Update: These additional disadvantages were pointed out by Nick Meyer and Martin York: The user is able to release the lock and then use the buffer. If an exception occurs before releasing the lock, the buffer remains locked. I'd like to do it with a CSingleLock object (or something similar), which unlocks the buffer when the object goes out of scope. How could that be done?
Use an object that represents the buffer. When this obejct is initialized get the lock and when it is destroyed release the lock. Add a cast operator so it can be used in place of the buffer in any function call: #include <iostream> // Added to just get it to compile struct CMyBuffer { void doStuff() {std::cout << "Stuff\n";}}; struct CCriticalSection { void Lock() {} void Unlock() {} }; class CSomeClass { private: CMyBuffer m_buffer; CCriticalSection m_bufferLock; // Note the friendship. friend class CSomeClassBufRef; }; // The interesting class. class CSomeClassBufRef { public: CSomeClassBufRef(CSomeClass& parent) :m_owned(parent) { // Lock on construction m_owned.m_bufferLock.Lock(); } ~CSomeClassBufRef() { // Unlock on destruction m_owned.m_bufferLock.Unlock(); } operator CMyBuffer&() { // When this object needs to be used as a CMyBuffer cast it. return m_owned.m_buffer; } private: CSomeClass& m_owned; }; void doStuff(CMyBuffer& buf) { buf.doStuff(); } int main() { CSomeClass s; // Get a reference to the buffer and auto lock. CSomeClassBufRef b(s); // This call auto casts into CMyBuffer doStuff(b); // But you can explicitly cast into CMyBuffer if you need. static_cast<CMyBuffer&>(b).doStuff(); }
1,255,545
1,255,583
interfaces for templated classes
I'm working on a plugin framework, which supports multiple variants of a base plugin class CPlugin : IPlugin. I am using a boost::shared_ptr<IPlugin> for all reference to the plugins, except when a subsystem needs the plugin type's specific interface. I also need the ability to clone a plugin into another seprate object. This must return a PluginPtr. This is why CPlugin is a template rather than a straight class. CPlugin::Clone() is where the template paramter is used. The following are the class definitions I am using: IPlugin.h #include "PluginMgr.h" class IPlugin; typedef boost::shared_ptr<IPlugin> PluginPtr; class IPlugin { public: virtual PluginPtr Clone() =0; virtual TYPE Type() const =0; virtual CStdString Uuid() const =0; virtual CStdString Parent() const =0; virtual CStdString Name() const =0; virtual bool Disabled() const =0; private: friend class CPluginMgr; virtual void Enable() =0; virtual void Disable() =0; }; CPlugin.h #include "IPlugin.h" template<typename Derived> class CPlugin : public IPlugin { public: CPlugin(const PluginProps &props); CPlugin(const CPlugin&); virtual ~CPlugin(); PluginPtr Clone(); TYPE Type() const { return m_type; } CStdString Uuid() const { return m_uuid; } CStdString Parent() const { return m_guid_parent; } CStdString Name() const { return m_strName; } bool Disabled() const { return m_disabled; } private: void Enable() { m_disabled = false; } void Disable() { m_disabled = true; } TYPE m_type; CStdString m_uuid; CStdString m_uuid_parent; bool m_disabled; }; template<typename Derived> PluginPtr CPlugin<Derived>::Clone() { PluginPtr plugin(new Derived(dynamic_cast<Derived&>(*this))); return plugin; } An example concrete class CAudioDSP.h #include "Plugin.h" class CAudioDSP : CPlugin<CAudioDSP> { CAudioDSP(const PluginProps &props); bool DoSomethingTypeSpecific(); <..snip..> }; My problem (finally) is that CPluginMgr needs to update m_disabled of the concrete class, however as it is passed a PluginPtr it has no way to determine the type and behave differently according to the template paramater. I can't see how to avoid declaring ::Enable() and ::Disable() as private members of IPlugin instead but this instantly means that every section of the application now needs to know about the CPluginMgr class, as it is declared as a friend in the header. Circular dependancy hell ensues. I see another option, declare the Enable/Disable functions as private members of CPlugin and use boost::dynamic_pointer_cast<CVariantName> instead. void CPluginMgr::EnablePlugin(PluginPtr plugin) { if(plugin->Type == PLUGIN_DSPAUDIO) { boost::shared_ptr<CAudioDSP> dsp = boost::dynamic_pointer_cast<CAudioDSP>(plugin); dsp->Enable(); } } This however leads to lots of duplicate code with many multiple variants of the base CPlugin template. If anyone has a better suggestion please share it!
You can easily write : class CPluginMgr; class IPlugIn .. { friend CPluginMgr; ... }; Only a predefinition is needed for friend.
1,255,559
4,655,887
Integrate ITK (Insight Toolkit) into own project
i am having problems integrating ITK - Insight Toolkit into another image processing pipeline. ITK itself is a medical image processing toolkit and uses cmake as build system. My image pipeline project uses cmake as well. According to the user manual of ITK it is favorable to use the "UseITK.cmake" file in the build (out of source) directory of ITK. You can do that by adding the following lines the CMakeList.txt of your own project. # 'SET(ITK_DIR ...)' if 'FIND_PACKAGE(ITK REQUIRED)' fails FIND_PACKAGE(ITK REQUIRED) INCLUDE(${ITK_USE_FILE}) My problem is, this approach points to the current installtion of ITK, but i have to integrate itk completly into my project, without dependencies outside my project. Is there a build option in the cmake build system of itk, which dumps/delivers all the header and lib files into a build directory, so i can place them into my project on my own. I have a lib and header include structure i do not want to break. I already tried to to manually copy the lib and header files into my project but it didn't work out. I am new to itk and cmake so this question might sound vague. I hope you guys can help me anyway. Thanks in advance! Best regards, zhengtonic
I don't know if you're still having the problem, but here's an easy way: Build the ITK project, and then "make install" (or build the INSTALL.vcproj project in VS), and it will write to a directory you pass as CMAKE_INSTALL_PREFIX while configuring your project. This directory will contain /bin, /lib and /include. You can import those into your project directly.
1,255,576
1,255,904
What is good practice for generating verbose output?
what is good practice for generating verbose output? currently, i have a function bool verbose; int setVerbose(bool v) { errormsg = ""; verbose = v; if (verbose == v) return 0; else return -1; } and whenever i want to generate output, i do something like if (debug) std::cout << "deleting interp" << std::endl; however, i don't think that's very elegant. so i wonder what would be a good way to implement this verbosity switch?
The simplest way is to create small class as follows(here is Unicode version, but you can easily change it to single-byte version): #include <sstream> #include <boost/format.hpp> #include <iostream> using namespace std; enum log_level_t { LOG_NOTHING, LOG_CRITICAL, LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG }; namespace log_impl { class formatted_log_t { public: formatted_log_t( log_level_t level, const wchar_t* msg ) : fmt(msg), level(level) {} ~formatted_log_t() { // GLOBAL_LEVEL is a global variable and could be changed at runtime // Any customization could be here if ( level <= GLOBAL_LEVEL ) wcout << level << L" " << fmt << endl; } template <typename T> formatted_log_t& operator %(T value) { fmt % value; return *this; } protected: log_level_t level; boost::wformat fmt; }; }//namespace log_impl // Helper function. Class formatted_log_t will not be used directly. template <log_level_t level> log_impl::formatted_log_t log(const wchar_t* msg) { return log_impl::formatted_log_t( level, msg ); } Helper function log was made template to get nice call syntax. Then it could be used in the following way: int main () { // Log level is clearly separated from the log message log<LOG_DEBUG>(L"TEST %3% %2% %1%") % 5 % 10 % L"privet"; return 0; } You could change verbosity level at runtime by changing global GLOBAL_LEVEL variable.
1,255,919
1,256,218
boost::ifind_first with std::string objects
I am trying to use boost string algorithms for case insensitive search. total newbie here. if I am using it this way, I get an error. std::string str1("Hello world"); std::string str2("hello"); if ( boost::ifind_first(str1, str2) ) some code; Converting to char pointers resolves the problem. boost::ifind_first( (char*)str1.c_str(), (char*)str2.c_str() ); Is there a way to search std::string objects directly? Also, maybe there is another way to know if string is present inside another string with case-insensitive search?
You need to use boost::iterator_range. This works: typedef const boost::iterator_range<std::string::const_iterator> StringRange; std::string str1("Hello world"); std::string str2("hello"); if ( boost::ifind_first( StringRange(str1.begin(), str1.end()), StringRange(str2.begin(), str2.end()) ) ) std::cout << "Found!" << std::endl; EDIT: Using a const iterator_range in the typedef allows passing a temporary range.
1,255,945
1,256,570
C# vs. C++ in a cross-platform project
My team is planning to develop an application that is initially targeted for Windows but will eventually be deployed cross-platform (Mac, Linux and potentially embedded devices). Our decision is whether to use C#/.NET or generic C++ (with Qt as the user interface library). We’re projecting that by using C#, we can develop our product faster and at a lower cost due to the increase of productivity over C++, but we’re taking a gamble on whether cross-platform implementations of C# will be mature enough at the time when we want to roll out to other platforms. Any suggestions from any of you who have been in a similar situation?
Despite all the potential cross platform capabilities of Mono, today, C++/Qt is simply a much more mature option than either C#/WinForms or C#/Gtk# for cross-platform purposes. Any productivity gains you would get by using a higher-level language would likely be offset by dealing with limitations of Mono.
1,256,191
1,256,230
Why do libraries implement their own basic locks on windows?
Windows provides a number of objects useful for synchronising threads, such as event (with SetEvent and WaitForSingleObject), mutexes and critical sections. Personally I have always used them, especially critical sections since I'm pretty certain they incur very little overhead unless already locked. However, looking at a number of libraries, such as boost, people then to go to a lot of trouble to implement their own locks using the interlocked methods on Windows. I can understand why people would write lock-less queues and such, since thats a specialised case, but is there any reason why people choose to implement their own versions of the basic synchronisation objects?
Libraries aren't implementing their own locks. That is pretty much impossible to do without OS support. What they are doing is simply wrapping the OS-provided locking mechanisms. Boost does it for a couple of reasons: They're able to provide a much better designed locking API, taking advantage of C++ features. The Windows API is C only, and not very well-designed C, at that. They are able to offer a degree of portability. the same Boost API can be used if you run your application on a Linux machine or on Mac. Windows' own API is obviously Windows-specific. The Windows-provided mechanisms have a glaring disadvantage: They require you to include windows.h, which you may want to avoid for a large number of reasons, not least its extreme macro abuse polluting the global namespace.
1,256,240
1,256,280
Why is Boost scoped_lock not unlocking the mutex?
I've been using boost::mutex::scoped_lock in this manner: void ClassName::FunctionName() { { boost::mutex::scoped_lock scopedLock(mutex_); //do stuff waitBoolean=true; } while(waitBoolean == true ){ sleep(1); } //get on with the thread's activities } Basically it sets waitBoolean, and the other thread signals that it is done by setting waitBoolean to false; This doesn't seem to work, however, because the other thread can't get a lock on mutex_ !! I was assuming that by wrapping the scoped_lock in brackets I would be terminating its lock. This isn't the case? Reading online says that it only gives up the mutex when the destructor is called. Won't it be destroyed when it goes out of that local scope? Signaling part of code: while(running_){ boost::mutex::scoped_lock scopedLock(mutex_); //Run some function that need to be done... if(waitBoolean){ waitBoolean=false; } } Thanks!
The scoped_lock should indeed be released at the end of the scope. However you don't lock the waitBoolean when you're looping on it, suggesting you don't protect it properly other places as well - e.g. where it's set to false, and you'll end up with nasty race conditions. I'd say you should use a boost::condition_variable to do this sort of things, instead of sleep + thread-unsafe checking.
1,256,246
1,256,273
Address of register variable
In C, we cannot use & to find out the address of a register variable but in C++ we can do the same. Why is it legal in C++ but not in C? Can someone please explain this concept in-depth.
Here's an excerpt from Section 6.7.1 (footnote 101) of the C99 standard (pdf): The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register cannot be computed, either explicitly (by use of the unary & operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in 6.3.2.1). Thus, the only operator that can be applied to an array declared with storage-class specifier register is sizeof. And from Section 7.1.1, Paragraph 3 of the C++ standard (pdf): A register specifier has the same semantics as an auto specifier together with a hint to the implementation that the object so declared will be heavily used. [Note: the hint can be ignored and in most implementations it will be ignored if the address of the object is taken. —end note] Fun tidbits about register The C++ group (WG21) wants to deprecate register: The register keyword serves very little function, offering no more than a hint that a note says is typically ignored. It should be deprecated in this version of the standard, freeing the reserved name up for use in a future standard, much like auto has been re-used this time around for being similarly useless. Notes from the March, 2009 meeting: The consensus of the CWG was in favor of deprecating register. Look what the C99 group (WG14) said about register (pdf) at a meeting: General agreement to deprecate the “auto” keyword. Should we ask WG21 to go back to the previous use of “register” (no address)? No, this will not fly with WG21.
1,256,395
1,256,407
stl vector.push_back() abstract class doesn't compile
Let's say I have an stl vector containing class type "xx". xx is abstract. I have run into the issue where the compiler won't let me "instantiate" when i do something like the following: std::vector<xx> victor; void pusher(xx& thing) { victor.push_back(thing); } void main() { ; } I assume this is because the copy constructor must be called. I have gotten around this issue by storing xx*'s in the vector rather than xx's. Is there a better solution? What is it?
When you use push_back, you are making a copy of the object and storing it in the vector. As you surmised, this doesn't work since you can't instantiate an abstract class, which is basically what the copy-construction is doing. Using a pointer is recommended, or one of the many smart-pointer types available in libraries like boost and loki.
1,256,584
1,256,687
c++ strange c0000005 error
I am working on a project that can start a program on the winlogon desktop. The program works perfectly while debugging but when I start it outside the ide it fails strangly with the infamous c0000005 error. The weirdest thing though is it doesn't seem to occur on any particular line. Here is the code: #include "stdafx.h" #include <windows.h> #include "BinRes.h" #include <string> #include <iostream> int main(int argc, char* argv[]) { if(argc != 2) { return 0; } std::string a; a.append(BinRes::getAppLocation()); a.append("\\wls.exe"); BinRes::ExtractBinResource("EXE",102,"wls.exe"); Sleep(500); SC_HANDLE schsm; schsm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS); SC_HANDLE schs; schs = CreateService(schsm,"WLS","WLS",SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,SERVICE_DEMAND_START,NULL,a.c_str(),0,0,0,0,0); char* cd = argv[1]; LPCSTR* arg = (LPCSTR*)&cd; StartService(schs,1,arg); HANDLE endevent; endevent = OpenEvent(EVENT_ALL_ACCESS,TRUE,"ENDWLS"); WaitForSingleObject(endevent,INFINITE); SERVICE_STATUS ss; QueryServiceStatus(schs,&ss); if(ss.dwCurrentState != SERVICE_STOPPED) { LPSERVICE_STATUS xyz = (LPSERVICE_STATUS)malloc(sizeof(LPSERVICE_STATUS)); ControlService(schs,SERVICE_CONTROL_STOP,xyz); } DeleteService(schs); //error occurs right here DeleteFile(a.c_str()); return 0; } The error always occurs after DeleteService and before the next line but I'm sure it isn't DeleteService because the service is deleted. I tried commenting out DeleteService and DeleteFile but it still crashes. I'm sure I've made some bonehead mistake and am just going blind. Thanks in advance for the help!
I think the problem lies within the LPSERVICE_STATUS xyz = (LPSERVICE_STATUS)malloc(sizeof(LPSERVICE_STATUS)); ControlService(schs,SERVICE_CONTROL_STOP,xyz); part. The last argument xyz to ControlService is used by that API to return status information about the service. You are actually passing a pointer to a pointer sized memory region here, which is too small to hold all the values, which ControlService would like to fill in. IMHO you get bitten at run-time, because executing the ControlService call will override random memory directly after the space for the pointer allocated by malloc. Try SERVICE_STATUS xyz; memset(&xyz, 0, sizeof(xyz)); ControlService(schs, SERVICE_CONTROL_STOP, &xyz); instead. There is no need to allocate the structure dynamically here. According to the documentation, the ControlService will only use it to return status information; it won't be stored somewhere within Windows internal data structures. More about the content of the structure can be in the MS documentation. No idea, why it might work during debugging. Maybe, the malloc linked against for debugging behaves slightly differently in comparison to the production version malloc?
1,256,614
1,498,792
Catching a WM_NOTIFY message from a custom ListCtrl
My application is c++, and is a combination of MFC and ATL. The part I'm working with here is MFC. I have a custom list control class in one of my dialogs which inherits from CListCtrl. I'm trying to add a handler for the LVN_ITEMCHANGED message so I can update the rest of the dialog form, which is dependant on the contents of the list. More specifically, each list item has a checkbox field and I need to detect when that has been changed. The problem is, my list isn't sending out the message. ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_OUTPUT_CMDS, OnLvnItemchangedListOutputCmds) That's my message map and it works just fine, I've detected other messages like LVN _ ITEMCHANGING, NM_CLICK, and NM _ RELEASEDCAPTURE by simply changing the message. My guess is therefore that the listctrl custom class is somehow not posting the message properly. This question can be answered many ways: 1. How can I post the LVN_ITEMCHANGED message from the child list to it's parent (the dialog)? 2. Am I even catching the right message? Most of the ones I've tried have triggered the update too soon (i.e. before the data in the list is updated) When I do this, the dialog refreshes based on the previous state of the list. 3. Is there something else I should be doing that I'm not? I ask this just to make it open ended.
I've moved this question to stackoverflow.com/questions/1272398 The answer is posted there.
1,256,768
1,256,898
C++: 2D arrays vs. 1D array differences
I have an array of float rtmp1[NMAX * 3][3], and it is used as rtmp1[i][n], where n is from 0 to 2, and i is from 0 to 3 * NMAX - 1. However, I would like to convert rtmp1 to be rtmp1[3 * 3 * NMAX]. Would addressing this new 1D array as rtmp1[3 * i + n] be equivalent to rtmp1[i][n]? Thanks in advance for the clarifications.
rtmp1[i][n] is equivalent to rtmp1[i*NMAX + n] See http://www.cplusplus.com/doc/tutorial/arrays/, where your NMAX is their width.
1,256,803
1,256,923
Using abstract class as a template type
I'm still pretty new to c++ (coming over from java). I have a stl list of type Actor. When Actor only contained "real" methods there was no problem. I now want to extend this class to several classes, and have a need to change some methods to be abstract, since they don't make sense as concrete anymore. As I expected (from the documentation) this is bad news because you can no longer instantiate Actor, and so when I iterate through my list I run into problems. What is the c++ way to do this? Sorry if there's anything unclear
You can not handle this directly: As you can see when the class is abstract you can not instanciate the object. Even if the class where not abstract you would not be able to put derived objects into the list because of the slicing problem. The solution is to use pointers. So the first question is who owns the pointer (it is the responcability of the owner to delete it when its life time is over). With a std::list<> the list took ownership by creating a copy of the object and taking ownership of the copy. But the destructor of a pointer does nothing. You need to manually call the delete on a pointer to get the destructor of the obejct to activate. So std::list<> is not a good option for holding pointers when it also needs to take ownership. Solution 1: // Objects are owned by the scope, the list just holds apointer. ActorD1 a1; Actor D1 derived from Actor ActorD2 a2; ActorD2 a3; std::list<Actor*> actorList; actorList.push_back(&a1); actorList.push_back(&a2); actorList.push_back(&a3); This works fine as the list will go out of scope then the objects everything works fine. But this is not very useful for dynamically (run-time) created objects. Solution 2: Boost provides a set of containers that handle pointers. You give ownership of the pointer to the container and the object is destroyed by the containter when the container goes out ofd scope. boost::ptr_list<Actor> actorList; actorList.push_back(new ActorD1); actorList.push_back(new ActorD2); actorList.push_back(new ActorD2);
1,256,963
1,256,988
If MessageBox()/related are synchronous, why doesn't my message loop freeze?
Why is it that if I call a seemingly synchronous Windows function like MessageBox() inside of my message loop, the loop itself doesn't freeze as if I called Sleep() (or a similar function) instead? To illustrate my point, take the following skeletal WndProc: int counter = 0; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: SetTimer(hwnd, 1, 1000, NULL); //start a 1 second timer break; case WM_PAINT: // paint/display counter variable onto window break; case WM_TIMER: //occurs every second counter++; InvalidateRect(hwnd, NULL, TRUE); //force window to repaint itself break; case WM_LBUTTONDOWN: //someone clicks the window MessageBox(hwnd, "", "", 0); MessageBeep(MB_OK); //play a sound after MessageBox returns break; //default .... } return 0; } In the above example, the program's main function is to run a timer and display the counter's value every second. However, if the user clicks on our window, the program displays a message box and then beeps after the box is closed. Here's where it gets interesting: we can tell MessageBox() is a synchronous function because MessageBeep() doesn't execute until the message box is closed. However, the timer keeps running, and the window is repainted every second even while the message box is displayed. So while MessageBox() is apparently a blocking function call, other messages (WM_TIMER/WM_PAINT) can still be processed. That's fine, except if I substitute MessageBox for another blocking call like Sleep() case WM_LBUTTONDOWN: Sleep(10000); //wait 10 seconds MessageBeep(MB_OK); break; This blocks my application entirely, and no message processing occurs for the 10 seconds (WM_TIMER/WM_PAINT aren't processed, the counter doesn't update, program 'freezes', etc). So why is it that MessageBox() allows message processing to continue while Sleep() doesn't? Given that my application is single-threaded, what is it that MessageBox() does to allow this functionality? Does the system 'replicate' my application thread, so that way it can finish the WM_LBUTTONDOWN code once MessageBox() is done, while still allowing the original thread to process other messages in the interim? (that was my uneducated guess) Thanks in advance
The MessageBox() and similar Windows API functions are not blocking the execution, like an IO operation or mutexing would do. The MessageBox() function creates a dialog box usually with an OK button - so you'd expect automatic handling of the window messages related to the message box. This is implemented with its own message loop: no new thread is created, but your application remains responsive, because selected messages (like for painting) are handled calling recursively your WndProc() function, while other messages are not transmitted, because of the modal type of the created window. Sleep() and other functions (when called directly from your WndProc() handling a window message) would actually block the execution of your single threaded message loop - no other message would be processed.
1,257,115
1,257,375
how to find allocated memory in linux
Good afternoon all, What I'm trying to accomplish: I'd like to implement an extension to a C++ unit test fixture to detect if the test allocates memory and doesn't free it. My idea was to record allocation levels or free memory levels before and after the test. If they don't match then you're leaking memory. What I've tried so far: I've written a routine to read /proc/self/stat to get the vm size and resident set size. Resident set size seems like what I need but it's obviously not right. It changes between successive calls to the function with no memory allocation. I believe it's returning the cached memory used not what's allocated. It also changes in 4k increments so it's too coarse to be of any real use. I can get the stack size by allocating a local and saving it's address. Are there any problems with doing this? Is there a way to get real free or allocated memory on linux? Thanks
I'd have to agree with those suggesting Valgrind and similar, but if the run-time overhead is too great, one option may be to use mallinfo() call to retrieve statistics on currently allocated memory, and check whether uordblks is nonzero. Note that this will have to be run before global destructors are called - so if you have any allocations that are cleaned up there, this will register a false positive. It also won't tell you where the allocation is made - but it's a good first pass to figure out which test cases need work.
1,257,161
1,257,179
Array Allocation Subscript Number
Quick question regarding how memory is allocated. If someone were to allocate 20 chars like this: char store[20]; does this mean that it allocated 20 char type blocks of memory, or that it allocated char type blocks of memory starting with 0 and ending with 20. The difference is that the first example's range would be from store[0] to store[19], whereas the second example's range would be from store[0] to store[20].
It means it allocated one block of memory large enough to hold 20 chars (from index 0 to 19)
1,257,182
1,257,253
Only 2 digits in exponent in scientific ofstream
So according to cplusplus.com when you set the format flag of an output stream to scientific notation via of.setf(ios::scientific) you should see 3 digits plus and a sign in the exponent. However, I only seem to get 2 in my output. Any ideas? Compiled on Mac OS using GCC 4.0.1. Here's the actual code I am using: of.setf(ios::scientific); of.precision(6); for (int i=0;i<dims[0];++i) { for (int j=0;j<dims[1];++j) { of << setw(15) << data[i*dims[1]+j]; } of << endl; } and an example line of output: 1.015037e+00 1.015037e+00 1.395640e-06 -1.119544e-06 -8.333264e-07 Thanks
I believe cplusplus.com is incorrect, or at least is documenting a particular implementation - I can't see any other online docs which specifically state the number of exponent digits which are displayed - I can't even find it in the C++ specification. Edit: The C++ Standard Library: A Tutorial and Reference doesn't explicitly state the number of exponent digits; but all it's examples display two exponent digits.
1,257,219
1,257,263
C++ "conversion loses qualifiers" compile error
I ran into an interesting problem while debugging SWIG typemaps today. Anyone care to enlighten me why Visual C++ 2008 throws a "conversion loses qualifiers" error when converting from ourLib::Char * to const ourLib::Char * &? I thought Type * -> const Type * was a trivial conversion, and (when calling functions) Lvalue -> Lvalue & as well. EDIT: The solution we ended up going with: // ourLib::Char is a typedef'ed char on Win32 %typemap(in) const char* (const ourLib::Char* tmp) { if (!bapiLua::LuaTraits<ourLib::Char*>::FromLuaObject(L, $argnum, tmp)) SWIG_fail; $1 = const_cast<char *>(tmp); } // And in a different source file, already written: namespace bapiLua { template<> struct LuaTraits<ourLib::Char*> { static ourLib::Bool FromLuaObject(lua_State* L, int pos, const ourLib::Char*& o_result); }; } Removing the const from const ourLib::Char * tmp causes the error I described.
Say you had the following function: void test( const char*& pRef) { static const char somedata[] = { 'a' ,'b', 'c', '\0'}; pRef = somedata; } If you passed in a non-const char*, then when test() returned the compiler would have lost the fact that what p is pointing to is const. It's essentially the same reason as given in this C++ FAQ Lite question (dealing with pointers-to-pointers rather than pointer references): http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17
1,257,267
1,257,366
Is it legal C++ to pass the address of a static const int with no definition to a template?
I'm having trouble deciding whether not this code should compile or if just both compilers I tried have a bug (GCC 4.2 and Sun Studio 12). In general, if you have a static class member you declare in a header file you are required to define it in some source file. However, an exception is made in the standard for static const integrals. For example, this is allowed: #include <iostream> struct A { static const int x = 42; }; With no need to add a definition of x outside the class body somewhere. I'm trying to do the same thing, but I also take the address of x and pass it to a template. This results in a linker error complaining about a lack of definition. The below example doesn't link (missing a definition for A::x) even when it's all in the same source file: #include <iostream> template<const int* y> struct B { static void foo() { std::cout << "y: " << y << std::endl; } }; struct A { static const int x = 42; typedef B<&x> fooness; }; int main() { std::cout << A::x << std::endl; A::fooness::foo(); } Which is bizarre since it works as long as I don't pass the address to a template. Is this a bug or somehow technically standards compliant? Edit: I should point out that &A::x is not a runtime value. Memory is set aside for statically allocated variables at compile time.
To be a well formed program you stil have to have the defintion of the static variable (without an initializer in this case) if it actually gets used, and taking the address counts as a use: C++2003 Standard: 9.4.2 Static data members Paragraph 4 (bold added) If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer
1,257,493
1,257,506
Given text in a #define, can it somehow be passed to a template?
Say I have a macro, FOO(name), and some template class Bar<> that takes one parameter (what type of parameter is the question). Everytime I call FOO with a different name, I want to get a different instantiation of Bar. The Bar<> template doesn't actually need to be able to get at the name internally, I just need to be sure that different names create different instances of Bar<> and that using the same name (even in different translation units) always gets at the same instance of Bar<>. So here's a rough first attempt: template<const char* x> class Bar { //... stuff }; #define FOO(name) Bar<#name> This would work, except that char literals can't be passed as template parameters because they don't have external linkage. If there was someway in the preprocessor to get a consistent hash of 'name' to say, an int (which can then be passed to the template) that would work, but I don't see any way to do that. Ideas?
Depending on where you intend to use this macro (namespace or class scope would work), you could create a tag type and use that: template<typename T> class Bar { //... stuff }; #define FOO(name) struct some_dummy_tag_for_##name {}; Bar<some_dummy_tag_for_##name> If this doesn't work, maybe you can "declare" those names before-hand: #define DECLARE_FOO(name) struct some_dummy_tag_for_##name {} #define FOO(name) Bar<some_dummy_tag_for_##name> // something.h DECLARE_FOO(foobar); // something.cpp FOO(foobar);
1,257,507
1,257,514
What does this mean const int*& var?
I saw someone using this in one answer: void methodA(const int*& var); I couldn't understand what the argument means. AFAIK: const int var => const int value which can't be changed const int* var => pointer to const int, ie *var can't be changed but var can be changed const int& var => reference to const int, ie value of var can't be changed What does const int*& var mean? Is const int& *var also possible? Can you please give some example as well, like what can and can't be done with it? UPDATE: I am not sure if I am thinking the right way, but I began to think of a reference as an alias of the variable that was passed as argument, so: const int * p; methodA(p) => here we are passing p as const int * but we don't know if this is pass by value or what, until we see the definition of methodA, so if methodA is like this: methodA(const int * & p2) ==> here p2 is another name to p, ie p and p2 are the same from now on methodA(const int* p2) ==> here p2 is passed as value, ie p2 is just local to this method Please correct me if I am thinking the wrong way. If yes, I might need to study some more about this. Can you please point to some nice references? UPDATE 2: If some beginner like me wants to know more about this thing, you can use the c++decl / cdecl program from here, which I just discovered to be very useful. $ c++decl Type `help' or `?' for help c++decl> explain const int&* p declare p as pointer to reference to const int c++decl> explain const int*& p declare p as reference to pointer to const int But, as every one here pointed out, the first example isn't legal in C++.
It is a reference to a pointer to an int that is const. There is another post somewhat related, actually, here. My answer gives a sorta of general algorithm to figuring these things out. This: const int& *var has no meaning, because you cannot have a pointer to reference. If the const's and pointers are getting in the way, remember you can typedef these things: typedef int* IntPointer; typedef const IntPointer ConstIntPointer; void foo(ConstIntPointer&); // pass by reference void bar(const ConstIntPointer&); // pass by const reference void baz(ConstIntPointer); // pass by value Might make it easier to read. If you need more help on C++, read this. More specifically, references. References as variables do not take space: int i; // takes sizeof(int) int*pi = &i; // takes sizeof(int*) int& ri = i; // takes no space. // any operations done to ri // are simply done to i References as parameters use pointers to achieve the end effect: void foo(int& i) { i = 12; } void foo_transformed(int *i) { *i = 12; } int main() { int i; foo(i); // same as: foo_transformed(&i); // to the compiler (only sort of) } So it's actually passing the address of i on the stack, so takes sizeof(int*) space on the stack. But don't start thinking about references as pointers. They are not the same.
1,257,638
1,264,991
Variable sized structs with trailers
I posted on this topic earlier but now I have a more specific question/problem. Here is my code: #include <cstdlib> #include <iostream> typedef struct{ unsigned int h; unsigned int b[]; unsigned int t; } pkt; int main(){ unsigned int* arr = (unsigned int*) malloc(sizeof(int) * 10); arr[0] = 0xafbb0000; arr[1] = 0xafbb0001; arr[2] = 0xafbb0011; arr[3] = 0xafbb0111; arr[4] = 0xafbb1111; arr[5] = 0xafbc0000; arr[6] = 0xafbc0001; arr[7] = 0xafbc0011; arr[8] = 0xafbc0111; arr[9] = 0xafbc1111; pkt* p = (pkt*) malloc(sizeof(int)*13); p->h = 0x0905006a; int counter; Here's what I get for(counter=0; counter < 10; counter++) p->b[counter] = arr[counter]; p->t = 0x55555555; std::cout << "header is \n" << p->h << std::endl; std::cout << "body is" << std::endl; for(counter=0; counter < 10;++counter) std::cout << std::hex << *((p->b)+counter) << std::endl; std::cout << "trailer is \n" << p->t << std::endl; } Here's what I get header is 151322730 body is 55555555 afbb0001 afbb0011 afbb0111 afbb1111 afbc0000 afbc0001 afbc0011 afbc0111 afbc1111 trailer is 55555555 *(p->b) is replaced with the trailer! And if I remove the line where I assigned the trailer, that is p->t=0x55555555;, then the trailer and p->b are the same (afbb0000). So my question is, how can I keep the structure define at the top the way it is and have this packet function properly. EDIT: I should be more clear. I writing this for a networking application, so I have to make a packet where the output is in this exact order, I am testing this by writing to a file and doing a hex dump. So my question really is: How do I make a packet with a header, variable sized body, and a trailer always have this order? The only two solutions I can think of are having many different structures, or having a vector. That is, I could structs where typedef struct{ unsigned int h; unsigned int b[12]; unsigned int t; } pkt1; typedef struct{ unsigned int h; unsigned int b[102]; unsigned int t; } pkt2; etc or I could do std::vector<unsigned int> pkt (12); pkt[0] = header; pkt[1] = data; ... pkt[2]= data; pkt[11] = trailer; I don't really like either of these solutions though. Is there a better way?? Also, this is somewhat of a separate question, I will have to do the same thing for receiving data. It is wise to do something like cast a block of data to a vector? I am going to be receiving the data as a void* and I will know the max length.
A C++ solution: #include <iostream> using namespace std; class Packet { public: Packet (int body_size) : m_body_size (body_size) { m_data = new int [m_body_size + 2]; } ~Packet () { delete [] m_data; m_data = 0; } int &Header () { return m_data [0]; } int &Trailer () { return m_data [m_body_size + 1]; } int Size () { return m_body_size; } int *Data () { return m_data; } int &operator [] (int index) { return m_data [index + 1]; } // helper to write class data to an output stream friend ostream &operator << (ostream &out, Packet &packet) { out << "Header = " << packet.Header () << endl; out << "Data [" << packet.Size () << "]:" << endl; for (int i = 0 ; i < packet.Size () ; ++i) { out << " [" << i << "] = 0x" << hex << packet [i] << endl; } out << "Trailer = " << packet.Trailer () << endl; return out; } private: int m_body_size, *m_data; }; // simple test function for Packet class int main () { Packet packet (10); packet.Header () = 0x0905006a; packet [0] = 0xafbb0000; packet [1] = 0xafbb0001; packet [2] = 0xafbb0011; packet [3] = 0xafbb0111; packet [4] = 0xafbb1111; packet [5] = 0xafbc0000; packet [6] = 0xafbc0001; packet [7] = 0xafbc0011; packet [8] = 0xafbc0111; packet [9] = 0xafbc1111; packet.Trailer () = 0x55555555; cout << packet; } I've not put error checking in or const accessors, you can bounds check the array access. Receiving data is straightforward: Packet Read (stream in) { get size of packet (exluding header/trailer) packet = new Packet (size) in.read (packet.Data, size + 2) return packet }
1,257,640
1,257,657
Boost Program Options Examples
In the boost tutorials online for program options : http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/tutorial.html#id2891824 It says that the complete code examples can be found at "BOOST_ROOT/libs/program_options/example" directory. I could not figure out where is this. Can anyone help me finding the examples?
On Debian systems, you find it in /usr/share/doc/libboost-doc/examples/libs/program_options. Otherwise, I suggest to download the archive from boost.org and have a look there.
1,257,643
1,257,654
Writing an app to interact with SQL 2008 without managed code
I want to write a winPE(vista) application that connects to a DB and just writes a row in a table saying it booted winPE. Here is my problem. I only ever do .NET. I'm pretty familiar with OO concepts so I'm finally taking the plunge to unmanaged code. I assume I have to use visual studio's unmanaged c++ project type, but I don't know where to go from there; what header files do I need? Are there any I can leverage? Are there any good tutorials for this type of thing?
Personally, I use OLEDB for all my old data access, its the underlying system that drives the others while still being cross-DB, so it might not be as easy to use as ADO, but once you get the concepts, create the classes to hold the data rows, its really simple. Here's some example code that should be useable almost as it is.
1,257,721
1,259,198
Can I use a mask to iterate files in a directory with Boost?
I want to iterate over all files in a directory matching something like somefiles*.txt. Does boost::filesystem have something built in to do that, or do I need a regex or something against each leaf()?
EDIT: As noted in the comments, the code below is valid for versions of boost::filesystem prior to v3. For v3, refer to the suggestions in the comments. boost::filesystem does not have wildcard search, you have to filter files yourself. This is a code sample extracting the content of a directory with a boost::filesystem's directory_iterator and filtering it with boost::regex: const std::string target_path( "/my/directory/" ); const boost::regex my_filter( "somefiles.*\.txt" ); std::vector< std::string > all_matching_files; boost::filesystem::directory_iterator end_itr; // Default ctor yields past-the-end for( boost::filesystem::directory_iterator i( target_path ); i != end_itr; ++i ) { // Skip if not a file if( !boost::filesystem::is_regular_file( i->status() ) ) continue; boost::smatch what; // Skip if no match for V2: if( !boost::regex_match( i->leaf(), what, my_filter ) ) continue; // For V3: //if( !boost::regex_match( i->path().filename().string(), what, my_filter ) ) continue; // File matches, store it all_matching_files.push_back( i->leaf() ); } (If you are looking for a ready-to-use class with builtin directory filtering, have a look at Qt's QDir.)
1,257,744
1,257,760
Can I use break to exit multiple nested 'for' loops?
Is it possible to use the break function to exit several nested for loops? If so, how would you go about doing this? Can you also control how many loops the break exits?
AFAIK, C++ doesn't support naming loops, like Java and other languages do. You can use a goto, or create a flag value that you use. At the end of each loop check the flag value. If it is set to true, then you can break out of that iteration.
1,257,844
1,257,892
Getting mouse position unbounded by screen size, c++ & windows
I'm currently writing a c++ console application that grabs the mouse position at regular intervals and sends it to another visual application where it is used to drive some 3d graphics in real time. The visual app is closed source and cannot be altered outside it's limited plug-in functionality. Currently I'm using the GetCursorPos() function which is easy and fast enough, but I'm running into the issue that all of the data is clipped based on the current screen resolution of 1920x1600 so that all x values are between 0 and 1920 and all y values are between 0 and 1600 no matter how far the mouse is physically moved. I need to get the mouse position before it's clipped at the edge of the screen, or possibly the deltas which I could use to calculate the current position. I've seen some references to the windows MouseMove event but I would really not want to implement a window to make it work or especially have it as the active to receive those events. I'm working in a windows environment and a language change is not feasible.
I don't have any direct experience with raw input, which is probably what you need to tap into. According to MSDN, you have to register the device, then setup your winproc to accept the WM_INPUT messages and then do your calculations based on the raw data. Here's another relevant link.
1,258,051
3,389,144
0xDEADBEEF equivalent for 64-bit development?
For C++ development for 32-bit systems (be it Linux, Mac OS or Windows, PowerPC or x86) I have initialised pointers that would otherwise be undefined (e.g. they can not immediately get a proper value) like so: int *pInt = reinterpret_cast<int *>(0xDEADBEEF); (To save typing and being DRY the right-hand side would normally be in a constant, e.g. BAD_PTR.) If pInt is dereferenced before it gets a proper value then it will crash immediately on most systems (instead of crashing much later when some memory is overwritten or going into a very long loop). Of course the behavior is dependent on the underlying hardware (getting a 4 byte integer from the odd address 0xDEADBEEF from a user process may be perfectly valid), but the crashing has been 100% reliable for all the systems I have developed for so far (Mac OS 68xxx, Mac OS PowerPC, Linux Redhat Pentium, Windows GUI Pentium, Windows console Pentium). For instance on PowerPC it is illegal (bus fault) to fetch a 4 byte integer from an odd address. What is a good value for this on 64-bit systems?
Generally it doesn't matter exactly what pattern you write, it matters that you can identify the pattern in order to determine where problems are occurring. It just so happens that in the Linux kernel these are often chosen so that they can be trapped if the addresses are dereferenced. Have a look in the Linux kernel at include/linux/poison.h. This file contains different poison values for many different kernel subsystems. There is no one poison value that is appropriate. Also, you might check per-architecture include files in the Linux kernel source tree for info on what is used on specific architectures.
1,258,055
1,258,071
Is it OK to use "delete this" to delete the current object?
I'm writing a linked list and I want a struct's destructor (a Node struct) to simply delete itself, and not have any side effects. I want my list's destructor to iteratively call the Node destructor on itself (storing the next node temporarily), like this: //my list class has first and last pointers //and my nodes each have a pointer to the previous and next //node DoublyLinkedList::~DoublyLinkedList { Node *temp = first(); while (temp->next() != NULL) { delete temp; temp = temp->next(); } } So this would be my Node destructor: Node::~Node { delete this; } Is this acceptable, especially in this context?
If the Node destructor is being called, then it's already in the process of being deleted. So a delete doesn't make sense inside your Node destructor. Also this is wrong: while (temp->next() != NULL) { delete temp; temp = temp->next(); } Instead you should get temp->next() into a temp variable. Otherwise you are accessing deleted memory. So more like this: DoublyLinkedList::~DoublyLinkedList { Node *temp = first(); while (temp != NULL) { Node *temp2 = temp->next(); delete temp; temp = temp2; } }
1,258,097
1,258,102
Best way to serialize a Float in java to be read by C++ app?
I need to serialize a java Float to be read by an application written in C++ over Socket comms. Is there a standard for this? It would be easiest to use the method floatToIntBits in the Float Class, however I am not sure how standard that is.
That is, in fact, pretty standard. The floatToIntBits function gives you the actual bytes of the IEEE encoding of the float. The only problem is that the bytes will be big-endian, so you'll have to reverse the byte order when reading into your C++ application. (unless your C++ platform is also big-endian!)
1,258,201
1,258,220
Will using goto cause memory leaks?
I have a program in which i need to break out of a large bunch of nested for loops. So far, the way most people have been telling me to do it is to use an ugly goto in my code. Now, if i create a bunch of local stack (i think that's what they are called, if not, i mean just regular variables without using the new command) variables inside my loops and my program hits that one if statement that triggers the goto, will i encounter a memory leak due to my program exiting many loops improperly and not cleaning up the local variables?
No, you will not cause a memory leak. Using a goto is not "exiting loops improperly." It's just not generally recommended from a code-structure point-of-view. That aside, when you leave the loop, the local variables will go out of scope and be popped off of the stack (i.e. cleaned up) in the process.
1,258,238
1,258,641
Language integration
I may be the minority here, but it seems through my entire academic/professional career I've been taught varying languages. During this time, syntax and programming paradigms were the focus, but at no point were we taught about integrating systems written using varying languages and the proper way to make this decision. Now for the record, I'm not talking about the canonical web stack or the newer, sexier, JVM-friendly languages. What I'm wondering is if there are "known resources" where I could learn about the decision making processes behind binding languages like, Java and C++, for example. Granted, tools like XML, JSON and XMPP come to mind. Then again, I've seen systems binding Java and C++ using serialization. I'm not looking for a one-fix-for-all type of solution. I'm more interested in learning about the varying solutions and how I should be going about making such decisions. My apologies if this is far too broad for this forum, but at least I'm not asking folks to correct or rewrite my botched code ;)
There are four different models that I can think of: Embed a dynamic language inside an app that is primarily written in a more "systems" language, like Lua, Python or Javascript embedded in a Java, C++ or C# app. This is used primarily for a scripting / customization component to the app. This will be accomplished by exposing some of the host applications data types in a format that the dynamic language can make use of. Write native (or C# or Java) extensions for a language with performance problems. Python and Ruby have lots of these extensions. This differs from the above in that the dynamic language is the framework. This is accomplished by writing the native libraries (or a wrapper around other native libraries) to conform to the calling conventions of the client language. This is also the same general structure when intermixing assembler with C in systems code. Run the applications in different address spaces and communicate over sockets or pipes. In this case, it's just a coincidence that the applications are running on the same machine at all -- they could just as well be talking over the network. Develop the app using multiple languages that share the same platform and calling conventions. For example, Java and Scala can be intermixed freely.
1,258,240
1,258,306
Logging exchange of messages by a process
I am currently having an OS which does support logging mechanisms like syslog. However, it is tedious when it comes to debug a process ie to find out what events or messages have a particular process exchanged with other processes in the system. Can any one suggest me a better mechanism to do the same ?
I would recommend wrapping your message passing mechanism with some sort of abstraction. Then you can place diagnostics in the message passing layer. I'd imagine that this is a design pattern of some sort. Create an abstraction that includes connectors between processes and messages sent across the connectors. If your message abstraction includes an identifier (e.g., GUID), then you can log the messages that flow through the connectors and follow them through the system easily. Take a look at the C2 architectural style for some ideas.
1,258,631
1,258,639
Locking files in windows
I am working on some legacy code which opens a file and adds binary data to the file: std::ifstream mInFile; #ifdef WINDOWS miWindowsFileHandle = _sopen(filename.c_str(), O_RDONLY , SH_DENYWR, S_IREAD); #endif mInFile.open(filename.c_str(), std::ios_base::binary); For some reason the code opens the file twice. Is this because _sopen is used to lock the file in windows? If so, how come std::ifstream::open doesn't lock the file? Is there a way to check if a windows file handle has already been closed?
It opens twice because the first one opens it, and locks it. Then fstream opens it again (somewhat contradictory to the intent of the previous statement.) On how to just lock the file, check this question out.
1,258,633
1,258,667
How to programmatically (C/C++) get Country code on Linux?
I'm porting my application into Linux (from Windows). I have such code: char buffer[32] = {0}; if ( GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_ICOUNTRY, buffer, _countof(buffer)) ) { std::string newPrefix(buffer); if ( !newPrefix.empty() && ( newPrefix != "-1" ) ) { countryPrefix_ = newPrefix; } } I need a function which return "country/region code, based on international phone codes" (for example, "1" for USA & Canada, "61" for Australia etc.) The country should be taken from OS' date/time settings (in Windows: Control Panel - Regional & language options).
there is no OS Wide locale setting for Unix. There can be a default used for users which don't overwrite it, but most users do overwrite it. And it is quite common to leave it as "C". there is no standard C or C++ way to get the information you want. the posix way of getting information related to the locale is to set the locale and the use nl_langinfo() (that returns a char*). While there is no POSIX macro defined for the international phone code, glibc has an extension for it (_NL_TELEPHONE_INT_PREFIX). Example: #include <langinfo.h> ... if (setlocale(LC_ALL, "") == NULL) { fprintf(stderr, "Unable to set locale.\n"); abort(); } printf("Telephone international prefix: %s\n", nl_langinfo(_NL_TELEPHONE_INT_PREFIX));
1,258,718
1,259,055
Hex to String Conversion C++/C/Qt?
I am interfacing with an external device which is sending data in hex format. It is of form > %abcdefg,+xxx.x,T,+yy.yy,T,+zz.zz,T,A*hhCRLF CR LF is carriage return line feed hh->checksum %abcdefg -> header Each character in above packet is sent as a hex representation (the xx,yy,abcd etc are replaced with actual numbers). The problem is at my end I store it in a const char* and during the implicit conversion the checksum say 0x05 is converted to \0x05. Here \0 being null character terminates my string. This is perceived as incorrect frames when it is not. Though I can change the implementation to processing raw bytes (in hex form) but I was just wondering whether there is another way out, because it greatly simplifies processing of bytes. And this is what programmers are meant to do. Also in cutecom (on LINUX RHEL 4) I checked the data on serial port and there also we noticed \0x05 instead of 5 for checksum. Note that for storing incoming data I am using //store data from serial here unsigned char Buffer[SIZE]; //convert to a QString, here is where problem arises QString str((const char*)Buffer); of \0 QString is "string" clone of Qt. Library is not an issue here I could use STL also, but C++ string library is also doing the same thing. Has somebody tried this type of experiment before? Do share your views. EDIT This is the sample code you can check for yourself also: #include <iostream> #include <string> #include <QString> #include <QApplication> #include <QByteArray> using std::cout; using std::string; using std::endl; int main(int argc,char* argv[]) { QApplication app(argc,argv); int x = 0x05; const char mydata[] = { 0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76, 0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99}; QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata)); printf("Hello %s\n",data.data()); string str("Hello "); unsigned char ch[]={22,5,6,7,4}; QString s((const char*)ch); qDebug("Hello %s",qPrintable(s)); cout << str << x ; cout << "\nHello I am \0x05"; cout << "\nHello I am " << "0x05"; return app.exec(); }
If your 0x05 is converted to the char '\x05', then you're not having hexadecimal values (that only makes sense if you have numbers as strings anyway), but binary ones. In C and C++, a char is basically just another integer type with very little added magic. So if you have a 5 and assign this to a char, what you get is whatever character your system's encoding defines as the fifth character. (In ASCII, that would be the ENQ char, whatever that means nowadays.) If what you want instead is the char '5', then you need to convert the binary value into its string representation. In C++, this is usually done using streams: const char ch = 5; // '\0x5' std::ostringstream oss; oss << static_cast<int>(ch); const std::string& str = oss.str(); // str now contains "5" Of course, the C std library also provides functions for this conversion. If streaming is too slow for you, you might try those.
1,259,056
1,259,088
overloaded "=" equality does not get called when making obj2 = obj1
i have this class called MemoryManager, it is supposed to implement a simple smart pointer, (count reference); i have a vector where i store the requested pointers,and i return the index of the pointer to the caller.. when a user creates a pointer of type MemoryManager he calls an initializer function called modified_malloc(size_t) , create a MemoryManager obj, alloc a memory space and store it into data,increase count, and store the object into global_MM_vecotr , and return the index as a pointer , when the use tries to use indirection ( ->) i return the appropriate real pointer from the vector, according to the index value.. class MemoryManager { public: //operators overloading prototypes private: void* data; int count ; }; std::vector<MemoryManager*> global_MM_vecotr; void* MemoryManager::operator=( void* x) { // some code here } the problem i am facing is that i overloaded a couple of operators, however when i try to run the code below the "=" operator doesn't get called.. can some1 point the problem out to me.. //the main code { MemoryManager* obj1 = (MemoryManager*) x->fun1(4); //fun1 returns an index to a MemoryManager obj in a vector; MemoryManager* obj2 = obj1 ; } Edit: already tried the following , no change { MemoryManager*obj1 = (MemoryManager*) x->fun1(4); //fun1 returns an index to a Class obj in a vector; MemoryManager*obj2 ; *obj2 = *obj1; } { MemoryManager* obj1 = ( MemoryManager*) x-> fun1(4); MemoryManager* obj2; obj2.operator =(*obj1); }
From you code, you have defined operator= for the MemoryManager class taking a void* . Your example code is initializing ClassA pointers and not assigning to MemoryManager instances. There are three reasons why your code is not being called. You are initializing not assigning, so if anything a constructor would be called rather than an assignment operator. You are initializing pointers and not objects, pointers are basic types and you cannot provide overloaded operators for them. You are using ClassA and not MemoryManager which you have actually provided the operator= for.
1,259,099
1,259,125
std::queue iteration
I need to iterate over std::queue. www.cplusplus.com says: By default, if no container class is specified for a particular queue class, the standard container class template deque is used. So can I somehow get to the queue's underlying deque and iterate over it?
If you need to iterate over a queue then you need something more than a queue. The point of the standard container adapters is to provide a minimal interface. If you need to do iteration as well, why not just use a deque (or list) instead?
1,259,192
1,259,466
webcam access in c++
I want to access the webcam so I can do some precessing on the images, like tracking a light, but I can't find a way to access the webcam. I googled it but I got confused. Can you point me to a library that can do that (windows)? and maybe also provide an example? I would need to periodically get a pixel map of the image, about 20 time per second or so if it would be possible.
Checkout OpenCV. It is a cross-platform computer vision SDK and has modules to capture images from the webcam. Maybe too feature rich for you, but it's worth a look.
1,259,261
1,259,441
Where do I put ATL dlls so they will work
A colleague developed a IE Plugin which I require to run for a piece of work using ATL. I have all of the source code and the compiled dll as well as a regedit. I have run the reg edit and moved the dll to the C:\Windows\System32 directory where I thought it was supposed to reside but that doesn't appear to have worked. Where should I put the dll for it to run correctly? Also is there a simple way to tell if the plugin has been installed correctly? Thanks
I assume that you're talking about this IE plugin. You should register your DLL using regsvr32.exe. This will register the COM classes (add some entries in windows registry). The path where DLL was stored when registering is the one considered when instantiating the COM class. If the dll was previously registered in system32 and you want to move it, you should first unregister it (again, with regsvr32 /u), move the DLL and re-register it in the new location.
1,259,272
1,259,324
Is there a way to forward declare covariance?
Suppose I have these abstract classes Foo and Bar: class Foo; class Bar; class Foo { public: virtual Bar* bar() = 0; }; class Bar { public: virtual Foo* foo() = 0; }; Suppose further that I have the derived class ConcreteFoo and ConcreteBar. I want to covariantly refine the return type of the foo() and bar() methods like this: class ConcreteFoo : public Foo { public: ConcreteBar* bar(); }; class ConcreteBar : public Bar { public: ConcreteFoo* foo(); }; This won't compile since our beloved single pass compiler does not know that ConcreteBar will inherit from Bar, and so that ConcreteBar is a perfectly legal covariant return type. Plain forward declaring ConcreteBar does not work, either, since it does not tell the compiler anything about inheritance. Is this a shortcoming of C++ I'll have to live with or is there actually a way around this dilemma?
You can fake it quite easily, but you lose the static type checking. If you replace the dynamic_casts by static_casts, you have what the compiler is using internally, but you have no dynamic nor static type check: class Foo; class Bar; class Foo { public: Bar* bar(); protected: virtual Bar* doBar(); }; class Bar; { public: Foo* foo(); public: virtual Foo* doFoo(); }; inline Bar* Foo::bar() { return doBar(); } inline Foo* Bar::foo() { return doFoo(); } class ConcreteFoo; class ConcreteBar; class ConcreteFoo : public Foo { public: ConcreteBar* bar(); protected: Bar* doBar(); }; class ConcreteBar : public Bar { public: ConcreteFoo* foo(); public: Foo* doFoo(); }; inline ConcreteBar* ConcreteFoo::bar() { return &dynamic_cast<ConcreteBar&>(*doBar()); } inline ConcreteFoo* ConcreteBar::foo() { return &dynamic_cast<ConcreteFoo&>(*doFoo()); }
1,259,291
1,259,332
Check if service is running?
Possible Duplicate: Querying if a Windows Service is disabled (without using the Registry)? I need to check if 'Event Log' services in running or not. How to do that?
Use OpenSCManager(), then OpenService(), then ControlService().
1,259,638
1,259,678
In C++, when does a process retain allocated memory even though delete is called?
I would like to understand what is going on in the GCC runtime in the following situation. I have a C++ program that allocates many blocks of memory and then deletes them. What's puzzling is that the memory is not being returned to the OS by the GCC runtime. Instead, it is still being kept by my program, I assume in case I want to allocate similar chunks of memory in the near future. The following program demonstrates what happens: #include <iostream> using namespace std; void pause1() { cout << "press any key and enter to continue"; char ch; cin >> ch; } void allocate(int size) { int **array = new int*[size]; for (int c = 0; c < size; c++) { array[c] = new int; } cout << "after allocation of " << size << endl; for (int c = 0; c < size; c++) { delete array[c]; } delete [] array; } int main() { cout << "at start" << endl; pause1(); int size = 1000000; for (int i = 0; i < 3; i++) { allocate(size); cout << "after free" << endl; pause1(); size *= 2; } return 0; } I check the amount of memory held by the process at each pause (when it should not be holding any memory at all) by running "ps -e -o vsz,cmd". The amount held by the process at each pause is the following: 2648kb - at start 18356kb - after allocating and freeing 1,000,000 ints 2780kb - after allocating and freeing 2,000,000 ints 65216kb - after allocating and freeing 4,000,000 ints I'm running on Fedora Core 6 and using GCC 4.1.1.
The memory allocator used by the C library allocates stuff in a variety of ways depending on how big the chunk is. Pages are not always returned to the OS when memory is freed, particularly if you do many small allocations. Memory can only be returned to the OS on a page-by-page basis, not for small allocations. If you really need to know, examine the C library source code and instrument it etc. In C++ you can override the allocators for containers to do your own memory management - you can then do whatever you want (e.g. mmap /dev/zero or whatever)
1,259,719
1,259,747
Can I combine the regular expressions questions ([\\d]*$) and ([\\d]*)c$
I have two simple questions about regular expressions. Having the string $10/$50, I want to get the 50, which will always be at the end of the string. So I made: ([\\d]*$) Having the string 50c/70c I want to get the 70, which will always be at the end of the string(i want it without the c), so I made: ([\\d]*)c$ Both seem do to what I want, but I actually would like to do 2 things with it: a) I'd like to put both on the same string(is it possible?). I tried with the | but it didn't seem to work. **b)**If indeed it is possible to do a), i'd like to know if it's possible to format the text. As you can see, both for dollars and cents, I will retrieve with the regular expression the value the string shows. But while in the first case we are dealing with dollars, in the second we're dealing with cents, so I'd like to transform 50 cents into 0,5. Is it possible, or will I have to code that by myself?
(a) is easy: (\d+)c?$ (b) you can't do with regular expressions.
1,259,803
1,259,845
What does zero-sized array allocation do/mean?
Looking at some example code and come across some zero-size array allocation. I created the following code snippet to clarify my question This is valid code: class T { }; int main(void) { T * ptr = new T[0]; return 0; } What is its use? Is ptr valid? Is this construct portable?
5.3.4 in the C++ Standard: 6 Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value... 7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. So, your code allocates an array which behaves in every respect like any other array of T (can be deleted with delete[], passed as a parameter, probably other things). However, it has no accessible indexes (that is, reading or writing ptr[0] results in undefined behaviour). In this context the different between the constant-expression and the expression is not whether the actual expression is compile time constant (which obviously 0 is), but whether it specifies the "last" dimension of a multi-dimensional array. The syntax is defined in 5.3.4:1.
1,259,815
1,260,078
_beginthreadex static member function
How do I create a thread routine of a static member function class Blah { static void WINAPI Start(); }; // .. // ... // .... hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL); This gives me the following error: ***error C2664: '_beginthreadex' : cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'*** What am I doing wrong?
Sometimes, it is useful to read the error you're getting. cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)' Let's look at what it says. For parameter three, you give it a function with the signature void(void), that is, a function which takes no arguments, and returns nothing. It fails to convert this to unsigned int (__stdcall *)(void *), which is what _beginthreadex expects: It expects a function which: Returns an unsigned int: Uses the stdcall calling convention Takes a void* argument. So my suggestion would be "give it a function with the signature it's asking for". class Blah { static unsigned int __stdcall Start(void*); };
1,259,834
1,260,798
Is there a difference between std::map<int, int> and std::map<const int, int>?
From what I understand, the key in a value pair in an std::map cannot be changed once inserted. Does this mean that creating a map with the key template argument as const has no effect? std::map<int, int> map1; std::map<const int, int> map2;
The answer to your title question is yes. There is a difference. You cannot pass a std::map<int, int> to a function that takes a std::map<const int, int>. However, the functional behavior of the maps is identical, even though they're different types. This is not unusual. In many contexts, int and long behave the same, even though they're formally different types.
1,260,040
1,260,060
Casting between unrelated congruent classes
Suppose I have two classes with identical members from two different libraries: namespace A { struct Point3D { float x,y,z; }; } namespace B { struct Point3D { float x,y,z; }; } When I try cross-casting, it worked: A::Point3D pa = {3,4,5}; B::Point3D* pb = (B::Point3D*)&pa; cout << pb->x << " " << pb->y << " " << pb->z << endl; Under which circumstances is this guaranteed to work? Always? Please note that it would be highly undesirable to edit an external library to add an alignment pragma or something like that. I'm using g++ 4.3.2 on Ubuntu 8.10.
If the structs you are using are just data and no inheritance is used I think it should always work. As long as they are POD it should be ok. http://en.wikipedia.org/wiki/Plain_old_data_structures According to the standard(1.8.5) "Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size. An object of POD5) type (3.9) shall occupy contiguous bytes of storage." If they occupy contiguous bytes of storage and they are the same struct with different name, a cast should succeed
1,260,175
1,264,871
Building log4cxx on visual 2005
When I build the log4cxx on Visual 2005 according to instructions http://logging.apache.org/log4cxx/building/vstudio.html, I am getting error below; 1>------ Build started: Project: apr, Configuration: Debug Win32 ------ 1>Compiling... 1>userinfo.c 1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\rpcndr.h(145) : error C2059: syntax error : ':' 1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\rpcndr.h(898) : error C2059: syntax error : ',' . . . 1>c:\program files\microsoft visual studio 8\vc\platformsdk\include\rpcndr.h(3119) : fatal error C1003: error count exceeds 100; stopping compilation When clicking the first error moves to code below /**************************************************************************** * Other MIDL base types / predefined types: ****************************************************************************/ typedef unsigned char byte; typedef ::byte cs_byte; // error indicates here Is there any comment?? Thanks
I remember having a problem building log4cxx.0.10.0 in windows (I don't remember if it was the exactly the same one you have) and I followed this steps. I hope that helps.
1,260,244
1,260,429
What is the most simple/elegant way to calculate the length of a number written as text?
Given the maximum possible value, how to simply express the space needed to write such number in decimal form as text ? The real task: logging process ids (pid_t) with fixed length, using gcc on Linux. It'd be good to have a compile time expression to be used in the std::setw() iomanipulator. I have found that linux/threads.h header contains a PID_MAX value with the maximum pid allocated to a process. So having #define LENGTH(t) sizeof(#t)-1 the LENGTH(PID_MAX) would be a compile time expression, but unfortunatelly this number is defined in hexa: #define PID_MAX 0x8000 My current best solution is a bit oddish static_cast<int>( ::floor( ::log(PID_MAX)/::log(10) + 1 ) ); But this is calculated runtime and uses functions from math.h
You could do it with a little template meta programming: //NunLength_interal does the actual calculation. template <unsigned num> struct NumLength_internal { enum { value = 1 + NumLength_internal<num/10>::value }; }; template <> struct NumLength_internal<0> { enum { value = 0 }; }; //NumLength is a wrapper to handle zero. For zero we want to return //a length of one as a special case. template <unsigned num> struct NumLength { enum { value = NumLength_internal<num>::value };}; template <> struct NumLength<0> { enum { value = 1 }; }; This should work for anything now. For example: cout << NumLength<0>::value << endl; // writes: 1 cout << NumLength<5>::value << endl; // writes: 1 cout << NumLength<10>::value << endl; // writes: 2 cout << NumLength<123>::value << endl; // writes: 3 cout << NumLength<0x8000>::value << endl; // writes: 5 This is all handled at compile time. Edit: I added another layer to handle the case when the number passed in is zero.
1,260,253
12,971,523
How do I put an QImage with transparency onto the clipboard for another application to use?
I have a QImage that I would like to put on the clipboard, which I can do just fine. However the transparency is lost when that data is pasted into a non-Qt application. The transparent part just comes out as black. I tried saving the data as a transparent PNG but nothing is usable on the clipboard. This is what I have so far: QImage mergedImage = mergeSelectedItems(scene->items()); QMimeData* mimeData = new QMimeData(); QByteArray data; QBuffer buffer(&data); buffer.open(QIODevice::WriteOnly); mergedImage.save(&buffer, "PNG"); buffer.close(); mimeData->setData("image/png", data); clipboard->setMimeData( mimeData );
I had the same problem. I replaced mimeData->setData("image/png", data); with mimeData->setData("PNG", data); It works in MS Office and Gimp, but not in OpenOffice.
1,260,510
1,260,524
Why can I not initialize an array by passing a pointer to a function?
I know this has a really simple explanation, but I've been spoiled by not having to use pointers for a while. Why can't I do something like this in c++ int* b; foo(b); and initialize the array through... void Something::foo(int* a) { a = new int[4]; } after calling foo(b), b is still null. why is this?
Pointers are passed to the function by value. Essentially, this means that the pointer value (but not the pointee!) is copied. What you modify is only the copy of the original pointer. There are two solutions, both using an additional layer of indirection: Either you use a reference: void f(int*& a) { a = new int[4]; } Or you pass in a pointer-to-pointer (less conventional for out parameters as in your case): void f(int** pa) { *pa = new int[4]; } And call the function like this: f(&a); Personally, I dislike both styles: parameters are for function input, output should be handled by the return value. So far, I've yet to see a compelling reason to deviate from this rule in C++. So, my advise is: use the following code instead. int* create_array() { return new int[4]; }
1,260,775
1,260,852
Usage guidelines: shared versus normal pointers
Is there a rigid guideline as to when one should preferably use boost::shared_ptr over normal pointer(T*) and vice-versa?
My general rule is, when memory gets passed around a lot and it's difficult to say what owns that memory, shared pointers should be used. (Note that this may also indicate a poor design, so think about things before you just go to shared pointers.) If you're using shared pointers in one place, you should try to use them everywhere. If you don't you'll have to be very careful about how you pass around pointers to avoid double frees. If your usage of memory is simple and it's obvious what owns memory, then just use normal pointers. Typically the bigger your project is, the more benefit you'll get out of shared pointers. There aren't rigid rules about this and there shouldn't be. As with many development decisions, there are trade offs and you have to do what's best for you.
1,260,954
1,261,168
How can I keep track of (enumerate) all classes that implement an interface
I have a situation where I have an interface that defines how a certain class behaves in order to fill a certain role in my program, but at this point in time I'm not 100% sure how many classes I will write to fill that role. However, at the same time, I know that I want the user to be able to select, from a GUI combo/list box, which concrete class implementing the interface that they want to use to fill a certain role. I want the GUI to be able to enumerate all available classes, but I would prefer not to have to go back and change old code whenever I decide to implement a new class to fill that role (which may be months from now) Some things I've considered: using an enumeration Pros: I know how to do it Cons I will have to update update the enumeration when I add a new class ugly to iterate through using some kind of static list object in the interface, and adding a new element from within the definition file of the implementing class Pros: Wont have to change old code Cons: Not even sure if this is possible Not sure what kind of information to store so that a factory method can choose the proper constructor ( maybe a map between a string and a function pointer that returns a pointer to an object of the interface ) I'm guessing this is a problem (or similar to a problem) that more experienced programmers have probably come across before (and often), and there is probably a common solution to this kind of problem, which is almost certainly better than anything I'm capable of coming up with. So, how do I do it? (P.S. I searched, but all I found was this, and it's not the same: How do I enumerate all items that implement a generic interface?. It appears he already knows how to solve the problem I'm trying to figure out.) Edit: I renamed the title to "How can I keep track of... " rather than just "How can I enumerate..." because the original question sounded like I was more interested in examining the runtime environment, where as what I'm really interested in is compile-time book-keeping.
Create a singleton where you can register your classes with a pointer to a creator function. In the cpp files of the concrete classes you register each class. Something like this: class Interface; typedef boost::function<Interface* ()> Creator; class InterfaceRegistration { typedef map<string, Creator> CreatorMap; public: InterfaceRegistration& instance() { static InterfaceRegistration interfaceRegistration; return interfaceRegistration; } bool registerInterface( const string& name, Creator creator ) { return (m_interfaces[name] = creator); } list<string> names() const { list<string> nameList; transform( m_interfaces.begin(), m_interfaces.end(), back_inserter(nameList) select1st<CreatorMap>::value_type>() ); } Interface* create(cosnt string& name ) const { const CreatorMap::const_iterator it = m_interfaces.find(name); if( it!=m_interfaces.end() && (*it) ) { return (*it)(); } // throw exception ... return 0; } private: CreatorMap m_interfaces; }; // in your concrete classes cpp files namespace { bool registerClassX = InterfaceRegistration::instance("ClassX", boost::lambda::new_ptr<ClassX>() ); } ClassX::ClassX() : Interface() { //.... } // in your concrete class Y cpp files namespace { bool registerClassY = InterfaceRegistration::instance("ClassY", boost::lambda::new_ptr<ClassY>() ); } ClassY::ClassY() : Interface() { //.... }
1,261,027
1,261,044
C++ unit testing with Microsoft MFC
I'm trying to convince my organization to start running unit tests on our C++ code. This is a two-part question: Any tips on convincing my employer that unit testing saves money in the long run? (They have a hard time justifying the immediate expenses.) I'm not familiar with any C++ testing frameworks that integrate well with MFC. Does anyone have experience with this, or use any general test harnesses that could be extended?
I can answer the second question - the Boost Test framework can be used with MFC and someone has posted an excellent article about it on Code Project: http://www.codeproject.com/KB/architecture/Designing_Robust_Objects.aspx
1,261,198
1,261,287
Automatic break when contents of a memory location changes or is read
The old DEC Tru64 UNIX debugger had a feature (called "watchpoints to monitor variables") that would watch a memory location (or range of addresses) for read or write activity and when it detected such activity would break the program so you could investigate why. See for details: http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V50_HTML/ARH9QATE/DOCU_009.HTM Is there any way to do this sort of thing in the VisualStudio debugger? Or is there an add-on or some other tool that can do this under Windows?
Yeah, you can do this in visual studio. You can create a "New Data Breakpoint" under the debug menu while you're broken in a running program. You then specify the address to watch and the number of bytes. This only works for changing the value. I don't know how to watch for read access. However it's a very common question to want to know where a value got changed. I find that I don't want to know who reads a value as often.
1,261,264
1,278,998
example for using streamhtmlparser
Can anyone give me an example on how to use http://code.google.com/p/streamhtmlparser to parse out all the A tag href's from an html document? (either C++ code or python code is ok, but I would prefer an example using the python bindings) I can see how it works in the python tests, but they expect special tokens already in the html at which points it checks state values. I don't see how to get the proper callbacks during state changes when feeding the parser plain html. I can get some of the information I am looking for with the following code, but I need to feed it blocks of html not just characters at a time, and i need to know when it's finished with a tag,attribute, etc not just if it's in a tag, attribute, or value. import py_streamhtmlparser parser = py_streamhtmlparser.HtmlParser() html = """<html><body><a href='http://google.com'>link</a></body></html>""" for index, character in enumerate(html): parser.Parse(character) print index, character, parser.Tag(), parser.Attribute(), parser.Value(), parser.ValueIndex() you can see a sample run of this code here
import py_streamhtmlparser parser = py_streamhtmlparser.HtmlParser() html = """<html><body><a href='http://google.com' id=100> link</a><p><a href=heise.de/></body></html>""" cur_attr = cur_value = None for index, character in enumerate(html): parser.Parse(character) if parser.State() == py_streamhtmlparser.HTML_STATE_VALUE: # we are in an attribute value. Record what we got so far cur_tag = parser.Tag() cur_attr = parser.Attribute() cur_value = parser.Value() continue if cur_value: # we are not in the value anymore, but have seen one just before print "%r %r %r" % (cur_tag, cur_attr, cur_value) cur_value = None gives 'a' 'href' 'http://google.com' 'a' 'id' '100' 'a' 'href' 'heise.de/' If you only want the href attributes, check for cur_attr at the point of the print as well. Edit: The Python bindings currently don't support any kind of event callbacks. So the only output available is the state at the end of processing the respective input. To change that, htmlparser.c:exit_attr (etc.) could be augmented with a callback function. However, this is really not the purpose of streamhtmlparser - it is meant as a templating engine, where you have markers in the source, and you process the input character by character.
1,261,380
1,261,428
What's the simplest and most efficient data structure for building acyclic dependencies?
I'm trying to build a sequence that determines the order to destroy objects. We can assume there are no cycles. If an object A uses an object B during its (A's) construction, then object B should still be available during object A's destruction. Thus the desired order of destruction is A, B. If another object C uses object B during its (C's) construction as well, then the desired order is A, C, B. In general, as long as an object X is only destroyed after all other objects that used that object during their construction, the destruction is safe. If our destruction order so far is AECDBF, and we now are given an X (we never know before hand what order the construction will initially happen in, it's discovered on the fly), that uses C and F during its construction, then we can get a new safe order by putting X before whichever is currently earlier in the list, C or F (happens to be C). So the new order would be ABXCDEF. In the context of the X example, a linked list seems unsuitable because a lot of linear scanning would be involved to determine which is earlier, C or F. An array will mean slow insertions which is going to be one of the more common operations. A priority queue doesn't really have a suitable interface, there's no, "Insert this item before whichever one of these items is earliest" (we don't know the right priority before hand to make sure it's inserted before the lower priority element and without disturbing other entries). All objects are constructed, desired order is computed, and the sequence will be iterated once and destructed in order. No other operations need to be done (in fact, after using whatever data structure to determine the order, it could be copied into a flat array and discarded). Edit: Just to clarify, the first time an object is used is when it is constructed. So if A uses B, then E uses B, when E tries to use B it has already been created. This means a stack won't give the desired order. AB will become ABE when we want AEB. Edit2: I'm trying to build the order 'as I go' to keep the algorithm in place. I would prefer to avoid building up a large intermediate structure and then converting that to a final structure. Edit3: I made this too complicated ;p
Since dependencies are always initialised before the objects that depend on them, and remain available until after such objects are destroyed, it should always be safe to destroy objects in strictly reverse order of initialisation. So all you need is a linked list to which you prepend objects as they are initialised and walk on destruction, and for each object to request initialisation of all its dependencies that have not yet been initialised before it initialises itself. So for initialisation of each object: initialise self, initialising uninitialised dependencies as we go add self to front of destruction list (or push self onto stack if you're using a stack) and for destruction, just walk the linked list from the front forwards (or pop items off stack until empty), destroying as you go. The example in your first paragraph initialised in order B, A, C would thus be destroyed in order C, A, B - which is safe; the example in your edit would be initialised in order B, A, E (not A, B, E since A depends on B), and thus destroyed in order E, A, B, which is also safe.
1,261,558
1,263,604
Is there a generally accepted idiom for indicating C++ code can throw exceptions?
I have seen problems when using C++ code that, unexpectedly to the caller, throws an exception. It's not always possible or practical to read every line of a module that you are using to see if it throws exceptions and if so, what type of exception. Are there established idioms or "best practices" that exist for dealing with this problem? I've thought of the following: In our doxygen documentation, we could add a comment in every function that is expected to throw an exception and it's type(s). Pluses: Simple. Minuses: Subject to user error. We could have an app-wide try/catch(...) for safety. Pluses: We won't have any more uncaught exceptions. Minuses: The exception is caught far away from the throw. It's hard to figure out what to do or what went wrong. Use Exception Specifications Pluses: This is the language-sanctioned way of dealing with this problem. Minuses: Refactoring of problem libraries needed for this to be effective. Not enforced at compile-time, so violations turn into run-time problems, which is what I'm trying to avoid! Any experiences with these methods, or any additional methods that I'm unaware of?
The idiomatic way to solve the problem is not to indicate that your code can throw exceptions, but to implement exception safety in your objects. The standard defines several exception guarantees objects should implement: No-throw guarantee: The function will never throw an exception Strong exception safety guarantee: If an exception is thrown, the object will be left in its initial state. Basic exception safety guarantee: If an exception is thrown, the object be left in a valid state. And of course, the standard documents the level of exception safety for every standard library class. That's really the way to deal with exceptions in C++. Rather than marking which code can or can not throw exceptions, use RAII to ensure your objects get cleaned up, and put some thought into implementing the appropriate level of exception safety in your RAII objects, so they're able to survive without special handling if an exception is thrown. Exceptions only really cause problems if they allow your objects to be left in an invalid state. That should never happen. Your objects should always implement at least the basic guarantee. (and implementing a container class which provides the proper level of exception safety is an enlightening C++ exercise ;)) As for documentation, when you're able to determine for certain which exceptions a function may throw, by all means feel free to document it. But in general, when nothing else is specified, it is assumed that a function may throw. The empty throw specfication is sometimes used to document when a function never throws. If it's not there, assume that the function may throw.
1,261,566
1,276,941
Converting old and new local times to UTC under Windows XP/Server 2003
My application converts past and present dates from local time to UTC. I need to ensure I will honor any future DST updates to Windows while still correctly handling past dates. The application is written in C++ and is running on Server 2003. Options I've researched: gmtime() and localtime() are not always correct for past dates because they will only ever observe current DST rules. (related SO question) A tz database is out because it requires a separate manual update. GetTimeZoneInformationForYear() is out because it requires Vista/Server 2008. Past DST information is stored in the registry, but I'm looking for something higher-level. Boost date_time: class us_dst_rules is deprecated and does not update if the OS updates. class dst_calc_engine<> is its successor, but it does not respect OS updates either. So... ... is anyone else using the raw registry solution to do this? ... any other suggestions? (edit: found out dst_calc_engine doesn't support DST updates)
I think I'd prefer to re-implement GetTimeZoneInformationForYear and possibly GetDynamicTimeZoneInformation based on the information in the registry at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. That way, your code will follow Windows updates and you can swap the dirty code out for the actual implementation on up-level platforms. Since you don't want to use an external database, I think no other options are viable.
1,261,598
1,261,623
A generic method to set the length of a dynamic array of arbitrary type in c++
I am doing a project converting some Pascal (Delphi) code to C++ and would like to write a function that is roughly equivalent to the Pascal "SetLength" method. This takes a reference to a dynamic array, as well as a length and allocates the memory and returns the reference. In C++ I was thinking of something along the lines of void* setlength(void* pp, int array_size, int pointer_size, int target_size, ....) { void * p; // Code to allocate memory here via malloc/new // something like: p = reinterpret_cast<typeid(pp)>(p); // p=(target_size) malloc(array_size); return p; } My question is this: is there a way to pass the pointer type to a function like this and to successfully allocate the memory (perhaps via a typeid parameter?)? Can I use <reinterpret_cast> somehow? The ultimate aim would be something like the following in terms of usage: float*** p; p=setlength(100,sizeof(float***),sizeof(float**),.....); class B; B** cp; cp=setlength(100,sizeof(B**),sizeof(B*),.....); Any help would be most welcome. I am aware my suggested code is all wrong, but wanted to convey the general idea. Thanks.
Use std::vector instead of raw arrays. Then you can simply call its resize() member method. And make the function a template to handle arbitrary types: If you want to use your function, it could look something like this: template <typename T> std::vector<T>& setlength(std::vector<T>& v, int new_size) { v.resize(new_size); return v; } But now it's so simple you might want to eliminate the function entirely and just call resize to begin with. I'm not entirely sure what you're trying to do with the triple-pointers in your example, but it looks like you don't want to resize though, you want to initialize to a certain size, which can be done with the vector constructor: std::vector<float>v(100);
1,261,680
1,261,778
Code crash when storing objects in `std::map`
typedef std::map<int, MyObject*> MyMap; MyMap* myMap = new MyMap; // ... myMap->insert( MyMap::value_type( 0, objectOfType_MyObject ) ); Why does my code crash with a stack trace going down to std::less<int>::operator() ? I understand that if I use a custom key class that I must provide a comparator, but this is an int. I've never used maps before and it's probably a dumb question but I've been stuck on this for ages now. Thanks
This code works (compiles & runs) for me: #include <map> class MyObject { }; int main(void) { typedef std::map<int, MyObject*> MyMap; MyMap *myMap = new MyMap; MyObject *obj = new MyObject; myMap->insert(MyMap::value_type(0, obj)); delete obj; delete myMap; } So the problem lies in the details (// ... or what MyObject can do) or elsewhere. You can probably fix things up a bit to help. Try to stack allocate things when you can. Do you actually need a pointer to a map? I suggest you don't: #include <map> class MyObject { }; int main(void) { typedef std::map<int, MyObject*> MyMap; MyMap myMap; MyObject *obj = new MyObject; myMap.insert(MyMap::value_type(0, obj)); delete obj; } And do you actually need to store pointers to object, or objects? #include <map> class MyObject { }; int main(void) { typedef std::map<int, MyObject> MyMap; MyMap myMap; myMap.insert(MyMap::value_type(0, MyObject())); } Much smaller, and almost impossible to get memory leaks. If you do need to store pointers, for polymorphic behavior, check out boost::ptr_container library, which has a map adapter that stores pointers.
1,262,063
1,262,077
Preprocessor macro expansion to another preprocessor directive
Initially I thought I needed this, but I eventually avoided it. However, my curiosity (and appetite for knowledge, hum) make me ask: Can a preprocessor macro, for instance in #include "MyClass.h" INSTANTIATE_FOO_TEMPLATE_CLASS(MyClass) expand to another include, like in #include "MyClass.h" #include "FooTemplate.h" template class FooTemplate<MyClass>; ?
I believe that cannot be done, this is because the pre-processor is single pass. So it cannot emit other preprocessor directives. Specifically, from the C99 Standard (6.10.3.4 paragraph 3): 3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, ... Interestingly enough, This is why the unary _Pragma operator was added to c99. Because #pragma could not be emited by macros, but _Pragma can.
1,262,076
1,272,704
ActiveMQ c++ tutorial
Can anyone recommend a good tutorial on JMS with c++ and ActiveMQ?
The examples that ship with the library are also pretty good. They have simple, straightforward examples like a simple async consumer and a simple producer which work together. http://svn.apache.org/viewvc/activemq/activemq-cpp/trunk/activemq-cpp/src/examples/
1,262,081
1,262,676
How to encrypt and decrypt a file with Qt/C++?
I want to create a program, which can encrypt and decrypt a complete file with an individual password. Is there any way to manage this in Qt and/or C++ and how?
I've never used it myself, but I've heard great things about QCA. It's cross platfrom, uses a Qt-style API and Qt datatypes.
1,262,308
1,263,313
Read binary C float in Actionscript 3?
I have binary C/C++ data types (e.g. in memory version of a C float) which I need to read into Actionscript 3 and would prefer not to code this from scratch. Anyone know of any libraries, sample code, pseudo code to help with this? For example: C/C++ app: float f = 1.1; SaveFloatToFile(f, 'myfile.bin'); Actionscript 3 app: var ba:ByteArray = ReadFromFile('myfile.bin'); var f:Float = ParseFloat(ba); // I need code for ParseFloat()
I did some more digging around and discovered that ByteArray has most of what I need (possibly with some bit shifting beforehand)