question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,348,788
2,348,820
write a C or C++ library with "template"
(1). When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition (which can only be in header file not source file) directly, but generate the code based on template definition for each of its instantiations and then compile the generated code for its instantiations? (2). If I want to write a C++ library which provide template classes and template functions, is it impossible to compile the library into shared file (.so, .a) because their instantiations will not be anywhere in the code of the library but only appear in the user's program? If yes, does it mean that template libraries are just source code files not precompiled files? How is C++ standard template library (STL) implemented? Is its source code precompiled or compiled together with user's program? (3). In C, how to write a library that provide functions acting like template functions in C++? Is overloading a good solution? If I have to write a procedure into a different function for different types of arguments, is there a good way for code reusing? Is this a good way to do it http://www.vlfeat.org/api/imop_8c_source.html? Any other ways? Thanks and regards!
When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition. Yes. It's a correct assumption. A template definition is incomplete code. You need to fill in the template parameters before compiling it. If I want to write a C++ library which provide template classes and template functions, is it impossible to compile the library into shared file (.so, .a) No it's not possible. You can only compile individual instantiations of a template. How is C++ standard template library (STL) implemented? Is its source code precompiled or compiled together with user's program? A large part of the STL code resides in header files and gets compiled together with your application. In C, how to write a library that provide functions acting like template functions in C++? Is this a good way to do it http://www.vlfeat.org/api/imop_8c_source.html? Any other ways? Including the same file multiple times after redefining a macro (as demonstrated in the link you provided) is a good way to do this.
2,348,960
2,376,513
How can I use Boost::Python to add a method to an exported class without modifying the base class?
I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do this conversion for me and later, when I am mapping the C++ classes to Python classes, I could attach this method. I would prefer if I could just call the method like baseClassInstance.get_std_list_of_items_as_python_list()
Boost provides a helper to wrap iterators which is documented here: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/iterator.html The example hear the end of that page worked for me, you just need to explicitly create the conversion, for example: class_<std::list<Item> >("ItemList") .def("__iter__", iterator<std::list<Item> >()); To modify the C++ class without changing it, I am in the habit of creating a thin wrapper that subclasses the real class. This makes a nice place to separate out all the crud that makes my C++ objects feel comfortable from Python. class Py_BaseClass : public BaseClass { public: std::list<Item> & py_get_items(); }
2,349,069
2,349,257
Issue with Freetype and OpenGL
Hey, i'm having a weird issue with drawing text in openGL loaded with the Freetype 2 library. Here is a screenshot of what I'm seeing. example http://img203.imageshack.us/img203/3316/freetypeweird.png Here are my code bits for loading and rendering my text. class Font { Font(const String& filename) { if (FT_New_Face(Font::ftLibrary, "arial.ttf", 0, &mFace)) { cout << "UH OH!" << endl; } FT_Set_Char_Size(mFace, 16 * 64, 16 * 64, 72, 72); } Glyph* GetGlyph(const unsigned char ch) { if(FT_Load_Char(mFace, ch, FT_LOAD_RENDER)) cout << "OUCH" << endl; FT_Glyph glyph; if(FT_Get_Glyph( mFace->glyph, &glyph )) cout << "OUCH" << endl; FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; Glyph* thisGlyph = new Glyph; thisGlyph->buffer = bitmap_glyph->bitmap.buffer; thisGlyph->width = bitmap_glyph->bitmap.width; thisGlyph->height = bitmap_glyph->bitmap.rows; return thisGlyph; } }; The relevant glyph information (width, height, buffer) is stored in the following struct struct Glyph { GLubyte* buffer; Uint width; Uint height; }; And finally, to render it, I have this class called RenderFont. class RenderFont { RenderFont(Font* font) { mTextureIds = new GLuint[128]; mFirstDisplayListId=glGenLists(128); glGenTextures( 128, mTextureIds ); for(unsigned char i=0;i<128;i++) { MakeDisplayList(font, i); } } void MakeDisplayList(Font* font, unsigned char ch) { Glyph* glyph = font->GetGlyph(ch); glBindTexture( GL_TEXTURE_2D, mTextureIds[ch]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, glyph->width, glyph->height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, glyph->buffer); glNewList(mFirstDisplayListId+ch,GL_COMPILE); glBindTexture(GL_TEXTURE_2D, mTextureIds[ch]); glBegin(GL_QUADS); glTexCoord2d(0,1); glVertex2f(0,glyph->height); glTexCoord2d(0,0); glVertex2f(0,0); glTexCoord2d(1,0); glVertex2f(glyph->width,0); glTexCoord2d(1,1); glVertex2f(glyph->width,glyph->height); glEnd(); glTranslatef(16, 0, 0); glEndList(); } void Draw(const String& text, Uint size, const TransformComponent* transform, const Color32* color) { glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTranslatef(100, 250, 0.0f); glListBase(mFirstDisplayListId); glCallLists(text.length(), GL_UNSIGNED_BYTE, text.c_str()); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glLoadIdentity(); } private: GLuint mFirstDisplayListId; GLuint* mTextureIds; }; Can anybody see anything weird going on here that would cause the garbled text? It's strange because if I change the font size, or the DPI, then some of the letters that display correctly become garbled, and other letters that were garbled before then display correctly.
I'm not familiar with FreeType, but from the picture, it looks like the width of the characters is not directly related to the size of the buffers (ie. glyph->buffer does not point to an array of glyph->width*glyth->height bytes). As a guess, I'd say that all the chars have a single width in memory (as opposed to the size they use on screen), probably the biggest of all the widths of the glyphs, but you load them with a per-char width instead of the correct one. So, only the glyphs that use the full width are correct.
2,349,098
2,349,103
C++ Linked list behavior
I have some C code, where in there are two linked lists(say A and B) and A is inserted at a particular position into B and A still has elements. How do I simulate the same behavior effectively using the C++ STL? If I try splice, it makes the second one empty. Thanks, Gokul.
You need to copy the elements. Consider something like this: std::copy(a.begin(), a.end(), std::inserter(b, b_iterator)); If you want the same nodes shared by two lists, this is simply not supported by std::list (STL containers always have exclusive ownership). You can avoid duplicating the elements by storing pointers in the list, or by using boost::ptr_list, which internally stores pointers but offers a nicer API.
2,349,114
2,349,117
How do I work with nested vectors in C++?
I'm trying to work with vectors of vectors of ints for a sudoku puzzle solver I'm writing. Question 1: If I'm going to access a my 2d vector by index, do I have to initialize it with the appropriate size first? For example: typedef vector<vector<int> > array2d_t; void readAPuzzle(array2d_t grid) { for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++) cin >> grid[i][j]; return; } int main() { array2d_t grid; readAPuzzle(grid); } Will seg fault. I assume this is because it is trying to access elments of grid that have not yet been initialized? I've swapped out grid's declaration line with: array2d_t grid(9, vector<int>(9, 0)); And this seems to get rid of this seg fault. Is this the right way to handle it? Question 2: Why is it that when I try to read into my grid from cin, and then print out the grid, the grid is blank? I'm using the following code to do so: void printGrid(array2d_t grid) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cout << grid[i][j] + " "; } cout << endl; } } void readAPuzzle(array2d_t grid) { for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++) cin >> grid[i][j]; return; } int main() { array2d_t grid(9, vector<int>(9, 0)); printGrid(grid); readAPuzzle(grid); printGrid(grid); } And I attempt to run my program like: ./a.out < sudoku-test Where sudoku-test is a file containing the following: 3 0 0 0 0 0 0 0 0 5 8 4 0 0 2 0 3 0 0 6 0 8 3 0 0 7 5 0 4 1 0 0 6 0 0 0 7 9 0 0 2 0 0 5 1 0 0 0 9 0 0 6 8 0 9 3 0 0 1 5 0 4 0 0 2 0 4 0 0 5 1 8 0 0 0 0 0 0 0 0 6 The first call to printGrid() gives a blank grid, when instead I should be seeing a 9x9 grid of 0's since that is how I initialized it. The second call should contain the grid above. However, both times it is blank. Can anyone shed some light on this?
Q1: Yes, that is the correct way to handle it. However, notice that nested vectors are a rather inefficient way to implement a 2D array. One vector and calculating indices by x + y * width is usually a better option. Q2A: Calculating grid[i][j] + " " does not concatenate two strings (because the left hand side is int, not a string) but instead adds the numeric value to a pointer (the memory address of the first character of the string " "). Use cout << grid[i][j] << " " instead. Q2B: You are passing the array by value (it gets copied) for readAPuzzle. The the function reads into its local copy, which gets destroyed when the function returns. Pass by reference instead (this avoids making a copy and uses the original instead): void readAPuzzle(array2d_t& grid)
2,349,283
2,349,303
Is it possible to have an instance of a class as a data member of another class?
I have a Board class where the constructor takes in the dimensions of the board as the parameter. I also have a Puzzle class that holds pieces and I want it to have a Board as a data member. I want it like this so that when I create an instance of Puzzle, I will have my instance of Board created as well so I don't have to make separate instances as a user. However, when I declare the board in my Puzzle.h file, it needs an actual number for the Board constructor: // Puzzle.h file private: Board theBoard(int height, int width); // Yells at me for not having numbers Is there a way to have an object of a class be a data member for another class if that object hasn't been created yet?
If I understand correctly, the problem is that you need to instantiate your board correctly: class Puzzle { public: Board theBoard; Puzzle(int height, int width) : theBoard(height, width) // Pass this into the constructor here... { }; };
2,349,366
2,349,386
Returning a copy of an Object's self in C++
Ok, So I've googled this problem and I have searched stack overflow but I can't seem to find a good answer. So, I am asking the question on here that is particular to my problem. If it is an easy answer, please be nice, I am new to the language. Here is my problem: I am trying to write a method for a C++ class that is overloading an operator. I want to return a copy of the instance modified but not the instance itself. For ease of example, I'll use a BigInt class to demonstrate the problem that I am having. If I had the following code: const BigInt & operator+() const //returns a positive of the number { BigInt returnValue = *this; //this is where I THINK the problem is returnValue.makepositve(); //for examples sake return returnValue; } I get the error that the return value may have been created on the stack. I know that this means that I have to create the object on the heap and return the reference. But If I were to change the 3rd line to something like: BigInt & returnValue = *this; I get an error telling me that the syntax is not right. I'm not really sure what to do, any help is much appreciated!
The problem is in your function signature. You really do have to return the entire object and not just a reference. Your function will look like this BigInt operator+() const //returns a positive of the number { BigInt returnValue = *this; returnValue.makepositve(); //for examples sake return returnValue; }
2,349,578
2,349,616
Conditional typedefs
If I have a little peice o' code as such... template <typename _T> class Foo { public: typedef const T& ParamType; void DoStuff(ParamType thingy); }; This can be non-optimal if sizeof(_T) <= sizeof(_T*). Therefore, I want to have a conditional typedef. If the size of _T is less than or equal to that of a pointer, just pass it in by value. Otherwise, pass it by const reference. Is this possible? I hear all this stuff about templates being turing complete but this is hurting my head.
Quite easy to achieve using partial template specialization. template< typename _T, bool _ByVal > struct FooBase { typedef const _T& ParamType; }; template< typename _T > struct FooBase< _T, true > { typedef const _T ParamType; }; template< typename _T, bool _ByVal = sizeof(_T) <= sizeof(void*) > class Foo : public FooBase< _T, _ByVal > { typedef typename FooBase< _T, _ByVal >::ParamType ParamType; void DoStuff(ParamType thingy); }; EDIT As per Jeff's sol'n one should indeed compare sizeof(_T) and sizeof(_T&) but I kept the original <= void* requirement.
2,349,698
2,349,745
C++: binary search compile error
I have the following lines of code: if(std::binary_search(face_verts.begin(), face_verts.end(), left_right_vert[0]) && std::binary_search(face_verts.begin(), face_verts.end(), left_right_vert[1])) And when I compile my code, I get the following errors: In file included from /usr/include/c++/4.4/algorithm:62, from R3Mesh.cpp:10: /usr/include/c++/4.4/bits/stl_algo.h: In function ‘bool std::binary_search(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<R3Point*, std::vector<R3Point, std::allocator<R3Point> > >, _Tp = R3Point]’: R3Mesh.cpp:1335: instantiated from here /usr/include/c++/4.4/bits/stl_algo.h:2762: error: no match for ‘operator<’ in ‘__val < __i.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = R3Point*, _Container = std::vector<R3Point, std::allocator<R3Point> >]()’ /usr/include/c++/4.4/bits/stl_algo.h: In function ‘_FIter std::lower_bound(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<R3Point*, std::vector<R3Point, std::allocator<R3Point> > >, _Tp = R3Point]’: /usr/include/c++/4.4/bits/stl_algo.h:2761: instantiated from ‘bool std::binary_search(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<R3Point*, std::vector<R3Point, std::allocator<R3Point> > >, _Tp = R3Point]’ R3Mesh.cpp:1335: instantiated from here /usr/include/c++/4.4/bits/stl_algo.h:2442: error: no match for ‘operator<’ in ‘__middle.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = R3Point*, _Container = std::vector<R3Point, std::allocator<R3Point> >]() < __val’ make: *** [R3Mesh.o] Error 1 I did #include <algorithm> in the beginning of the file and I can't seem to figure out the error. The following are the containers used in the function call: vector <R3Point > face_verts; vector <R3Point > left_right_vert; Thanks.
In order to use binary_search you input siquence must be sorted in accordance with certain comparison predicate. Later, this very same comparison predicate must be given (explicitly or implicitly) to binary_search to be used during searching. So, the questions you should answer in this case are the following Is the input sequence sorted? If it is not, you can stop right here. binary_search cannot be used with unordered sequences. If it is sorted, then what comparison predicate was used to sort it? And how was it passed to the sorting function? Once you know the comparison predicate and the passing approach, you can do the same with binary_search. Note, that the comparison is not necessarily implemented through the operator <, as other answers might suggest. It could be a standalone functor-based comparison predicate, for example. Moreover, the fact that binary_search did not pick up the comparison predicate automatically (as would be the case with operator <) suggests the "standalone" approach.
2,349,727
2,349,974
TInyOS 1.x Generating an error when compiling BLINK
root@everton-laptop:/opt/tinyos-1.x/apps/Blink# make pc compiling Blink to a pc binary ncc -o build/pc/main.exe -g -O0 -board=micasb -pthread -target=pc -Wall -Wshadow -DDEF_TOS_AM_GROUP=0x7d -Wnesc-all -fnesc-nido-tosnodes=1000 -fnesc-cfile=build/pc/app.c Blink.nc -lm In file included from /opt/tinyos-1.x/tos/platform/pc/packet_sim.h:55, from /opt/tinyos-1.x/tos/platform/pc/nido.h:81, from /opt/tinyos-1.x/tos/platform/pc/hardware.h:43, from /opt/tinyos-1.x/tos/system/tos.h:144: /opt/tinyos-1.x/tos/types/AM.h:155: parse error before `struct' /opt/tinyos-1.x/tos/types/AM.h:156: parse error before `struct' /opt/tinyos-1.x/tos/types/AM.h:158: parse error before `struct' /opt/tinyos-1.x/tos/types/AM.h: In function `TOS_MsgLength': /opt/tinyos-1.x/tos/types/AM.h:186: parse error before `TOS_Msg' In file included from /opt/tinyos-1.x/tos/platform/pc/hardware.h:116, from /opt/tinyos-1.x/tos/system/tos.h:144: /opt/tinyos-1.x/tos/platform/pc/eeprom.c: At top level: /opt/tinyos-1.x/tos/platform/pc/eeprom.c:115: warning: declaration of `length' shadows global declaration /opt/tinyos-1.x/tos/types/AM.h:158: warning: location of shadowed declaration /opt/tinyos-1.x/tos/platform/pc/eeprom.c:145: warning: declaration of `length' shadows global declaration /opt/tinyos-1.x/tos/types/AM.h:158: warning: location of shadowed declaration make: *** [build/pc/main.exe] Error 1 Tried compiling BLink and i keep getting the above error and not sure what to do next. any help would be nice .
Looking at the CVS repository for tos/types/AM.h, it looks like it's choking on the following code: 154: enum { 155: MSG_DATA_SIZE = offsetof(struct TOS_Msg, crc) + sizeof(uint16_t), // 36 by default 156: TINYSEC_MSG_DATA_SIZE = offsetof(struct TinySec_Msg, mac) + TINYSEC_MAC_LENGTH, // 41 by default 157: DATA_LENGTH = TOSH_DATA_LENGTH, 158: LENGTH_BYTE_NUMBER = offsetof(struct TOS_Msg, length) + 1, 159: TINYSEC_NODE_ID_SIZE = sizeof(uint16_t) 160: }; The common item from lines 155, 156, and 158 are the offsetof() macro, which should be defined in stddef.h and which looks like should have been brought in by the tos.h before it causes AM.h to be included, so offsetof() should already be defined. You might want to verify whether or not the compiler you're using has offsetof() properly defined and/or why it's not available for use in AM.h. If necessary, you can probably define it yourself using a more or less usual implementation: #define offsetof(st, m) ((size_t) ( (char *)&((st *)(0))->m - (char *)0 )) // stolen from Wikipedia
2,349,783
2,349,792
Can I do pointer arithmetic on an STL::vector::iterator
Currently I use an iterator to search through a vector and test its elements. I access the elements using std::vector<int>::iterator it; if (*it == 0); Can I use the same pointer arithmetic style logic to also test the next element (without altering my iterator)? I first need to see if it will push the iterator out of bounds if (it != myvec.end()) Then test both current element and next element if (*it == 1 && *(it + 1) == 1) Will this work as I expect from using pointers?
Yes, the iterators for std::vector are random access iterators so you add/subtract integral values to get other valid iterators. Technically, it may not be pointer arithmetic, but they act just like pointers.
2,349,801
2,349,809
Modelling a network with a vector of vectors
I am trying to model a network using C++. I have a struct called NetworkConnection: struct NetworkConnection { int i, j, weight; } and I have a class called Network class Network { public: std::vector<NetworkConnection> connections_for(int i) { return connections[i]; } void connect(int i, int j, int weight) { NetworkConnection connection; connection.i = i; connection.j = j; connection.weight = weight; connections[i].push_back(connection) } private: std::vector< std::vector<NetworkConnection> > connections; } Now my problem is that I am getting segfaults when calling connections_for(i), specifically in the copy constructor. Confusingly however the precise circumstances of the segfault vary between runs of the application. I have tried using a vector of pointers and a vector of vectors of pointers like so: std::vector< std::vector<NetworkConnection> * > connections; std::vector< std::vector<NetworkConnection *> > connections; with the appropriate adjustments to the interface but that did not solve the problem. Now I am at a loss as to how to fix this. What am I doing wrong here? Or alternatively how would you model a network in C++ with an interface similar to the above?
You want to use a map: class Network { public: std::vector<NetworkConnection> connections_for(int i) { return connections[i]; } void connect(int i, int j, int weight) { NetworkConnection connection; connection.i = i; connection.j = j; connection.weight = weight; connections[i].push_back(connection); } private: std::map<int, std::vector<NetworkConnection> > connections; }; You may even want to use a map of maps: class Network { public: std::map<int, NetworkConnection> &connections_for(int i) { return connections[i]; } void connect(int i, int j, int weight) { NetworkConnection connection; connection.i = i; connection.j = j; connection.weight = weight; std::map<int, NetworkConnection> &map = connections_for(i); map[j] = connection; } private: std::map<int, std::map<int, NetworkConnection> > connections; };
2,349,827
2,349,840
The difference between a program in C++ developed under Windows and Linux
What's the difference between a program developed in C++ under Windows and Linux? Why can't a program developed under Windows in C++ be used under Linux?
Windows and Linux use different container formats to hold the executable code (PE vs ELF). Windows and Linux have completely different APIs (except for trivial programs that only use the CRT and STL) Windows and Linux have a completely different directory structure You could write a program that can use either set of APIs (for example, using Qt), and that can handle either directory structure, but you still won't be able to run the same file on both operating systems because of the differing container formats. This can be solved by using Wine.
2,349,867
2,349,878
How can it be useful to overload the "function call" operator?
I recently discovered that in C++ you can overload the "function call" operator, in a strange way in which you have to write two pair of parenthesis to do so: class A { int n; public: void operator ()() const; }; And then use it this way: A a; a(); When is this useful?
This can be used to create "functors", objects that act like functions: class Multiplier { public: Multiplier(int m): multiplier(m) {} int operator()(int x) { return multiplier * x; } private: int multiplier; }; Multiplier m(5); cout << m(4) << endl; The above prints 20. The Wikipedia article linked above gives more substantial examples.
2,349,887
2,350,914
Is it worth cutting down a 540 byte class into smaller chunks? (C++)
So I've been developing a UI toolkit for the past year, and my Window class has gotten to a point where the size of the class (through sizeof) is 540 bytes). I was thinking, that since not all windows have children, I might split parts of the code that handles having children (its alignment etc) into a separate class and have a pointer to it. Same goes with texts, icons, and scrolling etc. Is this recommended practice or is there anything I'm blatantly missing?
First, the size of an object instance in itself doesn't really matter. The class should be designed to have a single responsibility, and if that requires 540 bytes of data, then so be it. However, 540 bytes is a unusually big number. It's 135 integers or pointers. It's something like 22 std::vectors. I have a hard time imagining that so many objects can be required for a single area of responsibility. But again, the size itself isn't the problem. The problem is if your class is responsible for more than it should. I was thinking, that since not all windows have children, I might split parts of the code that handles having children (its alignment etc) into a separate class and have a pointer to it. Same goes with texts, icons, and scrolling etc. It sounds like you've basically got a single EverythingUI class. And yes, that is bad design. Split it up for that reason. Handling of text has nothing to do with handing of icons or scrolling or... Put them in different classes.
2,349,897
2,350,040
C++ - Verifying correct input type
I've got the following piece of code: ... int x = 0; int y = 0; cin >> x >> y; if (x == -1 && y == -1) { cout << "exit!"; } else { doSomething(); } ... And it works, but only if I enter 2 numbers. If I were to enter a letter, like 'n', the program gets thrown into an infinite loop. How do I check to make sure the user entered a number and avoid the infinite loop?
Once cin sees a type disagreement between the input data and the variables you're trying to read into, it enters a "fail" state. The conflicting variables won't be updated. Observe: 2010-02-27 22:54:27 ~/tmp/ $ cat ju3.cpp #include <iostream> using namespace std; int main() { int x = 0; int y = 12345; string s, a; printf("cin good? %d, reading...\n", cin.good()); cin >> a >> x >> y >> s; printf("a=%s, x=%d, y=%d, s=%s\n", a.c_str(), x, y, s.c_str()); printf("... read, cin good? %d\n", cin.good()); return 0; } 2010-02-27 22:54:36 ~/tmp/ $ g++ ju3.cpp -o ju3 2010-02-27 22:54:56 ~/tmp/ $ echo 1 2 3 4 | ./ju3 cin good? 1, reading... a=1, x=2, y=3, s=4 ... read, cin good? 1 2010-02-27 22:55:05 ~/tmp/ $ echo a x y z | ./ju3 cin good? 1, reading... a=a, x=0, y=12345, s= ... read, cin good? 0 There are two ways to avoid the problem you're seeing. The quick-and-dirty solution is to just check cin.good() instead of comparing the numbers to -1. If you want cin to behave more robustly, read into strings instead of ints, and manually verify that they contain only numeric characters. You can then use stringstream to easily convert the strings to numbers.
2,349,978
2,350,003
Variables after the colon in a constructor
I am still learning C++ and trying to understand it. I was looking through some code and saw: point3(float X, float Y, float Z) : x(X), y(Y), z(Z) // <----- what is this used for { } What is the meaning of the "x(X), y(Y), z(Z)" sitting beside the constructor's parameters?
It's a way of invoking the constructors of members of the point3 class. if x,y, and z are floats, then this is just a more efficient way of writing this point3( float X, float Y, float Z): { x = X; y = Y; z = Z; } But if x, y & z are classes, then this is the only way to pass parameters into their constructors
2,349,995
2,350,055
Template class, function specialization
I want to have a template class that looks something like what I have down below. Then, I want a function in it with a template specialization depending on a CLASS template parameter. How do I make this work? I realize the code I provided is wrong on many levels, but it's just to illustrate the concept. template <typename _T, size_t num> class Foo { // If num == 1, I want to call this function... void Func<_T, 1>() { printf("Hi!"); } // Otherwise, I want to call this version. void Func<_T, num>() { printf("Hello world!"); } };
struct Otherwise { }; template<size_t> struct C : Otherwise { }; // don't use _Uppercase - those names are reserved for the implementation // (i removed the '_' char) template <typename T, size_t num> class Foo { public: void Func() { Func(C<num>()); } private: // If num == 1, I want to call this function... void Func(C<1>) { printf("Hi 1!"); } // If num == 2, I want to call this function... void Func(C<2>) { printf("Hi 2!"); } // Otherwise, I want to call this version. void Func(Otherwise) { printf("Hello world!"); } //// alternative otherwise solution: // template<size_t I> // void Func(C<I>) { .. } };
2,350,056
2,350,059
How could I do frequency analysis on a string without using a switch
I am working a school project to implement a Huffman code on text. The first part of course requires a frequency analysis on the text. Is there a better way aside from a giant switch and an array of counters to do it? ie: int[] counters for(int i = 0; i <inString.length(); i++) { switch(inString[i]) case 'A': counters[0]++; . . . I would like to do all alpha-numeric characters and punctuation. I am using c++.
Why not: int counters[256] = {0}; for(int i = 0; i <inString.length(); i++) counters[inString[i]]++; } std::cout << "Count occurences of \'a\'" << counters['a'] << std::endl;
2,350,248
2,350,263
Difference in performance between map and unordered_map in c++
I have a simple requirement, i need a map of type . however i need fastest theoretically possible retrieval time. i used both map and the new proposed unordered_map from tr1 i found that at least while parsing a file and creating the map, by inserting an element at at time. map took only 2 minutes while unordered_map took 5 mins. As i it is going to be part of a code to be executed on Hadoop cluster and will contain ~100 million entries, i need smallest possible retrieval time. Also another helpful information: currently the data (keys) which is being inserted is range of integers from 1,2,... to ~10 million. I can also impose user to specify max value and to use order as above, will that significantly effect my implementation? (i heard map is based on rb trees and inserting in increasing order leads to better performance (or worst?) ) here is the code map<int,int> Label // this is being changed to unordered_map fstream LabelFile("Labels.txt"); // Creating the map from the Label.txt if (LabelFile.is_open()) { while (! LabelFile.eof() ) { getline (LabelFile,inputLine); try { curnode=inputLine.substr(0,inputLine.find_first_of("\t")); nodelabel=inputLine.substr(inputLine.find_first_of("\t")+1,inputLine.size()-1); Label[atoi(curnode.c_str())]=atoi(nodelabel.c_str()); } catch(char* strerr) { failed=true; break; } } LabelFile.close(); } Tentative Solution: After review of comments and answers, i believe a Dynamic C++ array would be the best option, since the implementation will use dense keys. Thanks
Insertion for unordered_map should be O(1) and retrieval should be roughly O(1), (its essentially a hash-table). Your timings as a result are way OFF, or there is something WRONG with your implementation or usage of unordered_map. You need to provide some more information, and possibly how you are using the container. As per section 6.3 of n1836 the complexities for insertion/retreival are given: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf One issue you should consider is that your implementation may need to continually be rehashing the structure, as you say you have 100mil+ items. In that case when instantiating the container, if you have a rough idea about how many "unique" elements will be inserted into the container, you can pass that in as a parameter to the constructor and the container will be instantiated accordingly with a bucket-table of appropriate size.
2,350,466
2,350,474
How to assign / retrieve base class?
Suppose I have: class Foo { ... }; class Bar : public Foo { ... }; Foo foo; Bar bar; Is there anyway to do the following: foo_part_of_bar(bar) = foo; foo = foo_part_of_bar(bar); ? Thanks!
Assuming you meant class Bar : public Foo, the following should work. For foo_part_of_bar(bar) = foo; *(static_cast<Foo *>(&bar)) = foo; For foo = foo_part_of_bar(bar); foo = bar;
2,350,489
2,350,530
How to catch segmentation fault in Linux?
I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I could do this with __try - __catch. Is there cross-platform or platform-specific way to do the same? I need this in Linux, gcc.
On Linux we can have these as exceptions, too. Normally, when your program performs a segmentation fault, it is sent a SIGSEGV signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you should debug your code instead. Back to the topic. I recently encountered a library (short manual) that transforms such signals to exceptions, so you can write code like this: try { *(int*) 0 = 0; } catch (std::exception& e) { std::cerr << "Exception caught : " << e.what() << std::endl; } Didn't check it, though. Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.
2,350,531
2,350,562
Problem with D3D & COM
all the D3D interfaces are derived from COM's IUnknown interface, so I though I'd take an easy route for releasing D3D objects and use something like this: __inline BOOL SafeRelease(IUnknown*& pUnknown) { if(pUnknown != NULL && FAILED(pUnknown->Release())) return FALSE; pUnknown = NULL; return TRUE; } this doesn't work though, as the compiler will generate invalid type conversion error(s), when I try to use it. the only way around it I could think of was this: __inline BOOL SafeRelease(void* pObject) { IUnknown* pUnknown = static_cast<IUnknown*>pObject; if(pUnknown != NULL && FAILED(pUnknown->Release())) return FALSE; return TRUE; } but then I loose some functionality and it also looks(and is) very dodgy. is there a better way to do this? something that works like my first example would be optimal, though I would like to avoid using any macros(if its possible)
A template function solves your problem: template<class T> __inline bool SafeRelease(T*& pUnknown) { if (pUnknown == NULL) return false; if (0 == pUnknown->Release()) pUnknown = NULL; return true; }
2,350,544
2,351,513
In what situation do you use a semaphore over a mutex in C++?
Throughout the resources I've read about multithreading, mutex is more often used and discussed compared to a semaphore. My question is when do you use a semaphore over a mutex? I don't see semaphores in Boost thread. Does that mean semaphores no longer used much these days? As far as I've understand, semaphores allow a resource to be shared by several threads. This is only possible if those threads are only reading the resource but not writing. Is this correct?
Boost.Thread has mutexes and condition variables. Purely in terms of functionality, semaphores are therefore redundant[*], although I don't know if that's why they're omitted. Semaphores are a more basic primitive, simpler, and possibly implemented to be faster, but don't have priority-inversion avoidance. They're arguably harder to use than condition variables, because they require the client code to ensure that the number of posts "matches" the number of waits in some appropriate way. With condition variables it's easy to tolerate spurious posts, because nobody actually does anything without checking the condition. Read vs. write resources is a red herring IMO, it has nothing to do with the difference between a mutex and a semaphore. If you use a counting semaphore, you could have a situation where multiple threads are concurrently accessing the same resource, in which case it would presumably have to be read-only access. In that situation, you might be able to use shared_mutex from Boost.Thread instead. But semaphores aren't "for" protecting resources in the way mutexes are, they're "for" sending a signal from one thread to another. It's possible to use them to control access to a resource. That doesn't mean that all uses of semaphores must relate to read-only resources. For example, you can use a binary semaphore to protect a read/write resource. Might not be a good idea, though, since a mutex often gives you better scheduling behaviour. [*] Here's roughly how you implement a counting semaphore using a mutex and a condition variable. To implement a shared semaphore of course you need a shared mutex/condvar: struct sem { mutex m; condvar cv; unsigned int count; }; sem_init(s, value) mutex_init(s.m); condvar_init(s.cv); count = value; sem_wait(s) mutex_lock(s.m); while (s.count <= 0) { condvar_wait(s.cv, s.m); } --s.count; mutex_unlock(s.m); sem_post(s) mutex_lock(s.m); ++s.count; condvar_broadcast(s.cv) mutex_unlock(s.m); Therefore, anything you can do with semaphores, you can do with mutexes and condition variables. Not necessarily by actually implementing a semaphore, though.
2,350,621
2,350,677
Write a *.doc or *.rtf file from a c/c++ application
How can I write to/generate a *.doc file programmatically using c or c++? Is there a (open source/cross platform) library to do this? If this is not possible, can write an *.odt file and then convert it to *.doc? Thanks in advance! EDIT: Anders Abel commented that *.rtf file type is an option, so any suggestions on this one are also accepted.
Joel has an interesing article about this topic: http://www.joelonsoftware.com/items/2008/02/19.html Basically he suggest either: Use MS Word via COM to create the document. Generate another format that MS Word will load, such as RTF. RTF has the advantage that it is a text format. So you can generate a template document with place holders, and then just run a substitution operation when you want to generate your documents.
2,350,830
2,350,846
do i consider (int, double...) as classes
i'm new to c++ and having a little problem understanding about c++'s casting. According to "C++ Primer", the old style cast is like: int(variable) or (int) variable, and new ones introduced by c++ standard includes static_cast<>, const_cast<>, reinterpret_cast<> and dynamic_cast<>. Is the static_cast<> equivalent to "old style cast" ? I think that isn't it if I consider basic data types (int, double...) as a class, then it would be convinient to use just int(object) to do the casting ? Does the standard c++ implement basic types as a class?
1. Old style cast is equivalent of different casts: int i; double d = 3.14; i = static_cast<double>(d); //(double)d; const char* p = reinterpret_cast<char*>(&d); //(char*) &d; char* q = const_cast<char*>(p); //(char*) p; 2. Basic data types are not classes (e.g you can't inherit from them) but they support the constructor syntax for uniformity. int i(10); //same as int i = 10 To do conversions between basic types, you can indeed use this syntax (static_cast stands out more, though).
2,350,933
2,350,950
Pointers and Variables
I just need some clarification on variables A normal variable has 2 "parts" to it? one part is the actual value and the other part is the location of that value in the memory Is that right? So a pointer variable is just the location part of a normal variable, and it doesn't have value itself?
If you're talking about C, then pointers simply represent another level of indirection. If you consider the variable a as an integer, &a (address of a) is the location and it contains the value of a in that location. When you use a, you will get the value from the address. A pointer variable p, when used, will also get a value from a location. But the value at that location is another location from which you can get a value. So let's say you have: int a = 7; // set a to 7. int *p = &a; // set p to the address of a. In this example, a is the variable on the stack at location 0x1234 and p is on the stack at location 0x1236 (a 16-bit int/pointer system). What you have in memory is: +--------+ 0x1236 (p) | 0x1234 | +--------+ 0x1234 (a) | 0x0007 | +--------+ When you use a with, for example: int b = a; the value of a at memory location 0x1234 is used to set b. However, with a pointer: int c = *p; you first look up the value of p in memory location 0x1236 (the value is 0x1234), then dereference it (with '*') to get the value of a.
2,350,940
2,351,479
Streaming to QTextEdit via QTextStream
I have often wanted to use QTextEdit as a quick means of displaying what is being written to a stream. That is, rather than writing to QTextStream out(stdout), I want to do something like: QTextEdit qte; QTextStream out(qte); I could do something similar if I emit a signal after writing to a QTextStream attached to a QString. The problem is that I want the interface to be the same as it would if I were streaming to stdout etc.: out << some data << endl; Any ideas on how I might accomplish this? Thanks in advance.
You can subclass the QTextEdit and implement the << operator to give it the behaviour you want ; something like: class TextEdit : public QTextEdit { .../... TextEdit & operator<< (QString const &str) { append(str); return *this; } };
2,350,997
2,351,024
templates and inheritance issue!
I have a tempated base class check and publically derived class childcheck. the base class also have a partial specializatin but i inherit the childcheck class from the general templated class( not from the partial specialization of the class check). when i call the constructor of the base class from the initialization list of the derived class, compiler gives error, now if i remove the partial specialization of class check then compiler gives no error, so here is the code #include<iostream.h> template<class t> class check { t object; public: check(t element); }; template<class t> check<t>::check<t>(t element) { cout<<"base class constructor"<<endl; } //partial specialization template<class t> class check<t*> { int objectsize; t* object; public: check(t*,int); t* getelement()const; ~check(); }; template<typename t> check<t*>::check<t*>(t* ptr,int size) { cout<<"\n partial specialization constructor"; } //derived class template< class t> class childcheck:public check<t> { t chobject; public: childcheck(t); t getobject()const; }; template<class t> childcheck<t>::childcheck(t element):check<t>(element+1) { cout<<"derived class constructro"<<endl; } //and this is the main function main() { int* ptr; int x=2; ptr=&x; childcheck<int*> object(ptr); system("pause"); }
The check<t*>::check(t*,int); c'tor takes two parameters, but you are calling it ascheck<t>(element+1) from the derived class initialization list (with t==int*, so the partial specialization is instanced).
2,351,148
2,351,155
Explicit template instantiation - when is it used?
After few weeks break, I'm trying to expand and extend my knowlege of templates with the book Templates – The Complete Guide by David Vandevoorde and Nicolai M. Josuttis, and what I'm trying to understand at this moment is explicit instantiation of templates. I don't actually have a problem with the mechanism as such, but I can't imagine a situation in which I would like or want to use this feature. If anyone can explain that to me I will be more than grateful.
Directly copied from https://learn.microsoft.com/en-us/cpp/cpp/explicit-instantiation: You can use explicit instantiation to create an instantiation of a templated class or function without actually using it in your code. Because this is useful when you are creating library (.lib) files that use templates for distribution, uninstantiated template definitions are not put into object (.obj) files. (For instance, libstdc++ contains the explicit instantiation of std::basic_string<char,char_traits<char>,allocator<char> > (which is std::string) so every time you use functions of std::string, the same function code doesn't need to be copied to objects. The compiler only need to refer (link) those to libstdc++.)
2,351,437
2,351,485
When do you use function objects in C++?
I see function objects used often together with STL algorithms. Did function objects came about because of these algorithms? When do you use a function object in C++? What is its benefits?
As said jdv, functors are used instead of function pointers, that are harder to optimize and inline for the compiler; moreover, a fundamental advantage of functors is that they can easily preserve a state between calls to them1, so they can work differently depending on the other times they have been called, keep track somehow of the parameters they have used, ... For example, if you want to sum all the elements in two containers of ints you may do something like this: struct { int sum; void operator()(int element) { sum+=element; } } functor; functor.sum=0; functor = std::for_each(your_first_container.begin(), your_first_container.end(), functor); functor = std::for_each(your_second_container.begin(), your_second_container.end(), functor); std::cout<<"The sum of all the elements is: "<<functor.sum<<std::endl; Actually, as R Samuel Klatchko pointed out below, they can support multiple independent states, one for each functor instance: A slightly more precise statement is that functors can support multiple independent states (functions can support a single state via statics/globals which is neither thread-safe nor reentrant). Functors enables you to use even more complicated states, for example a shared state (static fields) and a private state (instance fields). However this further flexibility is rarely used.
2,351,516
2,351,631
How to avoid reallocation using the STL (C++)
This question is derived from the topic: vector reserve c++ I am using a datastructure of the type vector<vector<vector<double> > >. It is not possible to know the size of each of these vector (except the outer one) before items (doubles) are added. I can get an approximate size (upper bound) on the number of items in each "dimension". A solution with the shared pointers might be the way to go, but I would like to try a solution where the vector<vector<vector<double> > > simply has .reserve()ed enough space (or in some other way has allocated enough memory). Will A.reserve(500) (assumming 500 is the size or, alternatively an upper bound on the size) be enough to hold "2D" vectors of large size, say [1000][10000]? The reason for my question is mainly because I cannot see any way of reasonably estimating the size of the interior of A at the time of .reserve(500). An example of my question: vector<vector<vector<int> > > A; A.reserve(500+1); vector<vector<int> > temp2; vector<int> temp1 (666,666); for(int i=0;i<500;i++) { A.push_back(temp2); for(int j=0; j< 10000;j++) { A.back().push_back(temp1); } } Will this ensure that no reallocation is done for A? If temp2.reserve(100000) and temp1.reserve(1000) were added at creation will this ensure no reallocation at all will occur at all? In the above please disregard the fact that memory could be wasted due to conservative .reserve() calls. Thank you all in advance!
your example will cause a lot of copying and allocations. vector<vector<vector<double>>> A; A.reserve(500+1); vector<vector<double>> temp2; vector<double> temp1 (666,666); for(int i=0;i<500;i++) { A.push_back(temp2); for(int j=0; j< 10000;j++) { A.back().push_back(temp1); } } Q: Will this ensure that no reallocation is done for A? A: Yes. Q: If temp2.reserve(100000) and temp1.reserve(1000) where added at creation will this ensure no reallocation at all will occur at all? A: Here temp1 already knows its own length on creation time and will not be modified, so adding the temp1.reserve(1000) will only force an unneeded reallocation. I don't know what the vector classes copy in their copy ctor, using A.back().reserve(10000) should work for this example. Update: Just tested with g++, the capacity of temp2 will not be copied. So temp2.reserve(10000) will not work. And please use the source formating when you post code, makes it more readable :-).
2,351,544
2,351,595
Is array name a constant pointer in C++?
I have a question about the array name a int a[10] How is the array name defined in C++? A constant pointer? It is defined like this or just we can look it like this? What operations can be applied on the name?
The C++ standard defines what an array is and its behaviour. Take a look in the index. It's not a pointer, const or otherwise, and it's not anything else, it's an array. To see a difference: int a[10]; int *const b = a; std::cout << sizeof(a); // prints "40" on my machine. std::cout << sizeof(b); // prints "4" on my machine. Clearly a and b are not the same type, since they have different sizes. In most contexts, an array name "decays" to a pointer to its own first element. You can think of this as an automatic conversion. The result is an rvalue, meaning that it's "just" a pointer value, and can't be assigned to, similar to when a function name decays to a function pointer. Doesn't mean it's "const" as such, but it's not assignable. So an array "is" a pointer much like a function "is" a function pointer, or a long "is" an int. That is to say, it isn't really, but you can use it as one in most contexts thanks to the conversion.
2,351,616
2,351,632
is there any easy way to expose methods of private parent class c++
Is there any way to directly expose some methods of private parent class. In the following example if I have an object of type Child I want to be able to directly call method a() of its parent, but not b(); Current solution spawns a lot of boilerplate code especially if there are a lot of arguments. class Parent { public: void a(int p1, double p2, int p3, std::vector <int> &p4); void b(); }; class Child : private Parent { public: void a(int p1, double p2, int p3, std::vector <int> &p4) { Parent::a(p1, p2, p3, p4); } };
You can use the using declaration. class Child : private Parent { public: using Parent::a; };
2,351,786
2,352,208
dynamic_cast fails when used with dlopen/dlsym
Intro Let me apologise upfront for the long question. It is as short as I could make it, which is, unfortunately, not very short. Setup I have defined two interfaces, A and B: class A // An interface { public: virtual ~A() {} virtual void whatever_A()=0; }; class B // Another interface { public: virtual ~B() {} virtual void whatever_B()=0; }; Then, I have a shared library "testc" constructing objects of class C, implementing both A and B, and then passing out pointers to their A-interface: class C: public A, public B { public: C(); ~C(); virtual void whatever_A(); virtual void whatever_B(); }; A* create() { return new C(); } Finally, I have a second shared library "testd", which takes a A* as input, and tries to cast it to a B*, using dynamic_cast void process(A* a) { B* b = dynamic_cast<B*>(a); if(b) b->whatever_B(); else printf("Failed!\n"); } Finally, I have main application, passing A*'s between the libraries: A* a = create(); process(a); Question If I build my main application, linking against the 'testc' and 'testd' libraries, everything works as expected. If, however, I modify the main application to not link against 'testc' and 'testd', but instead load them at runtime using dlopen/dlsym, then the dynamic_cast fails. I do not understand why. Any clues? Additional information Tested with gcc 4.4.1, libc6 2.10.1 (Ubuntu 9.10) Example code available
I found the answer to my question here. As I understand it, I need to make the typeinfo available in 'testc' available to the library 'testd'. To do this when using dlopen(), two extra things need to be done: When linking the library, pass the linker the -E option, to make sure it exports all symbols to the executable, not just the ones that are unresolved in it (because there are none) When loading the library with dlopen(), add the RTLD_GLOBAL option, to make sure symbols exported by testc are also available to testd
2,351,794
2,351,856
C++: Any way to 'jail function'?
Well, it's a kind of a web server. I load .dll(.a) files and use them as program modules. I recursively go through directories and put '_main' functors from these libraries into std::map under name, which is membered in special '.m' files. The main directory has few directories for each host. The problem is that I need to prevent usage of 'fopen' or any other filesystem functions working with directory outside of this host directory. The only way I can see for that - write a warp for stdio.h (I mean, write s_stdio.h that has a filename check). May be it could be a deamon, catching system calls and identifying something? add Well, and what about such kind of situation: I upload only souses and then compile it directly on my server after checking up? Well, that's the only way I found (having everything inside one address space still).
As C++ is low level language and the DLLs are compiled to machine code they can do anything. Even if you wrap the standard library functions the code can do the system calls directly, reimplementing the functionality you have wrapped. Probably the only way to effectively sandbox such a DLL is some kind of virtualisation, so the code is not run directly but in a virtual machine. The simpler solution is to use some higher level language for the loadable modules that should be sandboxed. Some high level languages are better at sandboxing (Lua, Java), other are not so good (e.g. AFAIK currently there is no official restricted environment implemented for Python).
2,351,823
2,351,843
c++ round floating numbers to set precision
I wish to round a floating point number to set precision and return the result from a function. For example, I currently have the following function: inline bool R3Point:: operator==(const R3Point& point) const { // Return whether point is equal return ((v[0] == point.v[0]) && (v[1] == point.v[1]) && (v[2] == point.v[2])); } What I wish to do is instead of doing a direct v[i] == point.v[i] comparison, I wish to compare only digits to a certain set precision, so that if v[i] = 0.33349999999999996 and point.v[i] = 0.33350000000000002, my equal comparison will result in TRUE. I am aware that there's a c++ smanip setprecision ( int n ); function and I've seen it used a lot when displaying output on screen using cout. However, I'm not sure if this can be used within the function like I described. Thanks.
Generally, == should not be used to compare doubles, you should do something like : if(v[0] - point.v[0] < 1e-9) { } You can use abs or fabs if you are not sure of the sign and change the precision 1e-9 accordingly.
2,351,826
2,351,885
inheriting a class from a partial specialization of a template class
I have a templated class named check and its partial specialization, now i am publically inheriting a class named childcheck from the partial specialization of the class check. but compiler gives following error message no matching function for call to `check::check()' candidates are: check::check(const check&) check::check(t*) [with t = int*] look at the code and explain the reason please #include<iostream.h> template<class t> class check { t object; public: check(t); }; //defining the constructor template<class t> check<t>::check<t>(t element) { cout<<"general templated class constructor"<<endl; } //partial specialization template<class t> class check<t*> { t* object; public: check(t*); }; template<class t> check<t*>::check<t*>(t* element) { cout<<"partial specialization constructor"<<endl; } //childcheck class which is derived from the partial specialization template<class t> class childcheck:public check<t*>//inheriting from the partial specialization { t object; public: childcheck(t); }; template<class t> childcheck<t>::childcheck<t>(t element):check<t>(element) { cout<<"child class constructor"<<endl; } main() { int x=2; int*ptr=&x; childcheck<int*>object(ptr); cout<<endl; system("pause"); }
You inherit from check<t*> yet call a base class constructor check<t> as if you inherited from check<t>. Which check<> do you want to inherit from? I believe that what you really want do is this: template<class t> class childcheck:public check<t> If t is int*, then childcheck<int*> will inherit from check<int*> which is fine. The rest of your code can remain the way it is in the original question. Read about Template Partial Specialization at cprogramming.com, it explains your previous question.
2,351,936
2,351,968
create an object in switch-case
i use visual studi 2008. (c++) in my switch case a wanted to create an object, but i doens't work. is it right, that i can't create an object in a switch case? if that's right,whats the best way to work around it, a new method that's creates that object? edit the code: switch (causwahl){ case '1': cAccount *oAccount = new cAccount (ID); case '2' ....
I can't say for sure with such a vague question, but I'm guessing that you're doing something like this: switch(foo) { case 1: MyObject bar; // ... break; case 2: MyObject bar; // ... break; } This isn't allowed because each case statement has the same scope. You need to provide more scope if you want to use the same variable name: switch(foo) { case 1: { MyObject bar; // ... break; } case 2: { MyObject bar; // ... break; } }
2,351,972
2,351,982
What's the right way to overload the stream operators << >> for my class?
I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition istream& operator>>(istream& is, Thing& thing) { // etc... which works. It's not mentioned in the definition of the Thing class. I want it to be able to access members of my Thing class in its implementation - how do I do this?
Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing: class Thing { public: friend istream& operator>>(istream&, Thing&); ... }
2,352,090
2,353,039
CUDA with map<value, key> & atomic operations
As far as I know I can use C++ templates in CUDA device code. So If i'm using map to create a dictionary will the operation of inserting new values be atomic? I want to count the number of appearances of a certain values, i.e. create a code-dictionary with probabilities of the codes. Thanks Macs
You cannot use STL within device code. You could check thrust for similar functionality (check the experimental namespace in particular). Templates are fine in device code, CUDA C currently supports quite a few C++ features although some of the big ones such as virtual functions and exceptions are not yet possible ( and will only be possible on Fermi hardware). If you decide to implement this yourself, you can use the atomicAdd() intrinsic to get an atomic operation, check out the CUDA Programming Guide for more information.
2,352,160
2,352,193
C++: How to improve performance of custom class that will be copied often?
I am moving to C++ from Java and I am having a lot of trouble understanding the basics of how C++ classes work and best practices for designing them. Specifically I am wondering if I should be using a pointer to my class member in the following case. I have a custom class Foo which which represents the state of a game on a specific turn, and Foo has a member variable of custom class Bar which represents a logical subset of that game state. For example Foo represents a chess board and Bar represents pieces under attack and their escape moves (not my specific case, but a more universal analogy I think). I would like to search a sequence of moves by copying Foo and updating the state of the copy accordingly. When I am finished searching that move sequence I will discard that copy and still have my original Foo representing the current game state. In Foo.h I declare my Foo class and I declare a member variable for it of type Bar: class Foo { Bar b; public: Foo(); Foo(const Foo& f); } But in the implementation of my Foo constructors I am calling the Bar constructor with some arguments specific to the current state which I will know at run time. As far as I understand, this means that a Bar constructor is called twice - once because I wrote "Bar b;" above (which calls the default constructor if I understand correctly), and once because I am writing something like "b = Bar(arg1,arg2,...)" in Foo::Foo() and Foo::Foo(const Foo& f). If I am trying to make as many copies of Foo per second as possible, this is a problem, right? I am thinking a simple solution is to declare a pointer to a Bar instead: "Bar *b", which should avoid instantiating b twice. Is this good practice? Does this present any pitfalls I should know about? Is there a better solution? I can't find a specific example to help me (besides lots of warnings against using pointers), and all the information about designing classes is really overwhelming, so any guidance would be greatly appreciated! EDIT: Yes, I will have all the information necessary to create Bar when I create my Foo. I think everyone inferred this, but to make it clear, I have something more like this already for my default constructor: Foo(int k=5); and in Foo.cpp: Foo::Foo(int k) { b = Bar(k); ... } and then my Foo and its Bar member are updated incrementally as the game state changes. So calling my custom Bar constructor in my Foo constructor declaration initialization list looks like the best way to do it. Thank you for the answers!
Ideally you'd have all the information necessary to setup Bar at the time Foo is constructed. The best solution would be something like: class Foo { Bar b; public: Foo() : b() { ... }; Foo(const Foo& f) : b(f.a, f.b) { ... }; } Read more about constructor initialization lists (which has no direct equivalent in Java.) Using a pointer pb = new Bar(arg1, arg2) will actually most likely deteriorate your performance since heap allocation (which could involve, among other things, locking) can easily become more expensive than assigning a non-default constructed Bar to a default-constructed Bar (depending, of course, by how complex your Bar::operator= is.)
2,352,220
2,352,245
Alternative http port?
I want to write a browser-chat and write an own server in c++, because you can not send text between the different instances (chat user) in php and other languages. I have apache running with port 80 and that's why I cant run the "chat http server" on port 80. Some browsers block connection to a http site if it does not use port 80. Does someone knows, what port I should use for this small server for best browser compatibility? Maybe 8080? I could also buy a different IP to run it under :80, but my host wants 5€ per month for a new ip... Thanks.
You can use mod_proxy (or mod_proxy_balancer) to forward requests on some branch of your Apache site to the other web server that listens to localhost on some other port.
2,352,235
2,352,253
c++ development on Mac
I have till now mainly concentrated on web programming thus far and now want to enter application programming space. I use a mac, and wanted to know what sort of compilers, IDEs etc people generally use for c++ dev. extremely n00b One more thing immensely bothering me was the fact that c++ compilers generally output .exe which can't be used on macs. I need to understand basic OOP programming fundamentals and thought c++ would be the best choice. Please suggest something.
C++ is not restricted to .exe files.... window PE files are one container format for machine code. A C++ binary can be encased in any low-level container format you can think of. Objective-C on the mac can be a very pleasant language to learn, also Java. Do you really need to learn C++ at this junction ? C++ is suited to low-level programming problems -- i.e., video games, system software, and generally performance-critical software (photoshop and imovie).
2,352,342
2,352,356
The difference between python dict and tr1::unordered_map in C++
I have a question related to understanding of how python dictionaries work. I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutable (by supporting .append) and hence they cannot be used as dictionary keys. I wanted to know how does implementation of unordered_map in C++ handles these cases. (since strings in C++ are mutable)
Keys in all C++ map/set containers are const and thus immutable (after added to the container). Notice that C++ containers are not specific to string keys, you can use any objects, but the constness will prevent modifications after the key is copied to the container.
2,352,533
2,352,657
Adding virtual functions without modifying the original classes
Let's say we already have a hierarchy of classes, e.g. class Shape { virtual void get_area() = 0; }; class Square : Shape { ... }; class Circle : Shape { ... }; etc. Now let's say that I want to (effectively) add a virtual draw() = 0 method to Shape with appropriate definitions in each sub-class. However, let's say I want to do this without modifying those classes (as they are part of a library that I don't want to change). What would be the best way to go about this? Whether or not I actually "add" a virtual method or not is not important, I just want polymorphic behaviour given an array of pointers. My first thought would be to do this: class IDrawable { virtual void draw() = 0; }; class DrawableSquare : Square, IDrawable { void draw() { ... } }; class DrawableCircle : Circle, IDrawable { void draw() { ... } }; and then just replace all creations of Squares and Circles with DrawableSquares and DrawableCircles, respectively. Is that the best way to accomplish this, or is there something better (preferably something that leaves the creation of Squares and Circles intact). Thanks in advance.
(I do propose a solution down further... bear with me...) One way to (almost) solve your problem is to use a Visitor design pattern. Something like this: class DrawVisitor { public: void draw(const Shape &shape); // dispatches to correct private method private: void visitSquare(const Square &square); void visitCircle(const Circle &circle); }; Then instead of this: Shape &shape = getShape(); // returns some Shape subclass shape.draw(); // virtual method You would do: DrawVisitor dv; Shape &shape = getShape(); dv.draw(shape); Normally in a Visitor pattern you would implement the draw method like this: DrawVisitor::draw(const Shape &shape) { shape.accept(*this); } But that only works if the Shape hierarchy was designed to be visited: each subclass implements the virtual method accept by calling the appropriate visitXxxx method on the Visitor. Most likely it was not designed for that. Without being able to modify the class hierarchy to add a virtual accept method to Shape (and all subclasses), you need some other way to dispatch to the correct draw method. One naieve approach is this: DrawVisitor::draw(const Shape &shape) { if (const Square *pSquare = dynamic_cast<const Square *>(&shape)) { visitSquare(*pSquare); } else if (const Circle *pCircle = dynamic_cast<const Circle *>(&shape)) { visitCircle(*pCircle); } // etc. } That will work, but there is a performance hit to using dynamic_cast that way. If you can afford that hit, it is a straightforward approach that is easy to understand, debug, maintain, etc. Suppose there was an enumeration of all shape types: enum ShapeId { SQUARE, CIRCLE, ... }; and there was a virtual method ShapeId Shape::getId() const = 0; that each subclass would override to return its ShapeId. Then you could do your dispatch using a massive switch statement instead of the if-elsif-elsif of dynamic_casts. Or perhaps instead of a switch use a hashtable. The best case scenario is to put this mapping function in one place, so that you can define multiple visitors without having to repeat the mapping logic each time. So you probably don't have a getid() method either. Too bad. What's another way to get an ID that is unique for each type of object? RTTI. This is not necessarily elegant or foolproof, but you can create a hashtable of type_info pointers. You can build this hashtable in some initialization code or build it dynamically (or both). DrawVisitor::init() // static method or ctor { typeMap_[&typeid(Square)] = &visitSquare; typeMap_[&typeid(Circle)] = &visitCircle; // etc. } DrawVisitor::draw(const Shape &shape) { type_info *ti = typeid(shape); typedef void (DrawVisitor::*VisitFun)(const Shape &shape); VisitFun visit = 0; // or default draw method? TypeMap::iterator iter = typeMap_.find(ti); if (iter != typeMap_.end()) { visit = iter->second; } else if (const Square *pSquare = dynamic_cast<const Square *>(&shape)) { visit = typeMap_[ti] = &visitSquare; } else if (const Circle *pCircle = dynamic_cast<const Circle *>(&shape)) { visit = typeMap_[ti] = &visitCircle; } // etc. if (visit) { // will have to do static_cast<> inside the function ((*this).*(visit))(shape); } } Might be some bugs/syntax errors in there, I haven't tried compiling this example. I have done something like this before -- the technique works. I'm not sure if you might run into problems with shared libraries though. One last thing I'll add: regardless of how you decide to do the dispatch, it probably makes sense to make a visitor base class: class ShapeVisitor { public: void visit(const Shape &shape); // not virtual private: virtual void visitSquare(const Square &square) = 0; virtual void visitCircle(const Circle &circle) = 0; };
2,352,601
2,352,620
C++: Compiler warning for large unsigned int
I have following array, that I need to operate by hand on bitmaps. const unsigned int BITS[32] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648}; Unfortunately, when compiled I get warning: this decimal constant is unsigned only in ISO C90 How can I remove this?
Integer literals in C are, by default, of type "signed int" (edit: but see comments for caveats). The last number there is too large to be represented as a signed 32-bit integer, and so you need to tell the compiler that it's an unsigned integer by suffixing it with "U", as: 2147483648U Note that you can also add a suffix of "L" to make it a "long", but on many systems that's still 32-bit and thus irrelevant. Also, there's a much less error-prone (and easier-to-read) way to write this code, with the bit-shift operator: const unsigned int BITS[32] = {1U, 1U<<1, 1U<<2, 1U<<3, 1U<<4, /* and so on */ 1U<<31}; Or, writing in hexadecimal, if you don't like bit shifts for some reason: const unsigned int BITS[32] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, /* and so on */ 0x80000000U};
2,352,683
2,352,912
How to return a const QString reference in case of failure?
consider the following code: const QString& MyClass::getID(int index) const { if (i < myArraySize && myArray[i]) { return myArray[i]->id; // id is a QString } else { return my_global_empty_qstring; // is a global empty QString } } How can I avoid to have an empty QString without changing the return type of the method? (It seems that returning an empty QString allocated on the stack is a bad idea) Thanks.
You can't. Either do not return a const reference or use a local static variable like this: const QString& MyClass::getID(int index) const { if (i < myArraySize && (myArray[i] != 0)) { return myArray[i]->id; // id is a QString } static const QString emptyString; return emptyString; } The advantage of this method over the other proposed methods is that this solution does not require a change to the interface of MyClass. Furthermore, using a default parameter might confuse users of your class and lead to wrong class usage. This solution is transparent to the user. By the way, are you really using a C style array in your class?
2,353,124
2,353,133
Segfault when I delete an object - GDB says in free()
I am working on an assignment for networking where we are supposed to create a networking library in C and then use it in our C++ program. My C++ isn't as strong as my C so I got started on that first so I could tackle any problems that came up, and I present you my first one. :D I have a base class and an inherited class (there will eventually be another inherited one) which will provide functions that determine the servers behavior. Base Class header and destructor: // Message Forwarder Base Class class MessageForwarder { public: /* ------ Public Function Declarations ------ */ MessageForwarder(const string serverName, const string serverAddress); virtual ~MessageForwarder(); virtual void Print() const = 0; protected: /* ------ Private Variable Declarations ------ */ string monitor; // 192.168.1.102:8000 - The address to the monitoring server string myName; // The name of message forwarding server string myAddress; // The address of the message forwarding server }; MessageForwarder::~MessageForwarder() { delete &this->monitor; delete &this->myName; delete &this->myAddress; fprintf(stdout, "Cleaning up MessageForwarder\n"); } Inherited Class and destructor: // Client Message Forwarder Derived Class class ClientMessageForwarder : public MessageForwarder { public: /* ------ Public Function Declarations ------ */ ClientMessageForwarder(const string serverName, const string serverAddress); ~ClientMessageForwarder(); void Print() const; private: /* ------ Private Variable Declarations ------ */ }; ClientMessageForwarder::~ClientMessageForwarder() { fprintf(stdout, "Cleaning up ClientMessageHandler\n"); } My problem arises when I try to delete a class object. My program follows this: int main(int argc, char *argv[]) { /* ------ Variable Declarations ------ */ // Server Object MessageForwarder *msgFrwder; msgFrwder = new ClientMessageForwarder(serverName, serverAddress); msgFrwder->Print(); delete msgFrwder; <------------ SEGFAULT here! return 0;} When I go ahead and run my program it segfaults on the line delete msgFrwder; I go ahead and use GDB with the dumped core and ask where it happens and it gives me the following: #0 0x0000000800afe409 in free () from /lib/libc.so.7 #1 0x00000008006cbd17 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string () from /usr/lib/libstdc++.so.6 #2 0x0000000000401e88 in ~MessageForwarder (this=0x800d02080) at ./classes/msgfrwd.cpp:44 #3 0x00000000004023c5 in ~ClientMessageForwarder (this=0x800d02080) at ./classes/climsgfrwd.cpp:44 #4 0x000000000040158c in main (argc=7, argv=0x7fffffffe478) at ./msgfrwdserver.cpp:97 With my limited C++ knowledge I feel like I am following the proper steps to clean up and free my memory. When I run my program it does in fact output "Cleaning up MessageForwarder" so I know it executed that line. I have searched for solution and struggled with the problem for a while but can't find a solution. Any help would be much appreciated or an explanation of what is actually going on and why the segfault is happening would help. Thanks for all your help. Its appreciated. :D
string objects were not allocated using new operator. Do not delete them, they will be freed automatically
2,353,142
2,353,160
Overloading Operator + in C++
Ok, I am working through a book and trying to learn C++ operator overloading. I created a BigInt class that takes a single int (initially set to 0) for the constructor. I overloaded the += method and it works just fine in the following code: BigInt x = BigInt(2); x += x; x.print( cout ); The code will output 4. So, then I was working on overloading the global operator + using the following code: BigInt operator+(const BigInt lhs, const BigInt rhs) { BigInt returnValue(lhs); returnValue += rhs; return returnValue; } This also works fine for the following code: BigInt x = BigInt(1); BigInt y = BigInt(5); BigInt z = x + y; z.print(); This prints out 6. However, when I try to execute the following code, it just doesn't work. The book doesn't explain very well and implies that it should simply work. BigInt x = BigInt(1); BigInt z = x + 5; z.print(); This prints out 1. I'm not sure why z is 1 when it should be 6. I googled online and on stackoverflow but I couldn't find anyone else that was having a problem exactly like this. some were close, but the answers just didn't fit. Any help is much appreciated!
most likely problem is in += operator. Post code for it.
2,353,178
2,388,967
Disable alt-enter in a Direct3D (DirectX) application
I'm reading Introduction to 3D Game Programming with DirectX 10 to learn some DirectX, and I was trying to do the proposed exercises (chapter 4 for the ones who have the book). One exercise asks to disable the Alt+Enter functionality (toggle full screen mode) using IDXGIFactory::MakeWindowAssociation. However it toggles full screen mode anyway, and I can't understand why. This is my code: HR(D3D10CreateDevice( 0, //default adapter md3dDriverType, 0, // no software device createDeviceFlags, D3D10_SDK_VERSION, &md3dDevice) ); IDXGIFactory *factory; HR(CreateDXGIFactory(__uuidof(IDXGIFactory), (void **)&factory)); HR(factory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); factory->MakeWindowAssociation(mhMainWnd, DXGI_MWA_NO_ALT_ENTER); ReleaseCOM(factory);
I think the problem is this. Since you create the device by yourself (and not through the factory) any calls made to the factory you created won't change anything. So either you: a) Create the factory earlier and create the device through it OR b) Retrieve the factory actually used to create the device through the code below. IDXGIDevice * pDXGIDevice; HR( md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice) ); IDXGIAdapter * pDXGIAdapter; HR( pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter) ); IDXGIFactory * pIDXGIFactory; pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pIDXGIFactory); And call the function through that factory (after the SwapChain has been created) pIDXGIFactory->MakeWindowAssociation(mhMainWnd, DXGI_MWA_NO_ALT_ENTER); MSDN: IDXGIFactory
2,353,431
2,355,711
How can a script retain its values through different script loading in Lua?
My current problem is that I have several enemies share the same A.I. script, and one other object that does something different. The function in the script is called AILogic. I want these enemies to move independently, but this is proving to be an issue. Here is what I've tried. 1) Calling dofile in the enemy's constructor, and then calling its script function in its Update function which happens in every game loop. The problem with this is that Lua just uses the script of the last enemy constructed, so all of the enemies are running the same script in the Update function. Thus, the object I described above that doesn't use the same script for it's A.I. is using the other enemies' script. 2) Calling dofile in the Update function, and then calling its script function immediately after. The problem with this is that dofile is called in every object's update function, so after the AILogic function runs and data for that script is updated, the whole thing just gets reset when dofile is called again for another enemy. My biggest question here is whether there is some way to retain the values in the script, even when I switch to running a different one. I've read about function environments in Lua, but I'm not quite sure how to implement them correctly. Is this the right direction? Any advice is appreciated, thanks. Edit: I've also considered creating a separate place to store that data rather than doing it in the Lua script. Edit2: Added some sample code. (Just a test to get the functionality working). -- Slime's Script local count = 0; function AILogic( Slime ) --Make the slime move in circles(err a square) if count < 4 then Slime:MoveDir( 0 ); elseif count < 8 then Slime:MoveDir( 2 ); elseif count < 12 then Slime:MoveDir( 1 ); elseif count < 16 then Slime:MoveDir( 3 ); else count = 0; end count = count + 1; end
The lua interpreter runs each line as its own chunk which means that locals have line scope, so the example code can't be run as-is. It either needs to be run all at once (no line breaks), without locals, or run in a do ... end block. As to the question in the OP. If you want to share the exact same function (that is the same function at runtime) then the function needs to take the data as arguments. If, however, you are ok with using the same code but different (runtime) functions than you can use closures to hold the local/individual data. local function make_counter() local count = 0 return function () local c = count count = count + 1 return c end end c1 = make_counter() c2 = make_counter() c3 = make_counter() print(c1()) print(c1()) print(c1()) print(c1()) print(c2()) print(c3()) print(c2()) print(c3()) print(c2()) print(c3()) Alternatively, you could play with the environment of the function each time it is called, but that will only work correctly for some cases (depends on what the internals of the function are).
2,353,514
2,354,571
Implementing pImpl with minimal amount of code
What kind of tricks can be used to minimize the workload of implementing pImpl classes? Header: class Foo { struct Impl; boost::scoped_ptr<Impl> self; public: Foo(int arg); ~Foo(); // Public member functions go here }; Implementation: struct Foo::Impl { Impl(int arg): something(arg) {} // All data members and private functions go here }; Foo::Foo(int arg): self(new Impl(arg)) {} Foo::~Foo() {} // Foo's public functions go here (and they refer to data as self->something) How would you improve this, using Boost, possibly inheritance, CRTP or other tricks to avoiding as much boilerplate code as is possible? The runtime performance is not an issue.
Implementation of pimpl from Loki may be a good answer. See also a DDJ Article on this.
2,353,613
2,353,626
Best way to programatically check for existence of header file?
Is it just to test compile a simple program, with that header file #included in it? To better understand the compilation process I'm writing my own "configure", which tests for the existence of a few header and library files.
Yes, use the compiler to compile your simple test program. That's the best and easiest way to see if the compiler can find the header. If you hard code #include search paths you'll always have to modify and adapt for different compilers.
2,353,615
2,353,627
How to create a window based on only the size of the screen not including the windows border with C++/Windows?
When creating a window using CreateWindow(...), which requires the window width and height, I have to enter the values 656 and 516, instead of 640 and 480, so as to account for the windows border. I'm wondering if there is a way to create a window based only on the portion of the window not including the border, especially considering that if different versions of windows have different size borders, than the program might be displayed differently when I run it on said different versions (ie: using 640 - object.width will place the object not quite on the edge of the screen if the user's version of windows has different sized borders). So is there a way to create a window based only on the portion of the screen relevant to the program, or at the vary least a function along the lines of GetVericalBorder()/GetHorizontalBorder() so that I use these in CreateWindow()'s parameters instead of arbitrary and vague values like 656 and 516?
Have a look at AdjustWindowRectEx. You pass this function a rectangle containing the desired size of your windows' client area, and the window style flags, and it calculates how big to make the overall window so that the client area is the desired size.
2,353,633
2,353,969
Auto resizing of contents of QDockWidget
I've created a dock widget which contains a QTreeView. The size of the tree view remains static when the dock is resized. How can I get it to change it's size automatically to fill the dock area? I've created the dock widget using the designer and use multiple inheritance to include it in the main app. Inherited class: class TreePaneWid : public QDockWidget, protected Ui_TreePaneWid{ public: TreePaneWid(){ setupUi(this); show(); } };
In the designer, right click on the dock widget, go to Layout, and click Layout Horizontally.
2,353,980
2,354,049
At what exact moment is a local variable allocated storage?
Suppose we have the following: void print() { int a; // declaration a = 9; cout << a << endl; } int main () { print(); } Is the storage for variable a allocated at the moment function print is called in main or is it when execution reaches the declaration inside the function?
This is very much compiler dependent under the covers, but logically the storage is assigned as soon as the variable is declared. Consider this simplistic C++ example: // junk.c++ int addtwo(int a) { int x = 2; return a + x; } When GCC compiles this, the following code is generated (; comments mine): .file "junk.c++" .text .globl _Z6addtwoi .type _Z6addtwoi, @function _Z6addtwoi: .LFB2: pushl %ebp ;store the old stack frame (caller's parameters and locals) .LCFI0: movl %esp, %ebp ;set up the base pointer for our parameters and locals .LCFI1: subl $16, %esp ;leave room for local variables on the stack .LCFI2: movl $2, -4(%ebp) ;store the 2 in "x" (-4 offset from the base pointer) movl -4(%ebp), %edx ;put "x" into the DX register movl 8(%ebp), %eax ;put "a" (+8 offset from base pointer) into AX register addl %edx, %eax ;add the two together, storing the results in AX leave ;tear down the stack frame, no more locals or parameters ret ;exit the function, result is returned in AX by convention .LFE2: .size _Z6addtwoi, .-_Z6addtwoi .ident "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3" .section .note.GNU-stack,"",@progbits Everything between _Z6addtwoi and .LCFI2 is boilerplate code used to set up the stack frame (store the previous function's variables, etc. safely out of the way). That last "subl $16, %esp" is the allocation of the local variable x. .LCFI2 is the first bit of actual executing code that you've typed. "movl $2, -4(%ebp)" is putting the value 2 into the variable. (Initialization, in other words.) Now your space is allocated AND initialized. After that it loads the value into register EDX and follows that by moving your parameter, found in "8(%ebp)", into another register EAX. It then adds the two together, leaving the result in EAX. This is now the end of any code you've actually typed. The rest is again just boilerplate. Since GCC mandates that integers are returned in EAX, no work has to be done for the return value. The "leave" instruction tears down the stack frame and the "ret" instruction returns control back to the caller. TL;DR summary: you can think of your space as having been allocated with the very first line of executable code in your block (paired {}). I thought I'd clean this up a bit with explanatory comments seeing as this is the selected answer.
2,354,046
2,354,108
Variadic Macros : how to solve "too many actual parameters for macro.."
Ive been working on getting some of my code originally built on the mac to run under Visual Studio 2008 Express and have run into a weird problem with the variadic macros i use for my assert code : The macro is defined as : #define SH_ASSERT( assertID, exp, description, ... ) shAssertBasic( int(exp), assertID, description, __LINE__, __FILE__ , ##__VA_ARGS__ ) This all works fine under gcc (under osx) and used to run under VS 2005 however with 2008 I get the following warning : warning C4002: too many actual parameters for macro 'SH_ASSERT' The calling code is simply : SH_ASSERT(0, donkeys != aliens , "Donkeys are Aliens Code : Code %d condition %d" , 55, 666); I'm sure Im missing something simple and my google foo is failing me... Thanks.
Change the argument order (put description with the ... part) to do something like this: #define SH_ASSERT( assertID, exp, ... ) shAssertBasic( int(exp), assertID, __LINE__, __FILE__, __VA_ARGS__ ) It should do the trick, You also have the possibility to suppress the warning in windows: #pragma warning (push) #pragma warning( disable:code/number ) #pragma warning (pop)
2,354,103
2,354,116
typedef struct problem
I'm new in c++, how to made code below work (compile without a syntax error)? typedef struct _PersonA{ char name[128]; LPPersonB rel; }PersonA, *LPPersonA; typedef struct _PersonB{ char name[128]; LPPersonA rel; }PersonB, *LPPersonB; Please, don't ask me why I need to do it like this, because it is just an example to explain my question.
You have to forward declare: struct _PersonB; typedef struct _PersonA{ char name[128]; _PersonB* rel; // no typedef }PersonA, *LPPersonA; typedef struct _PersonB{ char name[128]; LPPersonA rel; }PersonB, *LPPersonB; That said, this is very...ugly. Firstly, there is no need for the typedef in C++: struct PersonB; struct PersonA { char name[128]; PersonB* rel; }; struct PersonB { char name[128]; PersonA* rel; }; Which also has the side-effect of getting rid of your bad name: _PersonA. This name is reserved for the compiler because it begins with an underscore followed by a capital letter. And that's it. Hiding pointers behind typedef's is generally considered bad, by the way.
2,354,138
2,354,192
Printing messages to console from C++ DLL
I have an application which uses C# for front end and C++ DLL for the logic part. I would want to print error messages on console screen from my C++ DLL even when the C# GUI is present. Please let me know how to do this. Thanks, Rakesh.
You can use AllocConsole() to create a console window and then write to standard output. If you are using C or C++ standard I/O functions (as opposed to direct win32 calls), there are some extra steps you need to take to associate the new console with the C/C++ standard library's idea of standard output. http://www.halcyon.com/~ast/dload/guicon.htm explains what you have to do and why, with complete code.
2,354,145
2,354,150
how to remove what setpixel put on the window?? (c++)
im using SetPixel to make stuff on my window which is the easyest because i only want to set one pixel at a time. SetPixel is great but i need to remove the color every time i update it, i could overwrite the color by black but.. it's a really big waste of time is there some way i can over write all of the colors to black? (i would like something that is faster then reseting them all to black). i make a window and then color with setpixel (there is other ways (to draw on the window) but i only want to set one pixel/color at a time)
You should typically create a bitmap, lock it, set and unset its pixels directly - possibly by direct access rather than using API calls, if there are a lot of updates - unlock and then invalidate the window so that your paint handler can blit the bitmap later. If you want to restore pixels, you can keep two bitmaps and store the values to restore in one bitmap.
2,354,152
2,354,222
P/Invoke a purely C++ library?
Is it possible to P/Invoke a pure C++ library, or does it have to be wrapped in C?
C++ libraries can be P/invoked, but you'll need to use "depends" to find the mangled method names (names like "@0!classname@classname@zz") and for instance methods use "ThisCall" calling convention in the p/invoke and pass the reference of the instance as the first argument (you can store the result of the constructor within an IntPtr).
2,354,302
2,374,047
Static source code analysis with LLVM
I recently discover the LLVM (low level virtual machine) project, and from what I have heard It can be used to performed static analysis on a source code. I would like to know if it is possible to extract the different function call through function pointer (find the caller function and the callee function) in a program. I could find the kind of information in the website so it would be really helpful if you could tell me if such an library already exist in LLVM or can you point me to the good direction on how to build it myself (existing source code, reference, tutorial, example...). EDIT: With my analysis I actually want to extract caller/callee function call. In the case of a function pointer, I would like to return a set of possible callee. both caller and callee must be define in the source code (this does not include third party function in a library).
You should take a look at Elsa. It is relatively easy to extend and lets you parse an AST fairly easily. It handles all of the parsing, lexing and AST generation and then lets you traverse the tree using the Visitor pattern. class CallGraphGenerator : public ASTVisitor { //... virtual bool visitFunction(Function *func); virtual bool visitExpression(Expression *expr); } You can then detect function declarations, and probably detect function pointer usage. Finally you could check the function pointers' declarations and generate a list of the declared functions that could have been called using that pointer.
2,354,701
2,356,242
Deleting an std::map (Visual C++)
I have a pointer to a map that I am trying to delete (this map was allocated with new). This map is valid I think, when I hover on it while debugging, it shows pMap: [0]() .. When I try to delete this empty map, my app just quits and I get a First-chance exception at 0xsomelocation in myapp.exe: 0xsomenumber: The object invoked has disconnected from its clients. in the output window. What does this mean? Thanks.. EDIT: Here's some sample code: typedef map<const char*, StructA*, StructB> myMap; typedef vector<myMap *> myMapStack; StructB has an overloaded operator () Edit: StructB IS indeed a struct, sorry, the operator () is just a string comparing function.. In some part of my code, a class's constructor calls a method, let's call it InitClass(), that initializes a myMap pointer like so: pMyMap = new myMap; // I also tried this with new myMap() // this pointer is then pushed onto the a map stack pMyMapStack.push_back(pMyMap); Later on in this class' destructor, I go pMyMap = pMyMapStack.back(); pMyMapStack.pop_back(); delete pMyMap; // after I step over this line the app quits.. and displays that message Thanks EDIT: I reverted back to an older version of the code that worked, and it's working fine now.. What worked was something like this: // after the pMyMapStack.pop_back() int x = pMyMap->size(); if (x >= 0) delete pMyMap; Earlier on I had changed it to this: // after the pMyMapStack.pop_back() int (x = pMyMap->size(); if (x >= 0){ pMyMap->clear(); delete pMyMap; } Weird.. There might be something else wrong in the code, but I just can't figure out where yet.. It is too big (and I'd probably get fired) if I posted the code in it's entirety so let's just leave it at that.. I think it might have been a pointer to a null map that I was trying to clear or delete that was causing the problems.. Thanks for all those who tried to help... :)
honestly i think we are going no where without real code posted. there might be 101 place where the code went wrong, not limited to the snippet posted. from the object insertion and removal implementation shown, there are no syntax nor logical error. if the source code was so valuable to be shared on here, try create an dummy project, simple enough to demonstrate the problem (if the problem doesn't exist in dummy proj, you know you're tackling wrong direction)
2,354,768
2,354,841
C++ equivalent for java final member data
First, my latest coding is Java, and I do not want to "write Java in C++". Here's the deal, I have to create an immutable class. It's fairly simple. The only issue is that getting the initial values is some work. So I cannot simply call initializes to initialize my members. So what's the best way of creating such a class? And how can I expose my immutable / final properties to the outside world in C++ standards? here's a sample class: class Msg { private: int _rec_num; int _seq; string text; public: Msg(const char* buffer) { // parse the buffer and get our member here... // ... lots of code } // does this look like proper C++? int get_rec_num() { return _rec_num; } };
C++ offers some nice mechanisms to make your class immutable. What you must do is: declare all your public (and maybe protected) methods const declare (but not define) operator= as private This will ensure that your objects cannot be modified after they have been created. Now, you can provide access to your now immutable data members anyway you want, using const methods. Your example looks right, provided that you make it const: int get_rec_num() const { return _rec_num; } EDIT: Since C++11 you can explicitly delete operator=, rather than just leave it undefined. This explicitly instructs the compiler to not define a default copy assignment operator: Msg& operator=(const Msg&) = delete;
2,354,784
2,354,807
__attribute__((format(printf, 1, 2))) for MSVC?
With GCC, I can specify __attribute__((format(printf, 1, 2))) , telling the compiler that this function takes vararg parameters that are printf format specifiers. This is very helpful in the cases where I wrap e.g. the vsprintf function family. I can have extern void log_error(const char *format, ...) __attribute__((format(printf, 1, 2))); And whenever I call this function, gcc will check that the types and number of arguments conform to the given format specifiers as it would for printf, and issue a warning if not. Does the Microsoft C/C++ compiler have anything similar ?
While GCC checks format specifiers when -Wformat is enabled, VC++ has no such checking, even for standard functions so there is no equivalent to this __attribute__ because there is no equivalent to -Wformat. I think Microsoft's emphasis on C++ (evidenced by maintaining ISO compliance for C++ while only supporting C89) may be in part the reason why VC++ does not have format specifier checking; in C++ using <iostream> format specifiers are unnecessary.
2,354,834
2,354,948
Alternative way to capture the screen? (c++, windows OS)
keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY, 0); keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); HBITMAP h; OpenClipboard(NULL); h = (HBITMAP)GetClipboardData(CF_BITMAP); CloseClipboard(); ... normally this works well. but if the foreground window changes and locks the clipboard then it can't open clipboard. Is there any alternative way to capture the screen -that can work in background too-? thanks,
A simple scheme to capture the screen of monitor 1, that served me well but doesn't cover all corner cases: Get the screen device context. Create a device context compatible with the screen device context. Create a device independent bitmap (needed to get at the pixel data) that is as large as the screen resolution. Select the device independent bitmap into the compatible device context. Bit blit the screen device context onto the compatible device context. Deselect the device independent bitmap. The image data is now in the device independent bitmap. Optionally write the image data to file.
2,354,901
2,355,117
C++ Lib/Headers in Emacs
Where could I find C++ libraries in my emacs? I have already installed emacs on my computer and already using it lately. I just want to add boost libraries in emacs so I could use them.
Emacs is a text editor, it doesn't compile your code. It doesn't know (or need to know) anything about your libraries. However, there are commands for running the compiler from inside emacs, I've never done it myself, I use command line compiling and makefiles for bigger projects. I would write the program using the boost libraries (or any libraries) just like normal. I'm guessing you'd use GCC to compile as you're using emacs to edit. When compiling you need to tell the compiler (GCC) where to look for the header files and the libraries. For example, in your program you will have a line like #include <library.h> then compile it using g++ myprogram.cpp -I/path/to/header/files -L/path/to/library If your program is more than a couple of files, I would recommend writing a makefile for it and including all the required compiler flags and search paths in the makefile.
2,354,905
2,354,958
Reading from the serial port from C++ or Python on windows
I need to read the serial port from windows, using either Python or C++. What API/Library should I use? Can you direct me to a tutorial? Thanks!
In python you've excellent package pyserial that should be cross-platform (I've used only in GNU/Linux environment). Give it a look, it's very simple to use but very powerful! Of course examples are provided! By the way, if it can be useful here you can find a project of mine which use pyserial, as an extended example.
2,355,056
2,355,084
How to mix Qt, C++ and Obj-C/Cocoa
I have a pure C++/Qt project on a Mac, but I now find that I need to call a few methods only available in the Cocoa API. Following instructions listed here: http://el-tramo.be/blog/mixing-cocoa-and-qt I have a C++ class implementation in a ".m" file. As a test, my "foo.m" file contains the following code (relevant #include methods have been stripped for clarity).: int foo::getMagicNumber() { NSCursor *cursor = [NSCursor new]; } Apparently, I need to add the .m file to a qmake variable called OBJECTIVE_SOURCES. My project .pro file looks like this: TARGET = testApp CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp OBJECTIVE_SOURCES += foo.m HEADERS += test.h However, I get the following error whenever I try and compile my project: foo.h:4expected '=', ',', ';', 'asm' or '__attribute__' before 'foo' This is pointing at the class foo file in my header file. If I remove all cocoa calls from the .m file, and move the .m file into the SOURCES section of my Qt .pro file everything works as expected. I'm using Qt 4.6.0. My question is: What is the recommended way of integrating Cocoa calls with Qt / C++, and what am i doing wrong in the example above?
It's compiling your .m file as Objective-C. You want it to be a .mm file for Objective-C++.
2,355,195
2,355,213
Check for derived type (C++)
How do I check at runtime if an object is of type ClassA or of derived type ClassB? In one case I have to handle both instances separately ClassA* SomeClass::doSomething ( ClassA* ) { if( /* parameter is of type base class */) { } else if { /* derived class */ ) { } } Maybe I could say that the derived class ClassB has some special capabilities. But how do I do that without changing the existing class ClassA ?
It's generally a very bad idea to switch on the exact type like that. By doing this, you are tightly coupling your method to derived classes of ClassA. You should use polymorphism. Introduce a virtual method in class A, override it in class B and simply call it in your method. Even if I was forced to handle the functionality in the external function itself for some reason, I would do something like: class ClassA { public: virtual bool hasSpecificFunctionality() { return false; } }; class ClassB : public ClassA { public: virtual bool hasSpecificFunctionality() { return true; } }; ClassA* SomeClass::doSomething ( ClassA* arg ) { if (arg->hasSpecificFunctionality()) { } else { } }
2,355,273
2,355,315
Overloading << operator and recursion
I tried the following code: #include <iostream> using std::cout; using std::ostream; class X { public: friend ostream& operator<<(ostream &os, const X& obj) { cout << "hehe"; // comment this and infinite loop is gone return (os << obj); } }; int main() { X x; cout << x; return 0; } When I compile & run this, it's as expected; an infinite loop. If I remove the cout statement inside the friend function, the recursion doesn't happen. Why is it so?
Optimizer decides all your remaining activity has no effect and optimizes it away. Whether it's right or wrong is a different matter. In particular: X x; creates empty object "x" cout << x; calls: return (os << obj); which is appending empty object; the compiler notices 'os' hasn't grown any since the last call and shows no promise doing so any further (and nothing else happens) so it decides the whole business is redundant and can be truncated at this point. In case you call cout << "hehe"; // comment this and infinite loop is gone there is some extra activity so the optimizer doesn't remove the following call. I guess if you initialized x with anything non-empty, or performed any non-null activity other than cout << "hehe";, you'd have recursion running just the same.
2,355,300
2,355,335
conditional compilation statement in limits.h
I am not able to understand the following statement from the file limits.h. What is the use of this statement and what does it accomplishes? /* If we are not using GNU CC we have to define all the symbols ourself. Otherwise use gcc's definitions (see below). */ #if !defined __GNUC__ || __GNUC__ < 2
It checks if your program is compiled by some other compiler than GCC, or some very old GCC version.
2,355,433
2,355,452
c++ variable initialization in a class to send it using mpi
I got stuck in a programming task. I want the elements of my stl vector to be placed in a contiguous memory to send it with MPI_Send() routine. here is an example: class Tem { //... private: vector<double> lenghtVector (4500);//this gives a compilation error but I need to have a fixed sized vector }; how can I have a vector with a serial memory of should I do something else? Thanks. Kindest Regards. SRec
The elements of a vector are stored contiguously according to C++ Standard (23.2.4/1). To resize it you could use appropriate constructor in the initializer list of Tem class.: class Tem { Tem() : lenghtVector(4500) {}; private: vector<double> lenghtVector; };
2,355,454
2,355,494
Segmentation fault from std::_Rb_tree_const_iterator<Type>::operator++
I get a segmentation fault when iterating over a set. The stack trace points to std::_Rb_tree_const_iterator<Type>::operator++ std::_Rb_tree_increment() but I get nothing more informative. The iterator is over a set returned by a function for (FactSet::factset_iterator fact_it = (*binSet_it).getDependencyGraph().getExtentionalFactSet().begin(); fact_it != (*binSet_it).getDependencyGraph().getExtentionalFactSet().end(); ++fact_it) {...} I cannot see the issue. Thanks in advance.
You don't want to be iterating over the return value like that. The middle termination condition is re-evaluated every iteration, so your end() will be for a different set every time, which means your iterator will never reach it. Cache the set in a local variable and then use the begin() and end() from that.
2,355,585
2,355,614
Error in using vector pointer in a function
I have this code, but it won't compile and i can't understand what is wrong - i guess the pointering of the vector is not correct. My idea was to collect some numbers in main() and store them in a vector and array, and then pass the memory address of them to a function, and using a pointers to print the data stored. I came up with this when i read something about pointers which said that i should use them in order to save memory, so IMO the code below will not copy the contents of the vector and the array but use a pointer to access their location in memory - that's what i want to do. #include <iostream> #include <vector> using namespace std; void function(vector<int>* a, int *s) { cout << "function starts.." << endl; for(int i=0;i<a->size();i++) { cout << a[i] << endl; cout << s[a[i]] << endl; } cout << "function ends..." << endl; } int main(void) { vector<int> m; int s[102]; for(int i=0;i<10;i++) { m.push_back(i*i); s[i*i] = i-2; } function(&m, &s); return 0; } I receive several errors on compiling, something is wrong. Please tell me what's wrong with my code and how to fix it. thank you...
You should pass the vector by reference, not by pointer: void function(vector<int>& a, int *s) And then function(m, ...); Using [] on a pointer to a vector would certainly cause strange problems because it behaves as if a pointed to an array of std::vectors (while it actually only points to one). The vectors itself are never indexed by that. You could also use (*a)[...] to index the vector by the pointer.
2,355,592
2,359,728
typecasting to unsigned in C
int a = -534; unsigned int b = (unsigned int)a; printf("%d, %d", a, b); prints -534, -534 Why is the typecast not taking place? I expected it to be -534, 534 If I modify the code to int a = -534; unsigned int b = (unsigned int)a; if(a < b) printf("%d, %d", a, b); its not printing anything... after all a is less than b??
First, you don't need the cast: the value of a is implicitly converted to unsigned int with the assignment to b. So your statement is equivalent to: unsigned int b = a; Now, an important property of unsigned integral types in C and C++ is that their values are always in the range [0, max], where max for unsigned int is UINT_MAX (it's defined in limits.h). If you assign a value that's not in that range, it is converted to that range. So, if the value is negative, you add UINT_MAX+1 repeatedly to make it in the range [0, UINT_MAX]. For your code above, it is as if we wrote: unsigned int b = (UINT_MAX + a) + 1. This is not equal to -a (534). Note that the above is true whether the underlying representation is in two's complement, ones' complement, or sign-magnitude (or any other exotic encoding). One can see that with something like: signed char c = -1; unsigned int u = c; printf("%u\n", u); assert(u == UINT_MAX); On a typical two's complement machine with a 4-byte int, c is 0xff, and u is 0xffffffff. The compiler has to make sure that when value -1 is assigned to u, it is converted to a value equal to UINT_MAX. Now going back to your code, the printf format string is wrong for b. You should use %u. When you do, you will find that it prints the value of UINT_MAX - 534 + 1 instead of 534. When used in the comparison operator <, since b is unsigned int, a is also converted to unsigned int. This, given with b = a; earlier, means that a < b is false: a as an unsigned int is equal to b. Let's say you have a ones' complement machine, and you do: signed char c = -1; unsigned char uc = c; Let's say a char (signed or unsigned) is 8-bits on that machine. Then c and uc will store the following values and bit-patterns: +----+------+-----------+ | c | -1 | 11111110 | +----+------+-----------+ | uc | 255 | 11111111 | +----+------+-----------+ Note that the bit patterns of c and uc are not the same. The compiler must make sure that c has the value -1, and uc has the value UCHAR_MAX, which is 255 on this machine. There are more details on my answer to a question here on SO.
2,355,816
2,355,850
Transferring signature of the method as template parameter to a class
I'd like to create a template interface for data-handling classes in my projects. I can write something like this: template <class T> class DataHandler { public: void Process(const& T) = 0; }; Then, suppose, I define a class this way: class MyClass: public DataHandler<int> { void Process(const int&) { /* Bla-bla */ } } Now, come the question, can I somehow define my template interface in the way that as parameter it will recieve not just type T, but the whole signature of the Process() function. I would like something working this way: class MyClass: public DataHandler<void (int&)> { void Process(const int&) { /* Bla-bla */ } } Is it possible? I know that, for instance, boost::signal receives template parameters this way, but, if I understand correctly, they use lot of black-magic there.
Yep you can. But in C++03, you are bound to do copy/paste code for every number of parameters (not too bad, since here you won't need overloads for const/non-const etc. The constnes is already known!). template<typename FnType> struct parm; template<typename R, typename P1> struct parm<R(P1)> { typedef R ret_type; typedef P1 parm1_type; }; template <class T> class DataHandler { typedef typename parm<T>::ret_type ret_type; typedef typename parm<T>::parm1_type parm1_type; public: virtual ret_type Process(parm1_type t) = 0; }; class MyClass: public DataHandler<void (const int&)> { void Process(const int&) { /* Bla-bla */ } }; In C++0x, you will be able to write template <class T> class DataHandler; template<typename R, typename ... P> class DataHandler<R(P...)> { public: virtual R Process(P... t) = 0; }; class MyClass: public DataHandler<void (const int&)> { void Process(const int&) { /* Bla-bla */ } }; How much nicer!
2,355,876
2,398,248
Windows Spooler Events API doesn't generate events for network printers
the context i use Spooler Events API to capture events generated by the spooler when a user prints a document ie. FindFirstPrinterChangeNotification FindNextPrinterChangeNotification the problem When I print a document on the network printers from my machine no events are captured by the monitor (uses the functions above) Notice Events ARE generated OK for local printers, only Network Printers are problematic!
From the documentation: Note: In Windows XP with Service Pack 2 (SP2) and later, the Internet Connection Firewall (ICF) blocks printer ports by default, but an exception for File and Print Sharing can be enabled. If a user makes a printer connection to another machine, and the exception is not enabled, then the user will not receive printer change notifications from the server. A machine admin will have to enable exception.
2,356,001
2,359,579
How to load a Windows icon using a pixel buffer?
I'm trying to create a Windows-compatible icon using a pixel buffer. The Surface class loads an image and saves it as an unsigned int array internally (0xRRGGBB). I'm trying to create an icon like so: Surface m_Test("Data/Interface/CursorTest.png"); HICON result = CreateIconFromResourceEx( (PBYTE)m_Test.GetBuffer(), m_Test.GetWidth() * m_Test.GetHeight(), FALSE, 0, 24, 24, LR_DEFAULTCOLOR ); However, result is always NULL. I can't find anywhere what data format CreateIconFromResourceEx expects. Ultimately I want to load an icon from an external file, without using resource files. Thanks in advance. EDIT: I figured it out! The final codez: // m_Cursors is an array of images coming from an image strip Pixel* buffer = m_Cursors[i]->GetBuffer(); int width = m_Cursors[i]->GetWidth(); int height = m_Cursors[i]->GetHeight(); HDC dc_andmask = CreateCompatibleDC(dc); HBITMAP cur_andmask = CreateCompatibleBitmap(dc, width, height); HBITMAP hOldAndMaskBitmap = (HBITMAP)SelectObject(dc_andmask, cur_andmask); HDC dc_xormask = CreateCompatibleDC(dc); HBITMAP cur_xormask = CreateCompatibleBitmap(dc, width, height); HBITMAP hOldXorMaskBitmap = (HBITMAP)SelectObject(dc_xormask, cur_xormask); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { Pixel currpix = buffer[x + y * width]; // the images use the alpha channel for transparancy if ((currpix & 0xFF000000) == 0 { // transparant SetPixel(dc_andmask, x, y, RGB(255, 255, 255)); SetPixel(dc_xormask, x, y, RGB(0, 0, 0)); } else { COLORREF curr = RGB(currpix & 0xFF0000 >> 16, currpix & 0x00FF00 >> 8, currpix & 0x0000FF); // opaque SetPixel(dc_andmask, x, y, RGB(0, 0, 0)); SetPixel(dc_xormask, x, y, curr); } } } // i don't know why this has to be done, but it fixes things // so who cares (b ")b SelectObject(dc_andmask, hOldAndMaskBitmap); SelectObject(dc_xormask, hOldXorMaskBitmap); DeleteObject(dc_xormask); DeleteObject(dc_andmask); ICONINFO temp = { FALSE, m_OffsetX[i], m_OffsetY[i], cur_andmask, cur_xormask }; m_CursorIDs[i] = CreateIconIndirect(&temp);
Use CreateIcon if you want to pass the raw bytes data from the AND and XOR mask. If instead you want to be able to use HBITMAPs, you can use CreateIconIndirect. Using this API, you can can even create icons with an alpha channel if you so desire.
2,356,116
2,356,205
Recommend crossplatform C++ UI and networking libraries
Things to take into consideration: - easy to use - fast - use underlying OS as much as feasable (like wxWidgets for UI) Ones I am leaning towards are wxWidgets for UI and Boost for networking - how do they compare to others?
I've had good look with wxWidgets on the front end and boost::asio on the network end. wxWidgets does have network classes built in, but you hit the wall quickly on them, and there's one or two big limitations. If you want to stay in the wx world, there's a package called wxCurl which is a fine package (I used it in the early days) that wraps libCurl with some wxWidgets idomatic C++. In a previous project of mine (a network/file transfer heavy project) we ended up going with boost::asio, which had the advantage of not being all that hard of an API, easier-seeming to set up that libCRUL (although that may have gotten better, that was been several years now), and gives us a very generic networking core (boost can compile anywhere, even command line apps)
2,356,120
2,356,722
Documenting preprocessor defines in Doxygen
Is it possible to document preprocessor defines in Doxygen? I expected to be able to do it just like a variable or function, however the Doxygen output appears to have "lost" the documentation for the define, and does not contain the define itself either. I tried the following /**My Preprocessor Macro.*/ #define TEST_DEFINE(x) (x*x) and /**@def TEST_DEFINE My Preprocessor Macro. */ #define TEST_DEFINE(x) (x*x) I also tried putting them within a group (tried defgroup, addtogroup and ingroup) rather than just at the "file scope" however that had no effect either (although other items in the group were documented as intended). I looked through the various Doxygen options, but couldn't see anything that would enable (or prevent) the documentation of defines.
Yes, it is possible. The Doxygen documentation says: To document global objects (functions, typedefs, enum, macros, etc), you must document the file in which they are defined. In other words, there must at least be a /*! \file */ or a /** @file */ line in this file. You can use @defgroup, @addtogroup, and @ingroup to put related items into the same module, even if they appear in separate files (see documentation here for details). Here's a minimal example that works for me (using Doxygen 1.6.3): Doxyfile: # Empty file. Test.h: /** @file */ /**My Preprocessor Macro.*/ #define TEST_DEFINE(x) (x*x) /** * @defgroup TEST_GROUP Test Group * * @{ */ /** Test AAA documentation. */ #define TEST_AAA (1) /** Test BBB documentation. */ #define TEST_BBB (2) /** Test CCC documentation. */ #define TEST_CCC (3) /** @} */ Foo.h: /** @file */ /** * @addtogroup TEST_GROUP * * @{ */ /** @brief My Class. */ class Foo { public: void method(); }; /** @} */ Bar.h: /** @file */ /** * @ingroup TEST_GROUP * My Function. */ void Bar(); In this case, the TEST_DEFINE documentation appears in the Test.h entry under the Files tab in the HTML output, and the TEST_AAA etc. definitions appear under Test Group in the Modules tab together with class Foo and function Bar. One thing to note is that if you put the file name after the @file command, e.g: /** @file Test.h */ then this must match the actual name of the file. If it doesn't, documentation for items in the file won't be generated. An alternative solution, if you don't want to add @file commands, is to set EXTRACT_ALL = YES in your Doxyfile. I hope this helps!
2,356,136
2,356,175
Can you create a start-up window in console program?
I want to a create dialog box like window before displaying the console window. I haven't actually tried anything yet but was just wondering if it can be displayed as a start-up window.
If you compile your win32 application as a console app, the console window will appear before you get a chance to do anything else. To get around this, you need to use a windows application - this won't display a console window at all by default. Some time after startup you can then call AllocConsole to create a console window.
2,356,168
2,356,393
Force GCC to notify about undefined references in shared libraries
I have a shared library that is linked with another (third-party) shared library. My shared library is then loaded using dlopen in my application. All this works fine (assuming files are in the proper path etc). Now, the problem is that I don't even need to specify to link against the third-party shared library when I link my library. GCC accept it without reporting errors about undefined references. So, the question; how can I force GCC to notify me about undefined references? If I change my library to be (temporarily) an executable, I get undefined references (when not supplying the library to the linker). (Works fine if I specify it.) I.e., the following is done: g++ -fPIC -shared -o libb.so b.o g++ -fPIC -shared -o liba.so a.o g++ -o a.exe a.cpp Where the second line does NOT give out an error and the third line complains about an undefined reference. Sample code: a.h: class a { public: void foobar(); }; a.cpp: #include "a.h" #include "b.h" void a::foobar() { b myB; myB.foobar(); } int main() { a myA; myA.foobar(); } b.h: class b { public: void foobar(); }; b.cpp: #include "b.h" void b::foobar() { }
-Wl,--no-undefined linker option can be used when building shared library, undefined symbols will be shown as linker errors. g++ -shared -Wl,-soname,libmylib.so.5 -Wl,--no-undefined \ -o libmylib.so.1.1 mylib.o -lthirdpartylib
2,356,402
2,379,938
Unique controls identification
Is there any way to uniquely identify controls using Accessibility? Once control is identified - I should be able to get its current position on screen (rectangle). Tried to do this with IAccIdentity, but don't know what to do with that string of bytes which it returns - is there any way I can extract necessary information from it (or obtain IAccessible using this string) Thanks.
Is this identity supposed to last across multiple invocations of the process? For the lifetime of a control its HWND is a unique identifer. OTOH, controls can be moved around the screen like any child window -- either moved relative to the parent or the parent may move taking the child with it. They can be created and destroyed dynamically as well, although that's less common.
2,356,450
2,356,748
Create C# bindings for complex system of C++ classes?
I have existing C++ lib containing many different classes working together. Some example usage should include something like passing an instance of one class to constructor/method of another class. I am planning to provide a C# binding for these C++ classes using C++/CLI therefore I don't have to port the whole C++ code. I can already do this in "Facade" way by creating another class which hides all the classes used in existing C++ code from the user. However, what I want is to provide the same classes with same method signatures to the user. Is there any guideline or recommendation for this? ps. I have looked at some of the existing opensource C# to C++ bindings projects. But they seem to used many different ways of doing this, and I don't really understand it.
A lot of this is going to depend on the factoring of your classes. In the work that I do, I try to treat the C++ classes I model as hidden implementation details that I wrap into appropriate C++/CLI classes. For the most part, I can get away with that by having managed interfaces that are NOT particularly granular. When your implementation involves directly implementing every detail of the underlying C++ code, then you'll end up with a very "chatty" interface that will involve a fair amount of cost in managed/unmanaged transitions. In particular, if your unmanaged C++ classes use stl, especially stl collection types, you will likely find yourself in for an unpleasant surprise when you discover that every iteration through your stl collections involves several managed/unmanaged transitions. I had an image decoder that used stl heavily and it ran like a dog because of that. The obvious fix to put #pragmas around the code that accessed stl types didn't help. What I found that did work was to hide all of that in a handle-based C interface that hid all the C++-isms behind an iron curtain. No stl exposed anywhere meant that it was allowed to exist as unmanaged code. I think your biggest issue is going to be in how you handle collections (if you use any) as the C++ collection philosophy and the .NET collection philosophy don't match up well. I suspect that you will spend a lot of time mapping .NET collections of adapted classes to your C++ collections of classes/types. EDIT Here's a blog article I wrote about this issue some time ago. It uses the managed C++ dialect, not C++/CLI, but the issue is the same.
2,356,475
2,363,818
Getting shared_ptr refs to appear in doxygen collaboration diagrams
I've done enough Googling to know that if I have something like class SubObject { public: //blah blah blah }; class Aggregate { public: boost::shared_ptr<SubObject> m_ptr; }; I can get Doxygen to create the "correct" collaboration diagram if I have a dummy declaration like namespace boost { template<class T> class shared_ptr { T *dummy; }; } in my header file. My question is: how do I get that to work over all my projects and all my headers, without having to actually include that line in every file?
Heh.... I feel stupid answering my own questions, but I figure this one out pretty much right after posting it: Put the code snippet namespace boost { template<class T> class shared_ptr { T *dummy; }; } in a header file, called something like "doxygen_dummy.h", and make sure it's included in your project's workspace or directory. You don't need to actually #include it anywhere (in fact, you don't want to, to avoid violating the One Definition Rule). You just need for Doxygen to be able to see it when it scans all your files.
2,356,636
2,356,686
Reading binary data without reinterpret_cast
Just because I've never read binary files before I wrote a program that reads binary STL files. I use ifstreams read member that takes a char* a parameter. To cast my struct to a char* I use a reinterpret_cast. But as far as I remember every book about C++ I read said something like "don't use reinterpret_cast except you have to". What would be a better way read binary data, not necessarily direct, but at last into a struct and without reinterpret_cast? The main function: std::ifstream in (cmdline[1].c_str(), std::ios::binary); in.seekg(80, std::ifstream::beg); //skip header int numTriangle; in.read (reinterpret_cast<char*>(&numTriangle), sizeof(int)); //determine number of triangles //create triangle data type and read data triangle* t = new triangle(); for (int i = 0; i < numTriangle; ++i) { in.read(reinterpret_cast<char*>(t), triangle::size); std::cout << *t; // there's an opertor<< for triangle } delete t; in.close(); //close file read from And the triangle struct //attempt to get the right size of a class without structure padding #pragma pack(push) #pragma pack(1) //standard STL triangle data structure struct triangle { public: float n[3]; //normals, 4*3=12 bytes float x[3]; //first point of the triangle, 4*3=12 bytes float y[3]; //second point of the triangle, 4*3=12 bytes float z[3]; //third point of the triangle, 4*3=12 bytes long int a; //attributes, 2 bytes static const int size = 12+12+12+12+2; //sum of member variables //static const int size = sizeof(n) + sizeof(x) + sizeof(y) + sizeof(z) + sizeof(a); }; #pragma pack(pop) (Extra question: #pragma pack(1) doesn't work with cygwins g++-4. How can I determine the size of the struct?)
Well, that code looks fine. You are even caring about the padding issue. I don't see how you can avoid casting here. You can do this sequence: static_cast<char*>(static_cast<void*>(t)) But really, i don't do that in my code. It's just a more noisy way of doing a direct reinterpret_cast to char*. (See casting via void* instead of using reinterpret_cast ). The struct size can be determined using sizeof. You just have to initialize the static member out of the class inside the .cpp (however, then the compiler doesn't know the value of ::size anymore and can't inline it). Alternatively, you can write it as a static inline member function. In its body, the class type is considered complete and sizeof (triangle) is allowed. Or you can just use sizeof like you have in the comment, but use the type and not the members (referring to nonstatic members that way is allowed only in C++0x) : //standard STL triangle data structure struct triangle { public: float n[3]; //normals, 4*3=12 bytes float x[3]; //first point of the triangle, 4*3=12 bytes float y[3]; //second point of the triangle, 4*3=12 bytes float z[3]; //third point of the triangle, 4*3=12 bytes long int a; //attributes, 2 bytes static int size() { return sizeof(triangle); } // this way static const int size = sizeof(float[3])*4 + sizeof(long int); // or this way }; However, the second way is not nice since you can easily forget updating it when you add a member.
2,356,778
2,357,003
Closing a QMainWindow on startup?
I have a Qt application that uses a QMainWindow-derived class for the main UI. On startup I want to make some security checks and, if they fail, display a message to the user and close the main window. Currently I make these checks in the QMainWindow constructor, but if I call the close method, nothing happens and the application continues to run. For example: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setupUi(this); ... if (checkFails()) { QMessageBox::warning(this, tr("Error"), tr("You cannot run this app")); // This has no effect close(); } } Alternatively I could make the checks in the main function but then I lose the ability to display a language-specific message box (the tr macro only works in a QObject-derived class by the looks of things.) Any ideas on how to close the main window on startup or make the tr macro work outside of a QObject derived class?
The event loop needs to be running before you can successfully close the main window. Since you probably first construct a window, and then start the event loop the close() call has no effect. Try the following solution instead: QTimer::singleShot(0, this, SLOT(close())); The QTimer::singleShot() will fire as soon as an event loop has been started, and subsequently calls the close() method on your application main window. The above solution will probably cause your main application window to be visible for a short period of time, causing unwanted flickering. A cleaner solution should perform the security checks prior to constructing the main window. Since tr() is also available as a static method on QObject, this can be done from the main function.
2,357,091
2,357,105
thread-safety question
A simple situation here, If I got three threads, and one for window application, and I want them to quit when the window application is closed, so is it thread-safe if I use one global variable, so that three threads will quit if only the global variable is true, otherwise continue its work? Does the volatile help in this situation? C++ programming.
If you only want to "read" from the shared variable from the other threads, then it's ok in the situation you describe. Yes the volatile hint is required or the compiler might "optimize out" the variable. Waiting for the threads to finish (i.e. join) would be good too: this way, any clean-up (by the application) that should occur will have a chance to get done.
2,357,284
2,357,548
C++ concurrent associative containers?
I'm looking for a associative container of some sort that provides safe concurrent read & write access provided you're never simultaneously reading and writing the same element. Basically I have this setup: Thread 1: Create A, Write A to container, Send A over the network. Thread 2: Receive response to A, Read A from container, do some processing. I can guarantee that we only ever write A once, though we may receive multiple responses for A which will be processed serially. This also guarantees that we never read and write A at the same time, since we can only receive a response to A after sending it. So basically I'm looking for a container where writing to an element doesn't mess with any other elements. For example, std::map (or any other tree-based implementation) does not satisfy this condition because its underlying implementation is a red-black tree, so any given write may rebalance the tree and blow up any concurrent read operations. I think that std::hash_map or boost::unordered_set may work for this, just based on my assumption that a normal hash table implementation would satisfy my criteria, but I'm not positive and I can't find any documentation that would tell me. Has anybody else tried using these similarly?
The STL won't provide any solid guarantees about threads, since the C++ standard doesn't mention threads at all. I don't know about boost, but I'd be surprised if its containers made any concurrency guarantees. What about concurrent_hash_map from TBB? I found this in this related SO question.
2,357,596
2,357,637
HTTP stream server: threads?
I already wrote here about the http chat server I want to create: Alternative http port? This http server should stream text to every user in the same chat room on the website. The browser will stay connected and wait for further html code. (yes that works, the browser won't reject the connection). I got a new question: Because this chat server doesn't need to receive information from the client, it's not necessary to listen to the client after the server sent its first response. New chat messages will be send to the server on a new connection. So I can open 2 threads, one waiting for new clients (or new messages) and one for the html streaming. Is this a good idea or should I use one thread per client? I don't think it's good to have one thread/client when there are many chat users online, since the server should handle multiple different chats with their own rooms. 3 posibilities: 1. One thread for all clients, send text to each client successive - there shouldn't be much lag since it's only text this will be like: user1.send("text");user2.send("text"),... 2. One thread per chat or chatroom 3. One thread per chat user - ... many... Thank you, I haven't done much with sockets yet ;).
I think easiest pattern for this simple app is to have pool of threads and then for each client pick available thread or make it wait until one becomes available. If you want serious understanding of http server architecture concepts google following: apache architecture nginx architecture
2,357,633
2,357,666
Windows Mobile development: C++ or C# -- which one is better? why?
While doing Windows Mobile development, which language should I use? C# or C++ or something else? Why one is better than others?
It depends what you're coding. Making native calls to the OS are possible via P/Invoke from C#, but extensive use is probably easier via native C++. You'll also require C++ for using some hardware that has not been wrapped by the Compact Framework. Most hardware (GPS, camera, etc.), is available via CF. If you're working with a Win Mobile 6.x device, you're probably better off with C#. In addition to hardware, Pocket Office's (POOM) object model is also available to C#, so you can integrate with it. It's worth noting that most references to Windows Phone 7 refer to managed code and the possibility of Silverlight. With Silverlight in the mix, you'll have to code with C#. Unless your app is high performance or is extremely miserly with memory, use C# or VB.NET. Scott
2,357,720
2,357,786
Network byte order conversion with "char"
I've always been taught that if an integer is larger than a char, you must solve the byte ordering problem. Usually, I'll just wrap it in the hton[l|s] and convert it back with ntoh[l|s]. But I'm confused why this doesn't apply to single byte characters. I'm sick of wondering why this is, and would love for a seasoned networks programmer to help me shed some light on why byte orderings only apply for multibyte integers. Ref: https://beej.us/guide/bgnet/html/multi/htonsman.html
What you are looking for is endianness. A big-endian architecture stores the bytes of a multibyte data type like so: while a little-endian architecture stores them in reverse: When data is transferred from one machine to another, the bytes of a single data type must be reordered to correspond with the endianness of the destination machine. But when a data type only consists of one byte, there is nothing to reorder.
2,357,746
2,357,777
Interview question; what is the main theme of Effective C++?
I was asked the following question at a recent job interview: What do you think is the main theme / single word that sums up the Effective C++ series from Scott Meyers? What would be your answer to this question?
In one word it's Advice
2,357,798
2,357,902
C++ using precalculated limiters in for loops
In scripting languages like PHP having a for loop like this would be a very bad idea: string s("ABCDEFG"); int i; for( i = 0; i < s.length(); i ++ ) { cout << s[ i ]; } This is an example, i'm not building a program like this. (For the guys that feel like they have to tell me why this piece of code <insert bad thing about it here>) If this C++ example was translated to a similar PHP script the lenght of the string would be calculated every loop cycle. That would cause an enormous perfomance loss in realistic scripts. I thought the same would apply to C++ programs but when I take a look at tutorials, several open-source libraries and other pieces of code I see that the limiter for the loop isn't precalculated. Should I precalculate the lenght of the string s? Why isn't the limiter always precalculated? (seen this in tutorials and examples) Is there some sort of optimization done by the compiler?
It's all relative. PHP is interpreted, but if s.length drops into a compiled part of the PHP interpreter, it will not be slow. But even if it is slow, what about the time spent in s[i], and what about the time spent in cout <<? It's really easy to focus on loop overhead while getting swamped with other stuff. Like if you wrote this in C++, and cout were writing to the console, do you know what would dominate? cout would, far and away, because that innocent-looking << operator invokes a huge pile of library code and system routines.
2,357,879
2,358,220
c++ d3d hooking - COM vtable
Trying to make a Fraps type program. See comment for where it fails. #include "precompiled.h" typedef IDirect3D9* (STDMETHODCALLTYPE* Direct3DCreate9_t)(UINT SDKVersion); Direct3DCreate9_t RealDirect3DCreate9 = NULL; typedef HRESULT (STDMETHODCALLTYPE* CreateDevice_t)(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); CreateDevice_t RealD3D9CreateDevice = NULL; HRESULT STDMETHODCALLTYPE HookedD3D9CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) { // this call makes it jump to HookedDirect3DCreate9 and crashes. i'm doing something wrong HRESULT ret = RealD3D9CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); return ret; } IDirect3D9* STDMETHODCALLTYPE HookedDirect3DCreate9(UINT SDKVersion) { MessageBox(0, L"Creating d3d", L"", 0); IDirect3D9* d3d = RealDirect3DCreate9(SDKVersion); UINT_PTR* pVTable = (UINT_PTR*)(*((UINT_PTR*)d3d)); RealD3D9CreateDevice = (CreateDevice_t)pVTable[16]; DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)RealD3D9CreateDevice, HookedD3D9CreateDevice); if (DetourTransactionCommit() != ERROR_SUCCESS) { MessageBox(0, L"failed to create createdev hook", L"", 0); } return d3d; } bool APIENTRY DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID lpReserved) { if (fdwReason == DLL_PROCESS_ATTACH) { MessageBox(0, L"", L"", 0); RealDirect3DCreate9 = (Direct3DCreate9_t)GetProcAddress(GetModuleHandle(L"d3d9.dll"), "Direct3DCreate9"); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)RealDirect3DCreate9, HookedDirect3DCreate9); DetourTransactionCommit(); } // TODO detach hooks return true; }
The signature for the C interface of IDirect3D9::CreateDevice is: STDMETHOD(CreateDevice)( THIS_ UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow, DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) PURE; Which expands to: typedef HRESULT (STDMETHODCALLTYPE* CreateDevice_t)( IDirect3D9 FAR *This, // you forgot this. UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); In other words, you declared the thunk for CreateDevice incorrectly. Also, instead of directly indexing into the IDirect3D9 vtable, you might just want to #define CINTERFACE and access the function you want to override through d3d->lpVtbl->CreateDevice.
2,358,049
2,360,069
How do I rewrite equations from matlab for use in c++
I have derived and simplified an equation in Matlab and want to use it in a c++ program. Matlab likes to use powers, the ^ sign but c++ doesn't like it one bit. How can I get Matlab to rewrite the equation so that it outputs a c++ friendly equation?
If the equation is really so long that you don't want to go through by hand, one option you might consider for reformatting the equation to make it C++ friendly is to parse the text of the MATLAB code for the equation using the REGEXPREP function in MATLAB. Here's an example of how you could replace expressions of the form x^2 or y.^3 with pow(x,2) or pow(y,3): eqStr = 'the text of your equation code'; %# Put your equation in a string expr = '(\w+)\.?\^(\d+)'; %# The pattern to match repStr = 'pow($1,$2)'; %# The replacement string newStr = regexprep(eqStr,expr,repStr); %# The new equation string You would just have to take the code for your MATLAB equation and put it in a string variable eqStr first. The output from REGEXPREP will then be the text for your new C++ friendly equation newStr. You could also change the replacement string to give you results of the form x*x or y*y*y using dynamic operators. For example: eqStr = 'the text of your equation code'; %# Put your equation in a string expr = '(\w+)\.?\^(\d+)'; %# The pattern to match repStr = '${repmat([$1,''*''],1,$2-''0''-1)}$1'; %# The replacement string newStr = regexprep(eqStr,expr,repStr); %# The new equation string
2,358,056
2,358,299
Is there a way to reduce ostringstream malloc/free's?
I am writing an embedded app. In some places, I use std::ostringstream a lot, since it is very convenient for my purposes. However, I just discovered that the performance hit is extreme since adding data to the stream results in a lot of calls to malloc and free. Is there any way to avoid it? My first thought was making the ostringstream static and resetting it using ostringstream::set(""). However, this can't be done as I need the functions to be reentrant.
Well, Booger's solution would be to switch to sprintf(). It's unsafe, and error-prone, but it is often faster. Not always though. We can't use it (or ostringstream) on my real-time job after initialization because both perform memory allocations and deallocations. Our way around the problem is to jump through a lot of hoops to make sure that we perform all string conversions at startup (when we don't have to be real-time yet). I do think there was one situation where we wrote our own converter into a fixed-sized stack-allocated array. We have some constraints on size we can count on for the specific conversions in question. For a more general solution, you may consider writing your own version of ostringstream that uses a fixed-sized buffer (with error-checking on the bounds being stayed within, of course). It would be a bit of work, but if you have a lot of those stream operations it might be worth it.
2,358,131
2,358,295
Mapping between two sets of classes
I have a requirement where in i have a set of classes and they have a one on one correspondence with another set of classes. Consider something like this a) template < class A > class Walkers { int walk( Context< A >* context ); }; The set of Context classes are not templates. They are individual classes. I need to create a mapping between these two sets. One way, i could think of is to create a typelist and refer to the class at the appropriate location. But i feel that is more error prone, as i may mismatch the Contexts in the typelist. Can someone advise me how to do this ? Thanks, Gokul.
I am not sure to understand what you want to do, what your requirements or goal are, but you could try to use traits to define the relationship: // direct mapping template <typename T> struct context_of; template <> struct context_of<A> { typedef ContextA type; }; // reverse mapping template <typename T> struct from_context; template <> struct from_context< ContextA > { typedef A type; }; The code you posted would be written as: template <typename T> class Walker { public: typedef typename context_of<T>::type context_type; int walker( context_type* context ); }; To reduce typing you could build the mappings out of typelists (possibly complex), or you might want to use a helper macro (dirtier, simpler): #define GENERATE_CONTEXT_ENTRY( the_class, the_context ) \ template <> struct context_of< the_class > { \ typedef the_context type; }; \ template <> struct from_context< the_context > \ typedef the_class type; }; GENERATE_CONTEXT_ENTRY( A, ContextA ); GENERATE_CONTEXT_ENTRY( B, ContextB ); #undef GENERATE_CONTEXT_ENTRY