question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,402,522
1,402,554
shared_ptr and references in C++
References in C++ are a conveneint construct that allow us to simplify the following C code: f(object *p){ //do something } int main(){ object* p = (object*) calloc(sizeof(object)); f(p); } to f(object& o){ //do something } int main(){ object o = object(); f(o); } Shared pointers are another convenience in C++ that simplify memory management. However, I am not sure how to pass a shared_ptr to a function like f(object& o) which accepts arguments by reference? f(object& o){ //do something } int main(){ shared_ptr<object> p (new object()); f(*p); } Will the shared pointer be incremented when its object is passed by reference to a function?
Take a shared_ptr by value, and the reference count will increase. This is easier when you typedef it: typedef boost:shared_ptr<object> object_ptr; void foo(object_ptr obj) { obj->/* stuff*/; obj.reset(); //only resets this local copy, that means: // reduce reference count (back to 1), and // set obj to point at null. } int main(void) { object_ptr obj(new object()); foo(obj); } Keep in mind references are aliases. When you pass by reference, you're not passing pointers, copies, etc..., you're aliasing another object. (In reality they are implemented as pointers): typedef boost:shared_ptr<object> object_ptr; void foo(object_ptr& obj) { obj.reset(); // the references was never increased, since a copy has not // been made, this *is* obj in main. so the reference // goes to 0, and obj is deleted } int main(void) { object_ptr obj(new object); foo(obj); // after this, obj has been reset! } Always remember to be const correct, to prevent errors: typedef boost:shared_ptr<object> object_ptr; void foo(const object_ptr& obj) { obj.reset(); // cannot do! } int main(void) { object_ptr obj(new object); foo(obj); } I think you should prefer to pass smart pointers as references when possible, to avoid extraneous increments and decrements (and copies and whatnot).
1,402,948
1,402,973
which is the most efficient XML Parser for C++?
I need to write an application that fetches element name value (time-series data) pair from any xml source, be it file, web server, any other server. the application would consume the XML and take out values of interest, it has to be very very fast (lets say 50000 events/seconds or more) also the XML document size would be huge and frequency of these document could be high as well (for ex. 2500 files/min - more than 500MB of XML data/file). I just want to see how you experienced people think I should approach this. I am a novice who just got started although I can do any solution you suggest me, no matter how tough/easy. Thank you very much.
If you use SAX parsing, your bottleneck is the I/O involved, not the XML string processing. And given your 500 MB number, I'd say you'd have to do SAX parsing instead of DOM parsing. So, anything with a SAX type interface should be just fine.
1,403,150
1,403,157
How do you dynamically allocate a matrix?
How do you dynamically allocate a 2D matrix in C++? I have tried based on what I already know: #include <iostream> int main(){ int rows; int cols; int * arr; arr = new int[rows][cols]; } It works for one parameter, but now for two. What should I do?
A matrix is actually can be represented as an array of arrays. int rows = ..., cols = ...; int** matrix = new int*[rows]; for (int i = 0; i < rows; ++i) matrix[i] = new int[cols]; Of course, to delete the matrix, you should do the following: for (int i = 0; i < rows; ++i) delete [] matrix[i]; delete [] matrix; I have just figured out another possibility: int rows = ..., cols = ...; int** matrix = new int*[rows]; if (rows) { matrix[0] = new int[rows * cols]; for (int i = 1; i < rows; ++i) matrix[i] = matrix[0] + i * cols; } Freeing this array is easier: if (rows) delete [] matrix[0]; delete [] matrix; This solution has the advantage of allocating a single big block of memory for all the elements, instead of several little chunks. The first solution I posted is a better example of the arrays of arrays concept, though.
1,403,251
1,405,366
Unicode Input Handling in Games
I have a game that requires me to allow players to chat with each other via network. All is well, except the part where players can type in Unicode input. So, the question can be split into two parts: When players type, how do I capture input? I have done this before via the game input handling (polling), however, it is not as responsive as something like Windows Forms. After I capture input into a string, how do I output it using TrueType Fonts? The reason I ask this is because usually, I would build bitmap fonts at the start of the game from the all the text used in the game. But with unicode input, there are nearly 10k characters that are needed, which is quite impossible to build at the start of the game. P.S. My target input languages are more specific to Chinese, Korean and Japanese.
For Input Use SDL_EnableUNICODE to enable unicode input handling Receive the SDL_KeyboardEvent as usual Use the unicode member of SDL_keysym to get the unicode For Rendering If the needed font size is reasonably small, say 16px, you actually could just render it all to a single texture, you can fit a minimum of 4096 glyphs on 1024x1024 texture at that size, a bit more when you pack them tightly (see fontgen for example code). That should be enough for common chat, but not enough to fit all the glyphs of a TTF file. If you don't want to use a larger texture size you have to generate the fonts on demand, to do that just create the Texture's as usual and then use glTexSubImage2D to upload new glyphs to the texture. Another alternative is to not use textures for glyphs, but for the text itself. That way you bypass all the trouble that glyph generation produces. But its probably not such a good idea for non-static editable text.
1,403,410
1,403,576
How to solve the problem of global access?
I'm building an app, and I need the wisdom of the SO community on a design issue. In my application, there needs to be EXACTLY one instance of the class UiConnectionList, UiReader and UiNotifier. Now, I have figured two ways to do this: Method 1: Each file has a global instance of that class in the header file itself. Method 2: there is a separate globals.h file that contains single global instances of each class. Example code: Method 1 file: uiconnectionlist.h #ifndef UICONNECTIONLIST_H #define UICONNECTIONLIST_H #include <QObject> #include <QList> class UiConnection; class UiConnectionList : public QObject { Q_OBJECT public: UiConnectionList(); void addConnection(UiConnection* conn); void removeConnection(UiConnection* conn); private: QList<UiConnection*> connList; }; namespace Globals { UiConnectionList connectionList; } #endif // UICONNECTIONLIST_H file: uinotifier.h #ifndef UINOTIFIER_H #define UINOTIFIER_H class UiNotifier { public: UiNotifier(); }; namespace Globals { UiNotifier uiNotifier; } #endif // UINOTIFIER_H Method 2: file: uiconnectionlist.h #ifndef UICONNECTIONLIST_H #define UICONNECTIONLIST_H #include <QObject> #include <QList> class UiConnection; class UiConnectionList : public QObject { Q_OBJECT public: UiConnectionList(); void addConnection(UiConnection* conn); void removeConnection(UiConnection* conn); private: QList<UiConnection*> connList; }; #endif // UICONNECTIONLIST_H file: uinotifier.h #ifndef UINOTIFIER_H #define UINOTIFIER_H class UiNotifier { public: UiNotifier(); }; #endif // UINOTIFIER_H file: globals.h #ifndef GLOBALS_H #define GLOBALS_H #include "uiconnectionlist.h" #include "uinotifier.h" namespace Globals { UiConnectionList connectionList; UiNotifier uiNotifier; } #endif // GLOBALS_H My Question What is the better/right way to do this? PS: I don't think that singleton is the right answer here, is it? Thanks Okay, so two answers have told me to make instances of UiConnectionList and UiNotifier, optionally wrap it in a UiContext and pass it around wherever required. Could someone enumerate reasons (with examples) why passing around the context is better than having globally accessible variables. This will help me judge what method is better (or better suited for my app). Thanks
With your usage in globals.h you are going to have a multiple definition of Globals::UiConnectionList and Globals::UiNotifier for each compilation unit (.cc or .cpp file) that you use. This is not the way to make exactly one instance of those clases. You should use the singleton pattern as previous posters suggested. If you didn't want to use the singleton pattern, the correct way is to define both clases in one compilation unit and then declare them as extern in the header file, the result is your intended one global instance of the class, but that won't prevent it from being copied or copy constructed. From your example you don't know the difference between declaration and definition.
1,403,465
1,403,512
What is boost's shared_ptr(shared_ptr<Y> const & r, T * p) used for?
boost::shared_ptr has an unusual constructor template<class Y> shared_ptr(shared_ptr<Y> const & r, T * p); and I am a little puzzled as to what this would be useful for. Basically it shares ownership with r, but .get() will return p. not r.get()! This means you can do something like this: int main() { boost::shared_ptr<int> x(new int); boost::shared_ptr<int> y(x, new int); std::cout << x.get() << std::endl; std::cout << y.get() << std::endl; std::cout << x.use_count() << std::endl; std::cout << y.use_count() << std::endl; } And you will get this: 0x8c66008 0x8c66030 2 2 Note that the pointers are separate, but they both claim to have a use_count of 2 (since they share ownership of the same object). So, the int owned by x will exist as long as x or y is around. And if I understand the docs correct, the second int never gets destructed. I've confirmed this with the following test program: struct T { T() { std::cout << "T()" << std::endl; } ~T() { std::cout << "~T()" << std::endl; } }; int main() { boost::shared_ptr<T> x(new T); boost::shared_ptr<T> y(x, new T); std::cout << x.get() << std::endl; std::cout << y.get() << std::endl; std::cout << x.use_count() << std::endl; std::cout << y.use_count() << std::endl; } This outputs (as expected): T() T() 0x96c2008 0x96c2030 2 2 ~T() So... what is the usefulness of this unusual construct which shares ownership of one pointer, but acts like another pointer (which it does not own) when used.
It is useful when you want to share a class member and an instance of the class is already a shared_ptr, like the following: struct A { int *B; // managed inside A }; shared_ptr<A> a( new A ); shared_ptr<int> b( a, a->B ); they share the use count and stuff. It is optimization for memory usage.
1,403,501
1,403,546
STL map onto itself?
I'd like to create a std::map that contains a std::vector of iterators into itself, to implement a simple adjacency list-based graph structure. However, the type declaration has me stumped: it would seem you need the entire map type definition to get the iterator type of said map, like so: map< int, Something >::iterator MyMap_it; // what should Something be? map< int, vector<MyMap_it> > MyMap_t; Is there some sort of partial map iterator type I can get with just the key type, so I can declare the full map?
You could use forward declaration of a new type. class MapItContainers; typedef map<int, MapItContainers>::iterator MyMap_it; class MapItContainers { public: vector<MyMap_it> vec; }; With this indirection the compiler should let you get away with it. It is not so very pretty but honestly I don't think you can break the self referencing easily.
1,403,517
1,403,545
C++ Stack Implementation
Hey all! Having a little trouble with my stack. Im trying to print each element that I've pushed onto the stack. Starting with the stack ctor we know that we have a fixed size for the array. So I allocate the items struct object to hold just that much space: stack::stack(int capacity) { items = new item[capacity]; if ( items == NULL ) { throw "Cannot Allocoate Sufficient Memmory"; exit(1); } maxSize = capacity; top = -1; } Yes, items is a struct type of the object "item". Have a look: class stack { stack(int capacity); ~stack(void); ... private: int maxSize; // is for the item stack int top; // is the top of the stack struct item { int n; }; item *items; public: friend ostream& operator<<(ostream& out, stack& q) ... First and formost we want to add to the stack by pushing each incoming element into the array FILO: bool stack::pushFront( const int n ) { if ( top >= maxSize-1 ) { throw "Stack Full On Push"; return false; } else { ++top; items[top].n = n; } return true; } // just a textbook example here: stack::~stack(void) { delete [] items; items = NULL; maxSize = 0; top = -1; } Yes the real issue for me is the items[++top].n = n; statement. I've been trying to find out how I can drag (+) the items array out to see ALL of the array elements after I push onto the stack. Im wondering why I cant drag that items[++top].n = n statement out when im debugging. All that comes up is the value that is passed as an 'n' paramater. Do I need to use a stack object type array to store the values into? When I overload the << operator and try to print the elements I get an insanely large negative number: ostream& operator<<(ostream& out, stack& q) { if ( q.top <= 0 ) // bad check for empty or full node out << endl << "stack: empty" << endl << endl; else for ( int x = 0; x < q.maxSize; x++ ) { out << q.items[x].n; // try to print elements } return out; } I'm way off and I need some guidence if anyone has the time!
In the overloaded << operator in the for loop you are iterating maxsize times. But you might not have pushed maxsize elements into the stack. You should iterate top times. Also, write a default constructor for item structure and initialize all the variblaes so that you do not get garbage values when you try to print them.
1,403,873
1,403,908
Rundll32 load order problem
My product consists of two dlls (A.dll and B.dll for clarity), A.dll depends on B.dll. Both A and B dlls are in the same folder (say c:\app). At the same time old version of B.dll is in Windows\System32 folder. When I try to run following command from command prompt (current folder is c:\app): rundll32.exe "c:\app\A.dll",DoWork I receive error because rundll32 uses old version of B.dll from System32 folder. I tried to use SetDllDirectory API from DllMain function of A.dll library to add c:\app folder to the search path but it doesn't work for me. I can't find any useful and complete information about rundll32 internals or any information about dll loading order. Is it possible to execute rundll32 successfuly in this deployment configuration? (I mean load new B.dll version from c:\app folder).
DLL Hell on SO Well, it's kind of cool in a retro sort of way. Here is a thought: try copying rundll32.exe into the same folder as the new dll's and your product, and run it from there. It might work...
1,404,189
1,405,412
How to read/redirect output of a dos command to a program variable in C/C++?
I want to run a dos command from my program for example "dir" command. I am doing it like, system("dir"); Is there any way to read the output of that command directly into a program variable? We can always redirect the output to a file and then read that file, by doing system("dir > command.out"); And then reading command.out file. But how can we do it directly rather than redirectling to a file and then reading?
Found an alternate way or rather windows equivalent of popen. It is _popen(). This works just right for me and moreover it's easy to use. char psBuffer[128]; FILE *pPipe; if( (pPipe = _popen( "dir", "rt" )) != NULL) { while(fgets(psBuffer, 128, pPipe)) { printf(psBuffer); } } Find the details with full example here.
1,404,305
1,404,333
C++ reference in constructor
I have a class whose constructor takes a const reference to a string. This string acts as the name of the object and therefore is needed throughout the lifetime of an instance of the class. Now imagine how one could use this class: class myclass { public: myclass(const std::string& _name) : name(_name) {} private: std::string name; }; myclass* proc() { std::string str("hello"); myclass* instance = new myclass(str); //... return instance; } int main() { myclass* inst = proc(); //... delete inst; return 0; } As the string in proc() is created on the stack and therefore is deleted when proc() finishes, what happens with my reference to it inside the class instance? My guess is that it becomes invalid. Would I be better off to keep a copy inside the class? I just want to avoid any unneccessary copying of potentially big objects like a string...
Yes, Reference becomes invalid in your case. Since you are using the string it is better to keep a copy of the string object in myclass class.
1,404,394
1,404,473
g++ external reference error
I have issue that is reproduced on g++. VC++ doesn't meet any problems. So I have 2 cpp files: 1.cpp: #include <string> #include <iostream> extern const std::string QWERTY; int main() { std::cout << QWERTY.c_str() << std::endl; } 2.cpp: #include <string> const std::string QWERTY("qwerty"); No magic, I just want place string constants into separated file. At link time ld produces an error: "undefined reference to `_QWERTY'" The first think to wrap both declarations into "extern "C"" - didn't help. Error and non c++ _QWERTY is still there. Thanks in advance for any suggestions
It looks like you are probably running into this bit of the standard: In C, a const-qualified object at file scope without an explicit storage class specifier has external linkage. In C++, it has internal linkage. Make this change to 2.cpp: #include <string> extern const std::string QWERTY("qwerty"); There is some more detail on what "linkage" means in this question - What is external linkage and internal linkage in C++.
1,404,638
1,404,710
During which phase of building a binary is activation record defined?
Is it during a pre-processing or compilation stage, say on gcc? Is it different on other compilers?
The stack frame is created at runtime by modifying the stack register of the processor (esp for Intel x86). The compiler only dump specific instructions to reserve space on the stack at each function call. This space is then recovered when the function exits.
1,404,717
1,412,936
Thread safe C++ std::set that supports add, remove and iterators from multple threads
I'm looking for something similar to the CopyOnWriteSet in Java, a set that supports add, remove and some type of iterators from multiple threads.
there isn't one that I know of, the closest is in thread building blocks which has concurrent_unordered_map The STL containers allow concurrent read access from multiple threads as long as you don't aren't doing concurrent modification. Often it isn't necessary to iterate while adding / removing. The guidance about providing a simple wrapper class is sane, I would start with something like the code snippet below protecting the methods that you really need concurrent access to and then providing 'unsafe' access to the base std::set so folks can opt into the other methods that aren't safe. If necessary you can protect access as well to acquiring iterators and putting them back, but this is tricky (still less so than writing your own lock free set or your own fully synchronized set). I work on the parallel pattern library so I'm using critical_section from VS2010 beta boost::mutex works great too and the RAII pattern of using a lock_guard is almost necessary regardless of how you choose to do this: template <class T> class synchronized_set { //boost::mutex is good here too critical_section cs; public: typedef set<T> std_set_type; set<T> unsafe_set; bool try_insert(...) { //boost has a lock_guard lock_guard<critical_section> guard(cs); } };
1,404,797
1,404,843
In C++, is a function automatically virtual if it overrides a virtual function?
I would expect that if foo is declared in class D, but not marked virtual, then the following code would call the implementation of foo in D (regardless of the dynamic type of d). D& d = ...; d.foo(); However, in the following program, that is not the case. Can anyone explain this? Is a method automatically virtual if it overrides a virtual function? #include <iostream> using namespace std; class C { public: virtual void foo() { cout << "C" << endl; } }; class D : public C { public: void foo() { cout << "D" << endl; } }; class E : public D { public: void foo() { cout << "E" << endl; } }; int main(int argc, char **argv) { E& e = *new E; D& d = *static_cast<D*>(&e); d.foo(); return 0; } The output of the above program is: E
Standard 10.3.2 (class.virtual) says: If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides* [Footnote: A function with the same name but a different parameter list (clause over) as a virtual function is not necessarily virtual and does not override. The use of the virtual specifier in the declaration of an overriding function is legal but redundant (has empty semantics). Access control (clause class.access) is not considered in determining overriding. --- end foonote]
1,404,885
1,405,327
Is mysql_close required on connection failure?
I have a code snippet which connects to a MySQL database like this (not directly from code so there might be typos): m_connectionHandler = mysql_init(NULL); if (m_connectionHandler == NULL) { // MySQL initialization failed return; } MYSQL *tmp = mysql_real_connect(m_connectionHandler, m_hostname, m_username, m_password, m_dbName, m_port, NULL, m_flags); if (tmp == NULL) { // Connect failed mysql_close(m_connectionHandler); return; } My question is if mysql_close (in the second if clause tmp == NULL), in the case when mysql_real_connect returns NULL, is required, or if mysql_real_connect frees the connection handler for me upon failure? The documentation does state that what you get from mysql_init should be freed by mysql_close, but there are indications that it's already freed by mysql_real_connect upon failure. Can anyone shed some light on this for me?
Your call to mysql_init(NULL) allocates memory. Regardless of whether you're able to really connect to the server, you've still allocated memory, so you need to free it with mysql_close, which not only closes connections but also releases memory. I see no indication in the documentation that mysql_real_connect would free the memory itself.
1,404,942
1,404,960
How to optimize the layers of pointer indirection
I am trying to optimize this sort of things in a heavy computing application: say I have a double d[500][500][500][500]; and the following is quite costly at least from compiler perspective double d[x][y][j][k] I want to tell compiler is that it's contiguous memory, to facilitate computing the offset. In my example, I have something like this: double n=0; for (int i=0; i < someNumber; i++) { n+=d[x][i][j][k] /*(some other math calculations)*/; } So I tried to optimize it by putting it in a separate function void func( double*** const restrict dMatrix ) { /* and do some calculations herel*/ } didn't help much :( Any suggestions on optimizing it? } Edit I cannot rewrite the code to make the array one-dimensional. I have to work with this multidimensional beast :(
I suspect that the problem is not the offset calculation but the actual access to memory. When you declare a 4-dimensional array and access elements with adjacent indices at any level except the last one memory addresses are actually quite far from each other and this leads to lots of cache misses and significant slowdown.
1,405,091
1,405,359
Handling relations between multiple subversion projects
In my company we are using one SVN repository to hold our C++ code. The code base is composed from a common part (infrastructure and applications), and client projects (developed as plugins). The repository layout looks like this: Infrastructure App1 App2 App3 project-for-client-1 App1-plugin App2-plugin Configuration project-for-client-2 App1-plugin App2-plugin Configuration A typical release for a client project includes the project data and every project that is used by it (e.g. Infrastructure). The actual layout of each directory is - Infrastructure branches tags trunk project-for-client-2 branches tags trunk And the same goes for the rest of the projects. We have several problems with the layout above: It's hard to start a fresh development environment for a client project, since one has to checkout all of the involved projects (for example: Infrastructure, App1, App2, project-for-client-1). It's hard to tag a release in a client projects, for the same reason as above. In case a client project needs to change some common code (e.g. Infrastructure), we sometimes use a branch. It's hard to keep track which branches are used in projects. Is there any way in SVN to solve any of the above? I thought of using svn:externals in the client projects, but after reading this post I understand it might not be right choice.
You could handle this with svn:externals. This is the url to a spot in an svn repo This lets you pull in parts of a different repository (or the same one). One way to use this is under project-for-client2, you add an svn:externals link to the branch of infrastructure you need, the branch of app1 you need, etc. So when you check out project-for-client2, you get all of the correct pieces. The svn:externals links are versioned along with everything else, so as project-for-client1 get tagged, branched, and updated the correct external branches will always get pulled in.
1,405,132
1,405,214
UNIX/OSX version of semtimedop
GLibC has a method semtimedop which allows you to perform an operation (a semaphore acquire in this case) which times out after a certain amount of time. Win32 also provides WaitForSingleObject which provides similar functionalty. As far as I can see there is no equivalent on OSX or other Unices. Can you suggest either the equivalent for semtimedop or a workaround to terminate a semop after a certain amount of time cleanly.
You can break out of a semop() call (and most other blocking calls) by getting a signal, such as one caused by alarm(). untested example: #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> volatile int alarm_triggered = 0; void alarm_handler(int sig) { alarm_triggered = 1; } int main(int argc, char **argv) { int rc; /* set up signal handler */ signal(SIGALRM, alarm_handler); /* ... */ alarm(30); /* 30 second timeout */ rc = semop(...); if (rc == -1 && errno == EINTR) { if (alarm_triggered) { /* timed out! */ } } alarm(0); /* disable alarm */ /* ... */ }
1,405,205
1,405,285
How could this manner of writing code be called?
I'm reviewing a quite old project and see code like this for the second time already (C++ - like pseudocode): if( conditionA && conditionB ) { actionA(); actionB(); } else { if( conditionA ) { actionA(); } if( conditionB ) { actionB(); } } in this code conditionA evaluates to the same result on both computations and the same goes for conditionB. So the code is equivalent to just: if( conditionA ) { actionA(); } if( conditionB ) { actionB(); } So the former variant is just twice more code for the same effect. How could such manner (I mean the former variant) of writing code be called?
I would call it 'twice is better'. It's made like that to be sure that the runtime really understood the question ;). (although in multi-threaded, not-safe environment, the result may differ between the two variants.)
1,405,502
1,405,605
How to handle NAT traversal in c++ peer to peer application ( please code examples not theory )
I need to develop simple game that will be using peer to peer connection using centralize index manager server. I know there is a problem when a client is trying to connect to another client that is behind a router. I was reading about NAT traversal that explains using mainly theory, but what I would really like to see is code examples with either C++ or Java. Can you help me to understand the meaning of NAT traversal via code? Maybe some kind of open source simple client game ?
NAT traversal is not that simple to get right. STUN might help: http://en.wikipedia.org/wiki/STUN
1,405,766
1,405,816
Can I make make a HALT_ONCE macro?
I'm trying to figure out a transparent solution for debug halts that repeatedly get hit in my game. For a trivial example; say I have a halt in my renderer that tells me when I'm trying to use a NULL material. My renderer handles this fine but I still want to know what I'm doing wrong. This halt will hit every frame now unless I manually disable it. This is the code id like to turn into a macro (or something else thats as transparent as porssible) #define HALT(errorMsg) printf(errorMsg);__asm { int 3 }; satic bool hitOnce = false; if (!hitOnce) { hitOnce = true; HALT("its all gone wrong!") } The idea i had, was to make a macro that created this code, with a unique bool variable each time. The problem Ive hit so far is that I cannot increment numbers to at compile time to generate unique static bools for each HALT_ONCE.
anything wrong with this? #define HALT_ONCE(err_msg) \ do { \ static bool hitOnce = false; \ if (!hitOnce) { \ hitOnce = true; \ printf(err_msg); \ __asm { int 3 }; \ } \ } while(0) Then you can just do this in your code: HALT_ONCE("its all gone wrong!"); The do/while creates its own scope which makes hitOnce only exist for a very short time. I think this will prevent it from conflicting with other hitOnce variables created by this macro.
1,405,911
1,406,049
Initializing and assigning values,from pass by reference
Okay, this is just a minor caveat. I am currently working with the lovely ArcSDK from ESRI. Now to get a value from any of their functions, you basically have to pass the variable, you want to assign the value to. E.g.: long output_width; IRasterProps->get_Width(&output_width); Its such a minor thing, but when you have to pick out around 30 different pieces of data from their miscellaneous functions, it really starts to get annoying. So what i was wondering is it possible to somehow by the magic of STL or C++ change this into: long output_width = IRasterProps->get_Width(<something magical>); All of the functions return void, otherwise the off chance some of them might return a HRESULT, which i can safely ignore. Any ideas? ***EDIT**** Heres the final result i got which works :)!!!!! A magic(P p, R (__stdcall T::*f)(A *)) { A a; ((*p).*f)(&a); return a; }
I know I've already answered, but here's another way. It's better in that it's faster (no boost::function overhead) and avoids the binders (since people seem to have an aversion to them), but is worse in that it's much less general (since it only works for one-argument member functions). template <typename P, typename T, typename A> A magic(P p, void (T::*f)(A &)) { A a; ((*p).*f)(a); return a; } Which you'd call like this: long output_width = magic(raster_props_object, &IRasterProps::get_Width); Or, if you happen to be using GCC, we can use some more tricks: #define MORE_MAGIC(p,f) ({ \ typedef __typeof(*(p)) big_ugly_identifier; \ magic((p),(&big_ugly_identifier::f)); \ }) Which will let us do this: long output_width = MORE_MAGIC(raster_props_object, get_Width); (Bonus points if the naming conventions made you think of a PDP-10.) EDIT: Updated to take any pointer-like type, so it will now work with shared_ptr, iterators, and hopefully _com_ptr. EDIT: Oops, they're pointers, not references. Here's a version (or overload) that deals with that, and allows -- by ignoring -- arbitrarily-typed return values. template <typename P, typename T, typename A, typename R> A magic(P p, R (T::*f)(A *)) { A a; ((*p).*f)(&a); return a; }
1,406,635
1,406,647
parsing proc/pid/cmdline to get function parameters
I'm trying to extract the parameter with which an app was called by using the data inside cmdline. If I start an application instance like this: myapp 1 2 and then cat the cmdline of myapp I will see something like myapp12. I needed to extract these values and I used this piece of code to do it pid_t proc_id = getpid(); sprintf(buf,"/proc/%i/cmdline",proc_id); FILE * pFile; pFile = fopen (buf,"r"); if (pFile!=NULL) { fread(buf,100,100,pFile); cout << "PID " << proc_id << endl; string str = buf; cout << buf << endl; size_t found=str.find_last_of("/\\"); cout << " file: " << str.substr(found+1) << endl; fclose (pFile); } But what I am getting is only the app name and no parameters... Update coppied from answer: well, my question now seems to be how do I read the cmdline file without it stopping at the first NULL character... fopen(cmdline, "rb") doesn't do anything else so...
All of the command line parameters (what would come through as the argv[] array) are actually null-separated strings in /proc/XXX/cmdline. abatkin@penguin:~> hexdump -C /proc/28460/cmdline 00000000 70 65 72 6c 00 2d 65 00 31 20 77 68 69 6c 65 20 |perl.-e.1 while | 00000010 74 72 75 65 00 |true.| This explains why when you cat'ed cmdline they were all "stuck" together (cat ignored the invalid NULL characters) and why your cout stopped after the first command line argument (the process name) since it thought that the process name was a null-terminated string and stopped looking for more characters at that point. Processing Command Line Arguments To process the command line arguments, you have a couple options. If you just want the entire command line as one giant string, loop from the 0 to (numRead - 2) (where numRead is the number of characters read) and replace any NULL bytes (curByte == 0) with spaces. Then just make sure to set the last character to be a NULL byte too (in case things got truncated due to the fixed-size buffer). If you instead want an array with all of the arguments, you need to be more creative. One option would be to loop from 0 to (numRead - 1) and could all of the NULL bytes that you find. Then allocate an array of char*'s of that length. Then loop back through the command line, setting the beginning of every string (i.e. the first byte in the array, plus each byte following a NULL byte) to consecutive elements of the array of char*'s. Just know that since you read to a fixed-size buffer, anything beyond that buffer would be truncated. So remember that whatever you do, you probably need to manually make sure that the end of the last string ends up being NULL terminated, otherwise most string handling functions won't know where the string ends and will keep on going forever.
1,406,643
1,406,664
retval = false && someFunction(); // Does someFunction() get called?
I'm currently working with the Diab 4.4 C++ compiler. It's a total POS, non ANSI-compliant, and I've found problems with it in the past. I'm wondering if the following problem is an issue with the compiler, or a shortcoming in my knowledge of C++ I realize that the form of x = x && y; will short-circuit the y part if x is false. What the compiler is doing is short-circuiting in the case of x = x && y(); where y() is a non-const function. class A { int _a; A(int a) { _a = a; } bool someFunction() { _a = 0; return true; } }; main(...) { A obj = A(1); bool retval = false; retval = retval && A.someFunction(); /* What is the value of A._a here? */ } What seems wrong to me is the fact that the compiler is doing this short-circuiting even though someFunction() is not a const function. If it's not const, is the compiler overstepping its bounds by skipping A.someFunction() when retval is false? Also, I realize this issue can be avoided by writing retval = A.someFunction() && retval; but I'd really like to know why this is happening.
The && and || operators are defined to evaluate lazily, this is the way the language works. If you want the side effects to always happen, invoke the function first and stash the result, or refactor the function to split the work from the state query.
1,406,649
1,406,703
Wanted: Elegant solution to race condition
I have the following code: class TimeOutException {}; template <typename T> class MultiThreadedBuffer { public: MultiThreadedBuffer() { InitializeCriticalSection(&m_csBuffer); m_evtDataAvail = CreateEvent(NULL, TRUE, FALSE, NULL); } ~MultiThreadedBuffer() { CloseHandle(m_evtDataAvail); DeleteCriticalSection(&m_csBuffer); } void LockBuffer() { EnterCriticalSection(&m_csBuffer); } void UnlockBuffer() { LeaveCriticalSection(&m_csBuffer); } void Add(T val) { LockBuffer(); m_buffer.push_back(val); SetEvent(m_evtDataAvail); UnlockBuffer(); } T Get(DWORD timeout) { T val; if (WaitForSingleObject(m_evtDataAvail, timeout) == WAIT_OBJECT_0) { LockBuffer(); if (!m_buffer.empty()) { val = m_buffer.front(); m_buffer.pop_front(); } if (m_buffer.empty()) { ResetEvent(m_evtDataAvail); } UnlockBuffer(); } else { throw TimeOutException(); } return val; } bool IsDataAvail() { return (WaitForSingleObject(m_evtDataAvail, 0) == WAIT_OBJECT_0); } std::list<T> m_buffer; CRITICAL_SECTION m_csBuffer; HANDLE m_evtDataAvail; }; Unit testing shows that this code works fine when used on a single thread as long as T's default constructor and copy/assignment operators don't throw. Since I'm writting T, that is acceptable. My problem is the Get method. If there is no data available (i.e. m_evtDataAvail is not set), then a couple of threads can block on the WaitForSingleObject call. When new data becomes available, they all fall through to the Lock() call. Only one will pass and can get the data out and move on. After the Unlock() another thread can move on through and will find that there is no data. Currently it will return the default object. What I want to happen is for that second thread (and others) to go back to the WaitForSingleObject call. I could add an else block that unlocked and did a goto but that just feels evil. That solution also adds the possibility for an endless loop since each trip back would restart the timeout. I could add some code to check the clock on entry and adjust the timeout on each trip back but then this simple Get method starts to get very complicated. Any ideas on how to solve these problems while maintaining testability and simplicity? Oh, for anyone wondering, the IsDataAvail function only exists for testing. It won't be used in production code. The Add and Get are the only methods that will be used in a non-testing environment.
You need to create a auto-reset event instead of a manual reset event. This guarantees that if multiple threads are waiting on an event, and when the event is set only one thread will be released. All other threads will remain in waiting state. You can create auto-reset event by passing FALSE to the second parameter of CreateEvent API. Also, note that this code is not exception safe i.e. after locking the buffer, if some statement throws an exception your critical section will not be unlocked. Use RAII principle to ensure that your critical section gets unlocked even in the case of exceptions.
1,406,941
1,406,950
Question about "using" keyword
I'm well aware of using namespaces however, every now and then I'm stumbling upon a using, which uses a specific class. For instance : #include <string> using namespace std; (...) However - every now and then, I'm seeing : using std::string; How should I interpret the "using" in this case ? Cheers
using std::string simply imports std::string into the current scope (aka, you can just use 'string' rather than 'std::string') without importing everything from ::std into the current scope. edit: clarification after comment.
1,406,995
1,407,225
Using STL/Boost to find and modify matching elements in a vector
Let's say I have a vector declared like this: struct MYSTRUCT { float a; float b; }; std::vector<MYSTRUCT> v; Now, I want to find all elements of v that share the same a, and average their b, i.e. Say v contains these five elements {a, b}: {1, 1}, {1, 2}, {2, 1}, {1, 3}, {2, 2} I want to get v[0], v[1], v[3] (where a is 1) and average b: (1 + 2 + 3)/3 = 2, and v[2] and v[4] (where a is 2) and average b: (1+2)/2 = 1.5 Afterwards v will look like this: {1, 2}, {1, 2}, {2, 1.5}, {1, 2}, {2, 1.5} I'm not really familiar with STL or Boost so I can only figure out how to do this the "bruteforce" way in C++, but I'm guessing that the STL (for_each?) and Boost (lambda?) libraries can solve this more elegantly. EDIT Just for reference, here's my (working) brute force way to do it: for(int j = 0; j < tempV.size(); j++) { MYSTRUCT v = tempV.at(j); int matchesFound = 0; for(int k = 0; k < tempV.size(); k++) { if(k != j && v.a == tempV.at(k).a) { v.b += tempV.at(k).b; matchesFound++; } } if(matchesFound > 0) { v.b = v.b/matchesFound; } finalV.push_back(v); }
Just thinking aloud, this may end up fairly silly: struct Average { Average() : total(0), count(0) {} operator float() const { return total / count; } Average &operator+=(float f) { total += f; ++count; } float total; int count; }; struct Counter { Counter (std::map<int, Average> &m) : averages(&m) {} Counter operator+(const MYSTRUCT &s) { (*averages)[s.a] += s.b; return *this; } std::map<int, Average> *averages; }; std::map<int, Average> averages; std::accumulate(v.begin(), v.end(), Counter(averages)); BOOST_FOREACH(MYSTRUCT &s, v) { s.b = averages[s.a]; } Hmm. Not completely silly, but perhaps not compelling either...
1,407,023
1,407,077
Progress indication with HTTP file download using WinHTTP
I want to implement an progress bar in my C++ windows application when downloading a file using WinHTTP. Any idea how to do this? It looks as though the WinHttpSetStatusCallback is what I want to use, but I don't see what notification to look for... or how to get the "percent downloaded"... Help! Thanks!
Per the docs: WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE Data is available to be retrieved with WinHttpReadData. The lpvStatusInformation parameter points to a DWORD that contains the number of bytes of data available. The dwStatusInformationLength parameter itself is 4 (the size of a DWORD). and WINHTTP_CALLBACK_STATUS_READ_COMPLETE Data was successfully read from the server. The lpvStatusInformation parameter contains a pointer to the buffer specified in the call to WinHttpReadData. The dwStatusInformationLength parameter contains the number of bytes read. There may be other relevant notifications, but these two seem to be the key ones. Getting "percent" is not necessarily trivial because you may not know how much data you're getting (not all downloads have content-length set...); you can get the headers with: WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE The response header has been received and is available with WinHttpQueryHeaders. The lpvStatusInformation parameter is NULL. and if Content-Length IS available then the percentage can be computed by keeping track of the total number of bytes at each "data available" notification, otherwise your guess is as good as mine;-).
1,407,081
1,408,503
Converting a C# class library to C++ on Red Hat Linux
We have developed a C# class library on VS 2008. We want the same functionality as a C++ library on Red Hat Linux. How do we accomplish that? I am sure we are not the first to migrate C# to C++. Are there any automated tools to convert the source code? We know about Mono, but we would very much prefer C++ source code. About 15% is the useful code, the rest 85% are unit tests using NUnit. At the very least we do want to migrate all the unit tests as source code. We used Reflector, which did almost all the work for us. The only thing it screwed up were constructors. Consider the following C# code: public MyClass() : this(1,2,3){} it should be converted to public MyClass() : {this(1,2,3);} but Reflector converted it to public MyClass() : {MyClass(1,2,3);}
You can get a head start by first converting to C++/CLI (the .NET flavor of C++). Red Gate's .NET Reflector supports conversions between .NET languages (you need a plugin to decompile to C++/CLI) and there are other tools as well.
1,407,197
1,407,206
Using binary flags to represent states, options, etc
If I wanted to represent states or options or something similar using binary "flags" so that I could pass them and store them to an object like OPTION1 | OPTION2 where OPTION1 is 0001 and OPTION2 is 0010, so that what gets passed is 0011, representing a mix of the options. How would I do this in C++? I was thinking something like enum Option { Option_1 = 0x01, Option_2 = 0x02, Option_3 = 0x04, //... } void doSomething(Option options) { //... } int main() { doSomething(Option_1|Option_2); } But then ideally, doSomething knows how to interpret the given Option. Am I on the right track? Is there a better way? Update And wouldn't I have to define an Option for every possible combination, also?
This is a common way these things are done. doSomething can use bitwise and operator to see if an option is selected: if (options & Option_1){ // option 1 is selected } Alternatively, you can consider using bit fields: struct Options { unsigned char Option_1 : 1; unsigned char Option_2 : 1; }; Options o; o.Option_1 = 1; o.Option_2 = 0;
1,407,354
1,949,894
Is there a C++ unit testing library that is similar to NUnit?
We need to migrate a unit test harness developed with C# and NUnit to C++ running on Red Hat Linux. We want to minimize the efforts in migration. We are reading resources such as this: http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle But we don't see anything similar to NUnit.
Expanding on Mark Bessey's answer: I really like cxxTest because it's just a set of C++ header files & Perl scripts. As long as you have a C++ compiler & Perl, it will work on nearly any system. It also has features to integrate with your IDE (although I haven't used them). Also, here's a good article Exploring the C++ Unit Testing Framework Jungle. This post is potentially out of date (circa 2004), but gives a great summary of features & straight-up examples utilizing each of the following C++ unit testing frameworks: CppUnit Boost.Test CppUnitLite NanoCppUnit Unit++ CxxTest
1,407,996
1,408,110
Send a key to another Windows application with C++
I'm sort of new to c++. I'm trying to send a key to another application, which I know the HWND of. I was thinking of doing ::SendMessage but I'm not sure what parameters to use. I'm trying to send the space key. Thanks.
SendInput might be what you want.
1,408,056
1,408,077
Should I write one method to convert distances or a bunch of methods?
I'm just learning C++ and programming. I'm creating a class called Distance. I want to allow the user (programmer using), my class the ability to convert distances from one unit of measure to another. For example: inches -> centimeters, miles -> kilometers, etc... My problem is that I want to have one method called ConvertTo that will convert to any unit of measure. Here's what I have so far: // unit_of_measure is an enum containg all my supported lengths, // (eg. inches, centimeters, etc...) int Distance::ConvertTo(unit_of_measure convert_unit) { switch (convert_unit) { case inches: if (unit != inches) { if (unit == centimeters) { distance *= CM_TO_IN; unit = inches; return 0; } else { cerr << "Conversion not possible (yet)." << endl; return 1; } } else { cout << "Warning: Trying to convert inches to inches." << endl; return 2; } case centimeters: if (unit != centimeters) { if (unit == inches) { distance /= CM_TO_IN; unit = centimeters; return 0; } else { cerr << "Conversion not possible (yet)." << endl; return 1; } } else { cout << "Warning: Trying to convert inches to inches." << endl; return 2; } // I haven't written anything past here yet because it seems // like a bad idea to keep going with this huge switch // statement. default: cerr << "Undefined conversion unit." << endl; return -1; } } So what do I do? Should I break this up or just continue on with what will become a HUGE switch statement.
Break it up into functions. What you have there is going to be very difficult to maintain and to use. It would be more convenient to the user and the programmer to have functions with descriptive names like: double inchesToCentimeters(double inches); double centimetersToInches(double cent); The function names tell you exactly what function to call, and there's no need to pass in the extra parameter that keeps track of the units. Just as an aside, in order to prevent having to keep track of what units a measurement is in, it's a good practice to always store you numbers in a common unit everywhere in your program, then convert to the display units only when you need to. For example, a program I'm maintaining now keeps all distance values in meters, but can convert to just about any distance unit you could think of. When you use a common unit, you save yourself a lot of function writing. Say your common distance unit is meters, now once you write the functions converting from meters to every other unit you need, and from all the other units to meters, you can combine these to go from any unit - to meters - to any other unit.
1,408,361
1,408,370
Unsigned Integer to BCD conversion?
I know you can use this table to convert decimal to BCD: 0 0000 1 0001 2 0010 3 0011 4 0100 5 0101 6 0110 7 0111 8 1000 9 1001 Is there a equation for this conversion or you have to just use the table? Im trying to write some code for this conversion but Im not sure how to do the math for it. Suggestions?
You know the Binary numeral system, don't you? Especially have a look at this chapter. EDIT: Also note KFro's comment that the lower nibble (= 4 bits) of the binary ASCII representation of numerals is in BCD. This makes conversions BCD <-> ASCII very easy as you just have to add/remove the leading 4 bits: Number ASCII Code 0 0011 0000 1 0011 0001 ... 8 0011 1000 9 0011 1001
1,408,513
1,408,540
"LNK1104: cannot open file 'X'": How to find out who wants X linked in?
Okay, I'm stumped. I'm fiddling with some project settings, trying to start linking against library Y instead of library X. When I search through the project file (.vcproj) and all the inherited property sheets (.vsprops), there are no references left to library X. I've closed and reopened Visual Studio to make sure it's not holding onto some old version of the project. However, as suggested by the title, I still get the link error LINK : fatal error LNK1104: cannot open file 'X' When I come across this sort of problem with header files (not knowing what file is including that header), I usually rename the problem header to cause a C1083: Cannot open include file error, which tells me what source file is requesting it. But here the LNK1104 is not nearly as useful. Does anyone have any ideas on how I can track this down? Thanks.
Under project settings / linker / general there's a setting called "show progress", if you set it to "/VERBOSE" the linker will show you all kinds of stuff including the "/DEFAULTLIB" items it finds. This can be helpful, depending on whether the import is coming from a lib file, or not. You should also search your solution source code for a "#pragma comment(lib,...", which causes a default library to be included at link-time. If library X is something like msvcrt, then the dependency is likely coming from an external or third-party library that you're using, and the only practical way to avoid this is to add X to the "ignore specific library" option under project settings / linker / input.
1,408,600
1,408,608
delete [] char *, memory issues
I have a global pointer variable char* pointer = new char[500]; /* some operations... */ there is a seperate FreeGlobal() function that does free up the pointer as below: delete[] pointer; First time when the function is called, it actually frees up the memory and now the pointer is a bad pointer. But when we call this more than once, it throws an exception. Is there a way to check the pointer variable before calling delete [] again? What are the work arounds? Is this a bad practice? Thank you.
Set pointer to null after you delete it. You should not try to delete the same data more than once. As mentioned by GRB in the comments for this post, it is perfectly safe to call delete[] NULL.
1,408,651
1,408,892
Is optimizing certain functions with Assembler in a C/C++ program really worth it?
In certain areas of development such as game development, real time systems, etc., it is important to have a fast and optimized program. On the other side, modern compilers do a lot of optimization already and optimizing in Assembly can be time consuming in a world where deadlines are a factor to take into consideration. Questions: Is optimizing certain functions with Assembly in a C/C++ program really worth it? Is there really a sufficient gain in performance when optimizing a C/C++ program with Assembly with today's modern compilers? What I understand with the answers posted, any gain that can be made is important in certain areas such as embedded systems, multimedia programming (graphics, sound, etc.). Also, one needs to be capable (or have someone capable) of doing a better job in Assembly than a modern compiler. Doing some really optimized C/C++ can take less time and can do a good enough job. One last thing, learning Assembly can help understand the inner mechanics of a program and make someone a better programmer in the end.
I'd say it's not worth it. I work on software that does real-time 3D rendering (i.e., rendering without assistance from a GPU). I do make extensive use of SSE compiler intrinsics -- lots of ugly code filled with __mm_add_ps() and friends -- but I haven't needed to recode a function in assembly in a very long time. My experience is that good modern optimizing compilers are pretty darn effective at intricate, micro-level optimizations. They'll do sophisticated loop transformations such as reordering, unrolling, pipelining, blocking, tiling, jamming, fission, and the like. They'll schedule instructions to keep the pipeline filled, vectorize simple loops, and deploy some interesting bit twiddling hacks. Modern compilers are incredibly fascinating beasts. Can you beat them? Well, sure, given that they choose the optimizations to use by heuristics, they're bound to get it wrong sometimes. But I've found it's much better to optimize the code itself by looking at the bigger picture. Am I laying out my data structures in the most cache friendly way? Am I doing something unorthodox that misleads the compiler? Can I rewrite something a bit to give the compiler better hints? Am I better off recomputing something instead of storing it? Could inserting a prefetch help? Have I got false cache sharing somewhere? Are there small code optimization that the compiler thinks unsafe but is okay here (e.g., converting division to multiplication by the reciprocal)? I like to work with the compiler instead of against it. Let it take care of the micro-level optimizations, so that you can focus on the mezzo-level optimizations. The important thing is to have a good idea how your compiler works so that you know where the boundaries between the two levels are.
1,408,695
1,408,915
B+ tree implementation, * * vs *
I am writing a B+ tree for a variety of reasons and I am come here to ask a question about implementation of its nodes. My nodes currently look like: struct BPlusNode { public: //holds the list of keys keyType **keys; //stores the number of slots used size_t size; //holds the array of pointers to lower nodes NULL if this is a leaf node BPlusNode **children; //holds the pointer to the next load to the 'left' BPlusNode *next; //Data page pointers NULL if this is a branch node Bucket **pages; }; As you can see my current implementation is using * * in the place where I am wondering whether I should use * * or *. I am well aware of the fact that * * requires two dereference operations and thus is a slower than simply using *, however this class uses a great deal of recursion and it is far more convienient to pass pointers to sub calls of recursive functions. To do this with * I would need to do pointer arithmetic and pass the resulting pointer. With ** someFunction(BPlusNode* currNode) { ...... someFunction(currNode->children[ChildIndex]); } with * someFunction(BPlusNode* currNode) { ...... someFunction((currNode->children) + ChildIndex); } I can see that there is an additional read of memory to produce the pointer desired in the * * version, but the * * version is also easier to think about for me (it conforms more closely to how I see the diagrams drawn in "The Art of Computer Programming" and on wikipedia). Does anyone have any thoughts one way or the other? Suggestions for a third option? Proof of why one is superior to the other? etc? Edit: I might post this as an answer below but I just realized that with the * * scheme I do not need to copy the entire contents of each subnode or bucket should I want to insert one into the middle of the array (ie resize the array). If there are 20 subnodes for the * scheme when I reallocate the array I would need to copy 20*sizeof(BPlusNode) bytes, as opposed to 20*sizeof(BPlusNode*) bytes for the * * scheme. On the other hand it has occurred to me that since I perform all the inserts and page splits are done up front maybe this increased efficiency in performing them is unnecessary, and the benefits of * over * * in searches outweighs it.
I would define another struct for the key and pointer data. I would commit to using fixed size nodes which should match your on-disk structure. This makes memory mapping the tree a lot easier. Your BPlusNode struct becomes a handle class that points to these mapped data nodes and synthesizes the things like prev and next pointers by reading the siblings as it descends the tree. It could look something like the following: enum BPlusNodeType { LEAF, BRANCH }; struct BPlusNodeData { static const size_t max_size = 511; // Try to fit into 4K? 8K? uint16_t size; uint16_t type; keyType key[max_size]; union { Bucket* data[max_size]; BPlusNodeData* children[max_size]; }; };
1,408,823
1,408,834
int and string parsing
If i have a int say 306. What is the best way to separate the numbers 3 0 6, so I can use them individually? I was thinking converting the int to a string then parsing it? int num; stringstream new_num; new_num << num; Im not sure how to do parse the string though. Suggestions?
Without using strings, you can work backwards. To get the 6, It's simply 306 % 10 Then divide by 10 Go back to 1 to get the next digit. This will print each digit backwards: while (num > 0) { cout << (num % 10) << endl; num /= 10; }
1,408,866
1,408,946
C++ dynamically allocated array of statically dimensioned arrays
I need to create a structure that holds a variable number of 'char[2]'s, i.e. static arrays of 2 chars. My question is, how do I allocate memory for x number of char[2]. I tried this (assuming int x is defined): char** m = NULL; m = new char[x][2]; ... delete [] m; (it didn't work) I realise I could use std::vector<char[2]> as a container, but I'm curious as to how it would be done with raw pointers. I am very new to C++ and trying to learn.
In your code, the type of 'm' doesn't match your 'new' call. What you want is: char (*m)[2] = NULL; m = new char[x][2]; ... delete [] m; m is a pointer to arrays of 2 chars, and you call new to get an array of x arrays of 2 chars and point m at the first one.
1,408,908
1,408,916
Looking for a free source code analyzer (Function depedency tree)
Does anybody know where I can find a utility/application running on Windows that analyses C source and outputs a functional dependency tree? What I'm looking for is something along these lines: PrintString->PrintCharacter->PrintByte->Printf
It's almost certainly overkill, but you can do this for C, C++, PHP, Java, C#, and more with Doxygen (if you have Graphviz dot installed). Here's a page with a sample call tree generated by Doxygen/dot. Doxygen runs on Windows fine, and can output HTML and a few other formats.
1,409,006
1,413,714
State Machine Implementation
I'm looking for some general Optimization Correctness Extensibility advice on my current C++ Hierarchical State Machine implementation. Sample variable isMicOn = false variable areSpeakersOn = false variable stream = false state recording { //override block for state recording isMicOn = true //here, only isMicOn is true //end override block for state recording } state playback { //override block for state playback areSpeakersOn = true //here, only areSpeakersOn = true //end override block for state playback state alsoStreamToRemoteIp { //override block for state alsoStreamToRemoteIp stream = true //here, both areSpeakersOn = true and stream = true //end override block for state alsoStreamToRemoteIp } } goToState(recording) goToState(playback) goToState(playback.alsoStreamToRemoteIp) Implementation Currently, the HSM is implemented as a tree structure where each state can have a variable number of states as children. Each state contains a variable number of "override" blocks (in a std::map) that override base values. At the root state, the state machine has a set of variables (functions, properties...) initialized to some default values. Each time we enter a child state, a list of "overrides" define variable and values that should replace the variables and values of the same name in the parent state. Updated original for clarity. Referencing variables At runtime, the current states are stored on a stack. Every time a variable is referenced, a downwards stack walk is performed looking for the highest override, or in the case of no overrides, the default value. Switching states Each time a single state frame is switched to, the state is pushed onto a stack. Each time a state is switched to, I trace a tree descension that takes me from the current state to the root state. Then I do a tree descension from the target state to the root state until I see the current trace matches the previous trace. I declare an intersection at where those 2 traces meet. Then, to switch to the target state, I descend from the source, popping state frames from the stack until I reach the intersection point. Then I ascend to the target node and push state frames onto the stack. So for the code sample above Execution trace for state switch Source state = recording Target State = alsoStreamToRemoteIp descension from source = recording->root (trace = [root]) descension from target = alsoStreamToRemoteIp->playback->root (trace = [playback, root]) Intersects at root. To switch from recording to alsoStreamToRemoteIp, Pop "recording" from the stack (and call its exit function... not defined here). Push "playback" onto the stack (and call the enter function). Push "alsoStreamToRemoteIp" onto the stack (and call the the enter function).
Two things: 1: For most cases just represent the state of your program as a Model, and interact with it directly or through the MVC pattern. 2: If you really need a FSM, i.e. you want to randomly make a bunch of actions to your model, only some of which are allowed at certain times. Then.... Still keep the state of your program in a Model (or multiple Models depending on decomposition and complexity) and represent states and transitions like. class State: def __init__(self): self.neighbors = {} Where neighbors contains a dictionary of of {Action: State}, so that you can do something like someAction.execute() # Actions manipulate the model (use classes or lambdas) currentState = currentState.neighbors[someAction] Or even cooler, have an infinite loop randomly selecting an action from the neighbors, executing it, and moving state indefinitely. It's a great way to test your program.
1,409,305
1,409,319
Best Practices: Should I create a typedef for byte in C or C++?
Do you prefer to see something like t_byte* (with typedef unsigned char t_byte) or unsigned char* in code? I'm leaning towards t_byte in my own libraries, but have never worked on a large project where this approach was taken, and am wondering about pitfalls.
If you're using C99 or newer, you should use stdint.h for this. uint8_t, in this case. C++ didn't get this header until C++11, calling it cstdint. Old versions of Visual C++ didn't let you use C99's stdint.h in C++ code, but pretty much every other C++98 compiler did, so you may have that option even when using old compilers. As with so many other things, Boost papers over this difference in boost/integer.hpp, providing things like uint8_t if your compiler's standard C++ library doesn't.
1,409,395
1,409,406
Creating Property grid in MFC
I want to create a property grid (the one which is similar to the one used in the resource editor in VS) using MFC. Does anybody whether there is any built in support in MFC for this?
You need VS2008 and the feature pack, it's called CMFCPropertyGridCtrl
1,409,454
1,409,465
c++ map find() to possibly insert(): how to optimize operations?
I'm using the STL map data structure, and at the moment my code first invokes find(): if the key was not previously in the map, it calls insert() it, otherwise it does nothing. map<Foo*, string>::iterator it; it = my_map.find(foo_obj); // 1st lookup if(it == my_map.end()){ my_map[foo_obj] = "some value"; // 2nd lookup }else{ // ok do nothing. } I was wondering if there is a better way than this, because as far as I can tell, in this case when I want to insert a key that is not present yet, I perform 2 lookups in the map data structures: one for find(), one in the insert() (which corresponds to the operator[] ). Thanks in advance for any suggestion.
Normally if you do a find and maybe an insert, then you want to keep (and retrieve) the old value if it already existed. If you just want to overwrite any old value, map[foo_obj]="some value" will do that. Here's how you get the old value, or insert a new one if it didn't exist, with one map lookup: typedef std::map<Foo*,std::string> M; typedef M::iterator I; std::pair<I,bool> const& r=my_map.insert(M::value_type(foo_obj,"some value")); if (r.second) { // value was inserted; now my_map[foo_obj]="some value" } else { // value wasn't inserted because my_map[foo_obj] already existed. // note: the old value is available through r.first->second // and may not be "some value" } // in any case, r.first->second holds the current value of my_map[foo_obj] This is a common enough idiom that you may want to use a helper function: template <class M,class Key> typename M::mapped_type & get_else_update(M &m,Key const& k,typename M::mapped_type const& v) { return m.insert(typename M::value_type(k,v)).first->second; } get_else_update(my_map,foo_obj,"some value"); If you have an expensive computation for v you want to skip if it already exists (e.g. memoization), you can generalize that too: template <class M,class Key,class F> typename M::mapped_type & get_else_compute(M &m,Key const& k,F f) { typedef typename M::mapped_type V; std::pair<typename M::iterator,bool> r=m.insert(typename M::value_type(k,V())); V &v=r.first->second; if (r.second) f(v); return v; } where e.g. struct F { void operator()(std::string &val) const { val=std::string("some value")+" that is expensive to compute"; } }; get_else_compute(my_map,foo_obj,F()); If the mapped type isn't default constructible, then make F provide a default value, or add another argument to get_else_compute.
1,409,562
1,409,943
Assigning Unique Numerical Identifiers to Instances of a Templated Class
Core problem: I want to be able to take an instance of a templated class, say: template<class a, class b, class c> class foo; foo<int, float, double>; and then do something like: foo<int, float, double>::value; //Evaluates to a unique number foo<long, float, double>::value; //Evaluates to a different unique number foo<int, float, double>::value; //Evaulates to the same unique number Except, really, it's: template<class a, class b, class c> int getUniqueIdentifier() { return foo<a, b, c>::value; } Current Solution Attempt: I'm thinking I want to use Boost::MPL's "Extensible Associative Sequence", since each element gets it's own unique identifier, but I think I need to be able to alter the sequence in place, which "insert" doesn't do. I may be barking up the wrong tree. (On the plus side, dayum, but MPL!) Purpose: Reinventing the wheel on a Signals & Sockets system. Components make and register channels with a "switchboard", which would use the unique identifiers to put the channels in a map, allowing run-time versatility. I've tried looking up the Qt library as an example, but I can't parse their abbreviations, and I think I'm missing some formal know-how. Thanks!
If you want to put things in a map, and need a per-type key, the proper solution is to use std::type_info::before(). It may be worthwhile to derive a class so you can provide operator<, alternatively wrap std::type_info::before() in a binary predicate.
1,409,597
1,409,695
Shared Memory Semaphore
I have 10 processes running, each writing to the same file. I don't want multiple writers, so basically I am looking for a mutex/binary semaphore to protect file writes. The problem is I can't share the semaphore amongst 10 processes, so I am looking at using shared memory between 10 processes, and putting the semaphore inside shared memory so it can be accessed by each process. Can anyone point me to documentation on this in C/C++ for Unix? Sample code to use this structure would be great. Thanks
It sounds like you'd be better off using flock(2): flock(fd, LOCK_EX); n = write(fd, buf, count); flock(fd, LOCK_UN);
1,409,701
1,409,710
Pattern for fast copy in C
I once saw a programming pattern (not design), how to implement a fast copy of buffers. It included an interleaved loop and switch. The thing was, it copied 4 bytes most of the time, only the last few bytes of the buffer were copied using smaller datatypes. Can someone tell me the name of it? It's named after a person. It's done in C and the compiler output is nearly optimal.
It sounds like you're thinking of Duff's device.
1,409,729
1,434,353
library for remote desktop
I'm working on porting a windows-only application to Linux, and eventually to Mac OSX. Part of this program is a remote-desktop-like feature - you can share a desktop space with several clients. The network protocol is very similar to the RDP protocol. The original author wrote everything from scratch. It works very well, but large parts of it are windows-specific. Now that I'm porting to multiple platforms, I'd like to avoid having to: Re-write the screen-grabbing & network protocol code code for Linux/X11, and then again for MacOSX. Spend the rest of my natural life bug fixing and tweaking these various implementations. So.. I'm looking for a c++ library that does these bits for me. Ideally I need the library to handle both the server and the client-side work (I.e.- both the screen grabbing and the display code). I've looked at libVNC, which looks good, except it does the server-side only, as far as I can tell (the only documentation I've ever found is the README file). I don't care particularly what the network protocol looks like. It'd be nice if I could modify the library to wrap the protocol in my own network protocol, but that's a nice-to-have feature. Can anyone suggest something?
Pick a cross-platform open-source VNC client you like and co-opt it's input handling code, replacing the VNC bits with your protocol. I'm unaware of any generic library for handling VNC client tasks.
1,409,890
1,409,924
Run-time type information in C++
What is runtime type control in C++?
It enables you to identify the dynamic type of a object at run time. For example: class A { virtual ~A(); }; class B : public A { } void f(A* p) { //b will be non-NULL only if dynamic_cast succeeds B* b = dynamic_cast<B*>(p); if(b) //Type of the object is B { } else //type is A { } } int main() { A a; B b; f(&a); f(&b); }
1,409,920
1,417,827
Calling a function in child thread in Qt?
I have a main thread that invokes a child thread function at different times but I am not sure whether that is right way of doing it in Qt.What is wrong with the below code and looking for better alternative There is a main thread running infinitly when ever main thread releases the lock child does a piece of work. #include <QtCore/QCoreApplication> #include <QSemaphore> #include <QThread> QSemaphore sem(0); class Background : public QThread { protected: void run() { for(;;) { sem.acquire(1); qDebug("Child function ran"); } } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Background child; child.start(); qDebug("Main running"); qDebug("release a lock"); sem.release(1); qDebug("Do somework in main"); //call child sem.release(1); sem.release(1); return a.exec(); }
Edit: rework of entire post to cover basics as well. Background.h: #ifndef BACKGROUND_H #define BACKGROUND_H #include <QThread> #include <QObject> class Background : public QThread { Q_OBJECT public: Background(QObject* parent = 0):QThread(parent){} protected: void run() { qDebug(qPrintable(QString("Child function ran in thread: %1").arg(QThread::currentThreadId()))); } }; class BackgroundConcurrent : public QObject { Q_OBJECT public: BackgroundConcurrent(QObject* parent = 0):QObject(parent){} public slots: void doWork() const { qDebug(qPrintable(QString("Concurrent child function ran in thread: %1").arg(QThread::currentThreadId()))); } }; class BackgroundTrigger : public QObject { Q_OBJECT public: BackgroundTrigger(QObject* parent = 0):QObject(parent){} ~BackgroundTrigger() { foreach(QObject* child, children()) { QThread* childThread = qobject_cast<QThread*>(child); if (childThread) childThread->wait(); } } public slots: void triggerWorker() { Background* child = new Background(this); child->start(); } }; #endif // BACKGROUND_H main.cpp: #include "Background.h" #include <QCoreApplication> #include <QtConcurrentRun> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Using QThread BackgroundTrigger childTrigger; qDebug(qPrintable(QString("Main function ran in thread: %1").arg(QThread::currentThreadId()))); // Call child childTrigger.triggerWorker(); childTrigger.triggerWorker(); // Using QtConcurrent BackgroundConcurrent cchild; QFuture<void> future1 = QtConcurrent::run(&cchild, &BackgroundConcurrent::doWork); QFuture<void> future2 = QtConcurrent::run(&cchild, &BackgroundConcurrent::doWork); return 0; } Sample output: Main function ran in thread: 1087038064 Child function ran in thread: 1091267472 Child function ran in thread: 1093417872 Concurrent child function ran in thread: 1095519120 Concurrent child function ran in thread: 1097644944 Be sure you run moc on your header files, qmake and cmake both support creating your makefiles. Here is the CMakeLists.txt file I used to build the code: cmake_minimum_required(VERSION 2.6) #Project name project(TEST) #Use Qt4 find_package(Qt4) if(QT4_FOUND) set(QT_USE_QTOPENGL TRUE) include(${QT_USE_FILE}) set(LIBS ${QT_LIBRARIES} ) #Source files (*.cpp, *.o) set(TEST_SRCS main.cpp) #Header files (*.h[pp]) set(TEST_HDRS Background.h) #Qt macros to handle uic, moc, etc... QT4_WRAP_CPP(TEST_MOC ${TEST_HDRS} OPTIONS -nw) set(TEST_ALLSRC ${TEST_SRCS} ${TEST_MOC}) #Create main add_executable(test ${TEST_ALLSRC}) target_link_libraries(test ${LIBS}) endif(QT4_FOUND)
1,410,226
1,410,255
Is there any use for C++ throw decoration?
I've started using C++ exceptions in a uniform manner, and now I'd like the compiler (g++) to check that there are no "exception leaks". The throw decoration should do this, like const does for constness of class methods. Well, it doesn't. Using throw is still documentary, but may even be dangerously misleading if others think a function cannot throw other exceptions than those listed in its documentation. Can g++ somehow be persuaded to be more strict on its throw-checking, i.e. really making sure a function decorated as throw() will never-ever throw anything. Edit: Found this question handling the subject widely.
It doesn't check compile-time, but a conforming compiler should ensure it at run-time. If a function throws anything outside of its throw-declaration, the C++ run-time should call std::unexpected, if I recall correctly.
1,410,649
1,410,718
waiting for multiple condition variables in boost?
I'm looking for a way to wait for multiple condition variables. ie. something like: boost::condition_variable cond1; boost::condition_variable cond2; void wait_for_data_to_process() { boost::unique_lock<boost::mutex> lock(mut); wait_any(lock, cond1, cond2); //boost only provides cond1.wait(lock); process_data(); } Is something like this possible with condition variables. And if not are there alternative solutions? Thanks
I don't believe you can do anything like this with boost::thread. Perhaps because POSIX condition variables don't allow this type of construct. Of course, Windows has WaitForMultipleObjects as aJ posted, which could be a solution if you're willing to restrict your code to Windows synchronization primitives. Another option would to use fewer condition variables: just have 1 condition variable that you fire when anything "interesting" happens. Then, any time you want to wait, you run a loop that checks to see if your particular situation of interest has come up, and if not, go back to waiting on the condition variable. You should be waiting on those condition variables in such a loop anyways, as condition variable waits are subject to spurious wakeups (from boost::thread docs, emphasis mine): void wait(boost::unique_lock<boost::mutex>& lock) ... Effects: Atomically call lock.unlock() and blocks the current thread. The thread will unblock when notified by a call to this->notify_one() or this->notify_all(), or spuriously. ...
1,410,706
1,410,744
Why does this generate compiler warning "Signed/Unsigned mismatch" only when compiled under x64?
Consider this code: LARGE_INTEGER l; size_t s; if (s < l.QuadPart) return 1; return 0; When this is compiled under x64 it generates the C4018 signed/unsigned mismatch compiler warning (Ignore the uninitialized local variable warning). The warning is fine, since QuadPart is LONGLONG which is signed and size_t is unsigned. But when I compile this under 32-bit there is no warning? How come? Under 32-bit LONGLONG is still signed and size_t is unsigned.
On 32-bit LONGLONG is equivalent to signed __int64 and size_t is equivalent to unsigned int. unsigned int has range that completely fits into signed __int64 range, so the compiler widens (does integer promotion) size_t to signed __int64 before the comparison and there's no warning. On 64-bit LONGLONG is again equivalent to signed __int64 but size_t is equivalent to unsigned __int64, so now size_t no longer fits into LONGLONG and the compiler can't perform any kind of promotion automatically, hence the warning.
1,411,101
1,411,127
Debugging a 2D array in VS2008
I have a 2D array which contains height information. I want to see it in the debugger to a certain point if the values are correct. I know we can see a 1D array using "myArray,5", but it doesn't work when i write "myArray,5,5" or "myArray[0],5", without the quotation marks. Does anybody know how to do this? Or is this even possible?
As first, you can view memory block contents at specified address (myArray). As second you can mouseover your array, and from pop-up menu show array members.
1,411,110
1,413,165
Access Violation Exception/Crash from C++ callback to C# function
So I have a native 3rd party C++ code base I am working with (.lib and .hpp files) that I used to build a wrapper in C++/CLI for eventual use in C#. I've run into a particular problem when switching from Debug to Release mode, in that I get an Access Violation Exception when a callback's code returns. The code from the original hpp files for callback function format: typedef int (*CallbackFunction) (void *inst, const void *data); Code from the C++/CLI Wrapper for callback function format: (I'll explain why I declared two in a moment) public delegate int ManagedCallbackFunction (IntPtr oInst, const IntPtr oData); public delegate int UnManagedCallbackFunction (void* inst, const void* data); --Quickly, the reason I declared a second "UnManagedCallbackFunction" is that I tried to create an "intermediary" callback in the wrapper, so the chain changed from Native C++ > C# to a version of Native C++ > C++/CLI Wrapper > C#...Full disclosure, the problem still lives, it's just been pushed to the C++/CLI Wrapper now on the same line (the return). And finally, the crashing code from C#: public static int hReceiveLogEvent(IntPtr pInstance, IntPtr pData) { Console.WriteLine("in hReceiveLogEvent..."); Console.WriteLine("pInstance: {0}", pInstance); Console.WriteLine("pData: {0}", pData); // provide object context for static member function helloworld hw = (helloworld)GCHandle.FromIntPtr(pInstance).Target; if (hw == null || pData == null) { Console.WriteLine("hReceiveLogEvent: received null instance pointer or null data\n"); return 0; } // typecast data to DataLogger object ptr IntPtr ip2 = GCHandle.ToIntPtr(GCHandle.Alloc(new DataLoggerWrap(pData))); DataLoggerWrap dlw = (DataLoggerWrap)GCHandle.FromIntPtr(ip2).Target; //Do Logging Stuff Console.WriteLine("exiting hReceiveLogEvent..."); Console.WriteLine("pInstance: {0}", pInstance); Console.WriteLine("pData: {0}", pData); Console.WriteLine("Setting pData to zero..."); pData = IntPtr.Zero; pInstance = IntPtr.Zero; Console.WriteLine("pData: {0}", pData); Console.WriteLine("pInstance: {0}", pInstance); return 1; } All writes to the console are done and then we see the dreaded crash on the return: Unhandled exception at 0x04d1004c in helloworld.exe: 0xC0000005: Access violation reading location 0x04d1004c. If I step into the debugger from here, all I see is that the last entry on the call stack is: > "04d1004c()" which evaluates to a decimal value of: 80805964 Which is only interesting if you look at the console which shows: entering registerDataLogger pointer to callback handle: 790848 fp for callback: 2631370 pointer to inst: 790844 in hReceiveLogEvent... pInstance: 790844 pData: 80805964 exiting hReceiveLogEvent... pInstance: 790844 pData: 80805964 Setting pData to zero... pData: 0 pInstance: 0 Now, I know that between debug and release some things are quite different in the Microsoft world. I am, of course worried about byte padding and initialization of variables, so if there is something I am not providing here, just let me know and I'll add to the (already long) post. I also think the managed code may NOT be releasing all ownership and then the native C++ stuff (which I don't have the code for) may be trying to delete or kill off the pData object, thus crashing the app. More full disclosure, it all works fine (seemingly) in Debug mode! A real head scratch issue that would appreciate any help!
I think the stack got crushed because of mismatching calling conventions: try out to put the attribute [UnmanagedFunctionPointer(CallingConvention.Cdecl)] on the callback delegate declaration.
1,411,222
1,411,288
Giving an instance of a class a pointer to a struct
I am trying to get SSE functionality in my vector class (I've rewritten it three times so far. :\) and I'm doing the following: #ifndef _POINT_FINAL_H_ #define _POINT_FINAL_H_ #include "math.h" namespace Vector3D { #define SSE_VERSION 3 #if SSE_VERSION >= 2 #include <emmintrin.h> // SSE2 #if SSE_VERSION >= 3 #include <pmmintrin.h> // SSE3 #endif #else #include <stdlib.h> #endif #if SSE_VERSION >= 2 typedef union { __m128 vector; float numbers[4]; } VectorData; //typedef union { __m128 vector; struct { float x, y, z, w; }; } VectorData; #else typedef struct { float x, y, z, w; } VectorData; #endif class Point3D { public: Point3D(); Point3D(float a_X, float a_Y, float a_Z); Point3D(VectorData* a_Data); ~Point3D(); // a lot of not-so-interesting functions private: VectorData* _NewData(); }; // class Point3D }; // namespace Vector3D #endif It works! Hurray! But it's slower than my previous attempt. Boo. I've determined that my bottle neck is the malloc I'm using to get a pointer to a struct. VectorData* Point3D::_NewData() { #if SSE_VERSION >= 2 return ((VectorData*) _aligned_malloc(sizeof(VectorData), 16)); #else return ((VectorData*) malloc(sizeof(VectorData))); #endif } One of the main problems with using SSE in a class is that it has to be aligned in memory for it to work, which means overloading the new and delete operators, resulting in code like this: BadVector* test1 = new BadVector(1, 2, 3); BadVector* test2 = new BadVector(4, 5, 6); *test1 *= test2; You can no longer use the default constructor and you have to avoid new like the plague. My new approach is basically to have the data external from the class so the class doesn't have to be aligned. My question is: is there a better way to get a pointer to an (aligned on memory) instance of a struct or is my approach really dumb and there's a much cleaner way?
How about: __declspec( align( 16 ) ) VectorData vd; ? You can also create your own version of operator new as follows void* operator new( size_t size, size_t alignment ) { return __aligned_malloc( size, alignment ); } which can then make allocationas follows AlignedData* pData = new( 16 ) AlignedData; to align at a 16 byte boundary. If thats no help then i may be misunderstanding what you are asking for ...
1,411,230
1,411,993
thread-safe function pointers in C++
I'm writing a network library that a user can pass a function pointer to for execution on certain network events. In order to keep the listening loop from holding up the developer's application, I pass the event handler to a thread. Unfortunately, this creates a bit of a headache for handling things in a thread-safe manner. For instance, if the developer passes a function that makes calls to their Windows::Forms application's elements, then an InvalidOperationException will be thrown. Are there any good strategies for handling thread safety?
Function pointers can not be thread safe as they declare a point to call. So they are just pointers. Your code always runs in the thread it was called from (via the function pointer). What you want to achieve is that your code runs in a specific thread (maybe the UI thread). For this you must use some kind of queue to synchronize the invocation into the MainThread. This is exactly what .Net's BeginInvoke()/Invoke() on a Form do. The queue is in that case (somewhere deep inside the .NET framework) the windows message queue. But you can use any other queue as long as the "correct" thread reads and executes the call requests from that queue.
1,411,279
1,411,468
Using boost::shared_ptr within inheritance hierarchy
Imagine the following situation: class IAlarm : public boost::enable_shared_from_this<IAlarm> { boost::shared_ptr<IAlarm> getThisPointerForIAlarm() { return shared_from_this(); } void verifyThis(int); // called by Device }; class Alarm : public IAlarm { Alarm( boost::shared_ptr< Device > attachedDevice){ attachedDevice->attachAlarm(this->getThisPointerForIAlarm()); } void sendAlarm(){ attachedDevice->Alarm(); } }; class Device { attachAlarm( boost::shared_ptr< IAlarm > ia){ this->alarm=ia; } }; I want to attach an Alarm to a Device. Alarm and Device aren't allowed to know about each other (this would end up in circular dependency). So that's why I use the Interface Class IAlarm. Finally I want to be able to attach several alarms on to one device. The alarms can access the device they are attached to and the devices can start verification on the attached Alarms Everything compiles nice. But if I try to attach an Alarm to a Device I get the following: boost::shared_ptr<Device> ptrDevice(new Device()); boost::shared_ptr<IAlarm> ptrAlarm(new Alarm( ptrDevice )); terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> >' what(): tr1::bad_weak_ptr What's exactly the problem? This setup worked more or less before using boost::shared_ptr with references and pure pointers. Is it possible to get this work with boost:shared_ptr?
The call to shared_from_this() is only valid if it is called on a dynamically allocated object that is owned by a shared_ptr (See the requirements listed in the docs). This means that there must exist a shared_ptr that owns the object, else shared_from_this() will not work. Especially this means that you can't (successfully) call shared_from_this() in the constructor, since the object is just being constructed and is not yet owned by any shared_ptr instance. To work around it you best move the code that attaches the alarm from the constructor to a separate method that gets called after the object is completely constructed: boost::shared_ptr<Alarm> a(new Alarm()); a->attach(attachedDevice);
1,411,505
1,421,063
Mystery pthread problem with fork()
I have a program which: has a main thread (1) which starts a server thread (2) and another (4). the server thread (2) does an accept(), then creates a new thread (3) to handle the connection. At some point, thread (4) does a fork/exec to run another program which should connect to the socket that thread (2) is listening to. Occasionally this fails or takes an unreasonably long time, and it's extremely difficult to diagnose. If I strace the system, it appears that the fork/exec has worked, the accept has happened, the new thread (4) has been created .. but nothing happens in that thread (using strace -ff, the file for the relevant pid is blank). Any ideas?
I came to the conclusion that it was probably this phenomenon: http://kerneltrap.org/mailarchive/linux-kernel/2008/8/15/2950234/thread as the bug is difficult to trigger on our development systems but is generally reported by users running on large shared machines; also the forked application starts a JVM, which itself allocates a lot of threads. The problem is also associated with the machine being loaded, and extensive memory usage (we have a machine with 128Gb of RAM and processes may be 10-100G in size). I've been reading the O'Reilly pthreads book, which explains pthread_atfork(), and suggests the use of a "surrogate parent" process forked from the main process at startup from which subprocesses are run. It also suggests the use of a pre-created thread pool. Both of these seem like good ideas, so I'm going to implement at least one of them.
1,411,526
1,411,791
How can I debug a program when debugger fails
I am debugging an Iphone program with the simulator in xCode and I have one last issue to resolve but I need help resolving it for the following reason: when it happens the program goes into debugging mode but no errors appear (no BAD ACCESS appears) and it does not show where the code fails. Putting some variables as global helps me to see their values to start pin pointing where the bug is but before I go into this fully I would like to know what techniques/tools you guys use to debug these situations. If it helps Im debugging the following: I merged some code into the SpeakHere demo. The code was added in the C++ modules of the program (AQRecorder.h and .mm). I seem to have pinpointed the problem code in a function I wrote.
My favourite is always to add debugging code and log it to a file. This allows me so report any and all information I need to resolve the issue if the debugger is not working properly. I normally control the debugging code by use of a flag which I can manipulate at run time or by the command line.
1,411,652
1,411,705
Is MySQL C++ Connector access to remote database possible?
I am accessing a MySQL database within a C++ app using MySQL C++ Connector. It works fine if I have the C++ and the MySQL on the same machine. So, something like the following code works fine: sql::Connection *_con; sql::mysql::MySQL_Driver *_driver; _driver = sql::mysql::get_mysql_driver_instance(); _con = _driver->connect("tcp://127.0.0.1:3306", "user", "password"); However, I can't seem to access the database if it is located on another machine. So, something like this: sql::Connection *_con; sql::mysql::MySQL_Driver *_driver; _driver = sql::mysql::get_mysql_driver_instance(); _con = _driver->connect("tcp://somesite.com:3306", "user", "password"); Is it just not possible or am I doing something wrong?
Did you accidentally setup your users so that they can only access your DB from the local machine? Did you do create user 'user'@'127.0.0.1' ... or create user 'user'@'%' .... If you did the first then you won't be able to log on from a different machine. Did you also grant the privileges correctly? See the MySQL docs for a more in depth explanation on how to do this correctly
1,411,667
1,411,708
c++ debugging in vis studio 2008, how to break when a variable becomes zero
I can detect when a variable changes, but it changes so often that its no use - what I want is to detect the moment that a variable becomes zero. Thanks,
That's not possible in Visual Studio. Visual Studio supports a number of debugging features in that particular area but I don't think you can combine them into a feature to get what you want Data Changing Breakpoints: break when a value changes (only supported in native C++) Conditionally breakpoints: break when the IP crosses the breakpoint and a particular condition is satisfied. What you could do though is wrap all writes to your variable into a setter function. Then use a conditional breakpoint to break when the value changes to 0. I think this is the closest you're going to get to the feature you want.
1,411,806
1,411,963
Determining size of a polymorphic C++ class
Using the sizeof operator, I can determine the size of any type – but how can I dynamically determine the size of a polymorphic class at runtime? For example, I have a pointer to an Animal, and I want to get the size of the actual object it points to, which will be different if it is a Cat or a Dog. Is there a simple way to do this, short of creating a virtual method Animal::size and overloading it to return the sizeof of each specific type?
If you know the set of possible types, you can use RTTI to find out the dynamic type by doing dynamic_cast. If you don't, the only way is through a virtual function.
1,411,813
1,411,961
Safely moving a C++ object
I’ve heard some words of warning against shipping an object to another memory location via memcpy, but I don’t know the specific reasons. Unless its contained members do tricky things that depend on memory location, this should be perfectly safe … or not? EDIT: The contemplated use case is a data structure like a vector, which stores objects (not pointers to objects) in a continuous chunk of memory (i.e. an array). To insert a new object at the n-th position, all objects starting at position n and beyond will need to be moved to make room for the object to be inserted.
For the sake of discussion, I assume you mean moving to mean that the original object "dropped" (is no longer used, didn't have it's destructor run) rather than have two copies (which would lead to a lot more problems, reference counts being off, etc). I generally refer to the property of being able to do this being bitwise movable. In the code bases I work on, the majority of objects are bitwise movable, as they don't store self references. However, some data structures aren't bitwise movable (I believe that gcc's std::set wasn't bitwise movable; other examples would be linked list nodes). In general, I would avoid attempting to use this property as it can lead to some very hard to debug errors, and prefer the object oriented calling copy constructors. Edited to add: There seems to be some confusion on how/why someone would do this: here's a comment I made on the how: Normally, I see the above on alternate implementations of vector. The memory is allocated via malloc(sizeof(Class)*size) and the objects are constructed in place via explicitly called constructors and destructors. Sometimes (like during reallocation) they have to be moved, so the option is to do std::vector's repeated calling of copy constructors on new memory and destructors on the old, or use memcopy and just "free" the old block. Most times the latter just "works", but doesn't for all objects. As to why, a memcopy (or realloc) approach can be significantly faster. Yes, it invokes undefined behavior, but it also just tends to work for a majority of objects. Some people consider the speed worth it. If you were really set on using this approach, I would suggest implementing a bitwise_movable type trait to allow types this works for to be whitelisted, and fall back on the traditional copy for objects not in the whitelist, much like the example here.
1,411,821
1,412,368
What would be the purpose of using the reference and dereference operators immediately in sequence "&*B"?
I have seen this in our code a couple times and it immediately makes me suspicious. But since I don't know the original intent I am hesitant to remove it. //requires double indirection which I won't go into FooClass::FooFunction(void ** param) { //do something } SomeClass * A = new SomeClass(); SomeClass **B = &A; FooFunction( reinterpret_cast<void**>(&*B) ); // what is happening here? The "&*B" part is the part in question? Feel free to integrate explanation of the reinterpret cast but I am pretty familiar with cast techniques.
I can see only one reason for this: B has overloaded operator*() to return an X, but whoever wrote the code needed an X*. (Note that in your code, X is A*.) The typical case for this is smart pointers and iterators. If the above isn't the case, maybe the code was written to be generic enough to deal with smart pointers/iterators. Or it used to use smart pointers and whoever changed it didn't bother changing &*, too? Have you poked through its history to see when this was introduced and what the code looked then?
1,411,844
1,411,891
Polymorphism & Pointers to arrays
I have a class A: class A { public: virtual double getValue() = 0; } And a class B: class B : public A { public: virtual double getValue() { return 0.0; } } And then in main() I do: A * var; var = new B[100]; std::cout << var[0].getValue(); //This works fine std::cout << var[1].getValue(); //This, or any other index besides 0, causes the program to quit If instead I do: B * var; var = new B[100]; std::cout << var[0].getValue(); //This works fine std::cout << var[1].getValue(); //Everything else works fine too Everything compiles fine, but it seems as though there is something wrong with my polymorphism perhaps? I'm puzzled.
You can't treat arrays polymorphically, so while new B[100] creates an array of B objects and returns a pointer to the array - or equivalently the first element of the array - and while it is valid to assign this pointer to a pointer to a base class, it is not valid to treat this as a pointer into an array of A objects. The principal reason that you can't is that (typically) derived objects are a different size to their base classes, so attempting to access the array as an array of base class objects will not use the correct offset to get a pointer to the next base class subobject of the next member of the derived class array.
1,412,016
1,412,036
Best way to create large hashmap at compile time (C++)?
In my application, I need a hash map mapping strings to a large number of static objects. The mappings remain fixed for the duration of the application. Is there an easy way to pre-generate the mappings at compile time rather than building it element-by-element when the application starts?
Look up gperf, it generates code for you that will perfectly hash.
1,412,080
1,412,289
Distributing with Boost Library?
I'm quite new to using boost and I can't seem to find documentation anywhere on how to distribute your application when using boost? Many of the libraries are shared libraries, I'm not expecting my users to have boost installed, I'm only using a single library (regex) so is there an easy way to package the regex library with my application without compiling with the static version?
Linux For binary distribution, I recommend using the distribution's package management, which should take care of any dependencies. Some commercial apps just use binary blobs and you need to install a version of boost by yourself. Finding libraries is a bit more difficult on linux. It does not automatically load shared objects from the current directory if they are linked at compile time (as opposed to loading at runtime with dlopen). You have to use the LD_LIBRARY_PATH env variable or use rpath. Both has it's drawbacks. Windows There is no way around including the dlls. The usual approach is to put everything into a directory and zip it up. Both To build from source you need the boost sources anyway, so no need to include libraries. Most libraries in boost are header only anyway, regexp is not one of them. It should be sufficient to include dlls for this module. In Linux you can check against which shared libs your binary is compiled by using: ldd binary
1,412,081
1,412,094
Are do-while-false loops common?
A while back I switched the way I handled c style errors. I found a lot of my code looked like this: int errorCode = 0; errorCode = doSomething(); if (errorCode == 0) { errorCode = doSomethingElse(); } ... if (errorCode == 0) { errorCode = doSomethingElseNew(); } But recently I've been writing it like this: int errorCode = 0; do { if (doSomething() != 0) break; if (doSomethingElse() != 0) break; ... if (doSomethingElseNew() != 0) break; } while(false); I've seen a lot of code where nothing gets executed after there's an error, but it has always been written in the first style. Is there anyone else who uses this style, and if you don't, why? Edit: just to clarify, usually this construct uses errno otherwise I will assign the value to an int before breaking. Also there's usually more code than just a single function call within the if (error == 0 ) clauses. Lots of good points to think on, though.
The second snippet just looks wrong. You're effectively re-invented goto. Anyone reading the first code style will immediately know what's happening, the second style requires more examination, thus makes maintenance harder in the long run, for no real benefit. Edit, in the second style, you've thrown away the error code, so you can't take any corrective action or display an informative message, log something useful etc....
1,412,338
1,421,291
Win32 C/C++ checking if two instances of the same program use the same arguments
I have an application and I want to be able to check if (for instance) two instances of it used the same arguments on execution. To make it clearer: myapp 1 2 myapp 1 3 This isn't a Singleton design pattern problem as I can have more than one instance running. I though about checking the running processes, but it seems that I can only get the process name and that doesn't help me. Writing a file on startup and then having other instances check if that file exists isn't viable due to abnormal program termination which would leave me hanging. In Linux I solved this by checking /proc/pid/cmdline and parsing the information there. Does anyone have any idea if I can do something similar on windows? Cheers
After some thinking I decided to do things a bit simpler... Implementing a mutex and checking it's existence is. As I needed to check if the instances started with the same parameters and not if the same application was started, I just needed to decide on the mutex name in runtime! so... sprintf(cmdstr,"myapp_%i_%i",arg1,arg2); DWORD m_dwLastError; m_hMutex = CreateMutex(NULL, FALSE, cmdstr); m_dwLastError = GetLastError(); if(ERROR_ALREADY_EXISTS == m_dwLastError) { found_other = true; } and that's it! no parsing, no wmi, no windows development sdk... Cheers to you all!
1,412,348
1,412,451
Is it possible to return a derived class from a base class method in C++?
I would like to do this: class Derived; class Base { virtual Derived f() = 0; }; class Derived : public Base { }; Of course this doesn't work since I can't return an incomplete type. But neither can I define Derived before base, since I can't inherit from an incomplete type either. I figure that I could use templates as a workaround (using Derived as a template argument to Base), but it seems a really ugly way of doing things. Might there be another way? Elaboration: I'm writing a raytracer, and each Shape class has a function which returns its bounding box. However, I've made the BBox a subclass of Shape, so I can visualize it. Is this bad design?
There's nothing wrong with the code in your question. This class Derived; class Base { virtual Derived f() = 0; }; class Derived : public Base { virtual Derived f() {return Derived();} }; should compile just fine. However, callers of 'Base::f()' will need to have seen the definition of 'Derived`.
1,412,737
1,412,769
Templated class function T: How to find out if T is a pointer?
As a follow-up to this question: I need to decide in a class function like this: template< typename T > bool Class::Fun <T*> ( T& variable ) {...} whether T is a pointer or not. In the question cited above the answer was to use partial template specialization. As far as I've found out this is not possible for class functions. Is this true? If so, is there another way of finding out if T is a pointer?
No need to specialize member function. In that answer used stand-alone structure. You're still free to use it in class member functions. // stand-alone helper struct template<typename T> struct is_pointer { static const bool value = false; }; template<typename T> struct is_pointer<T*> { static const bool value = true; }; // your class class Class{ public: template<typename T> void Fun(T& variable) { std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl; } }; On the other hand, you could overload function: class Class { public: template<typename T> void Fun(T& variable) { std::cout << "is it not a pointer! " << std::endl; } template<typename T> void Fun(T*& variable) { std::cout << "is it a pointer! " << std::endl; } };
1,412,751
1,412,792
Find largest and second largest element in a range
How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are duplicates.
for (e: all elements) { if (e > largest) { second = largest; largest = e; } else if (e > second) { second = e; } } You could either initialize largest and second to an appropriate lower bound, or to the first two items in the list (check which one is bigger, and don't forget to check if the list has at least two items)
1,412,885
1,412,904
Basic doubt in QT using C++ about making objects
int main (int argc, char* argv[]) { QApplication app(argc, argv); QTextStream cout(stdout, QIODevice::WriteOnly); // Declarations of variables int answer = 0; do { // local variables to the loop: int factArg = 0; int fact(1); factArg = QInputDialog::getInteger(0, "Factorial Calculator", "Factorial of:", 1); cout << "User entered: " << factArg << endl; int i=2; while (i <= factArg) { fact = fact * i; ++i; } QString response = QString("The factorial of %1 is %2.\n%3") .arg(factArg).arg(fact) .arg("Do you want to compute another factorial?"); answer = QMessageBox::question(0, "Play again?", response, QMessageBox::Yes | QMessageBox::No); } while (answer == QMessageBox::Yes); return EXIT_SUCCESS; } Link taken from here originally from above link... Can you help me out with "QInputDialog..(4th line of do while loop)" How do I get to know about which arguments does it have? I saw the documentation but i couldnt find out, whats this "0" and "1" in arguments..
Read the docs. Basically - first is a parent widget (NULL in this case), and the 1 after label is a default value.
1,413,158
1,413,347
Partial specialization of a class template in derived class affects base class
I have a metafunction: struct METAFUNCION { template<class T> struct apply { typedef T type; }; }; Then I define a helper: template<class T1, class T2> struct HELPER { }; And then I have second metafunction which derives from the METAFUNCTION above and defines partial specialization of apply struct: struct METAFUNCION2 : METAFUNCION { template<class T1, class T2> struct apply<HELPER<T1, T2> > : METAFUNCION::apply<T2> { }; }; So far, so good - the code compiles under g++ 4.3.2. So I used it like below: #include <typeinfo> #include <string> #include <cstdlib> #include <cxxabi.h> template<typename T> struct type_info2 { static std::string name() { char *p = abi::__cxa_demangle(typeid(T).name(), 0, 0, 0); std::string r(p); free(p); return(r); } }; #include <boost/mpl/apply.hpp> #include <iostream> int main() { std::cout << type_info2<boost::mpl::apply<METAFUNCION, int>::type>::name() << std::endl; std::cout << type_info2<boost::mpl::apply<METAFUNCION, HELPER<float, double> >::type>::name() << std::endl; std::cout << type_info2<boost::mpl::apply<METAFUNCION2, HELPER<float, double> >::type>::name() << std::endl; return(0); } The output: int double double That surprised me a bit as I expected: int HELPER<float, double> double Now, I know that code like above does not compile under Microsoft Visual C++ 2008 (I don't remeber the message but it was something along the lines that I cannot specialize apply struct inside METAFUNCTION2 struct). So my question is - is this g++ behaviour conformant with the standard? I have a strong feeling that there is something wrong here but I am not 100% sure. For the curious - I have the behaviuor as I expected when I redefine METAFUNCTION2 this way: struct METAFUNCION2 : METAFUNCION { template<class T> struct apply : METAFUNCION::apply<T> { }; template<class T1, class T2> struct apply<HELPER<T1, T2> > : METAFUNCION::apply<T2> { }; };
The following code is illegal: struct METAFUNCION2 : METAFUNCION { template<class T1, class T2> struct apply<HELPER<T1, T2> > : METAFUNCION::apply<T2> { }; }; According to C++ Standard 14.7.3/3: A declaration of a function template or class template being explicitly specialized shall be in scope at the point of declaration of an explicit specialization. EDIT: According to Core Issue 727 this restriction does not apply to partial specializations of member templates.
1,413,171
1,413,191
What is "strip" (GCC application) used for?
what is this little application for? When using it without any options reduces the size of the executables, but how/what it does?
From the (Mac OS X, but others are similar) man page: strip removes or modifies the symbol table attached to the output of the assembler and link editor. This is useful to save space after a program has been debugged and to limit dynamically bound symbols. Note the bit about "after a program has been debugged" because debugging a stripped executable is very hard, indeed. The "limit dynamically bound symbols" is a rarer use: it lets you make some of the functions in an external library inaccessible by taking away the index entries that tell where the actual code is located. This is also explained in the man page. As cheap and plentiful as disk is in most situation you simply wouldn't bother with this anymore. But you might want it for space constrained situation like embeded devices, rescue disks, etc.
1,413,193
1,413,302
Deterministic handle allocation algorithm
I'm trying to find an efficient deterministic way of allocating a 32-bit handle in such a way that it will operate indefinitely. A simple incrementing counter will not work because it will eventually loop around. Extending to 64-bits isn't possible because the values will be used in a network protocol which is expecting a 32-bit value. It's for a real-time system so it has to be deterministic and quick. Though it'll end up in an SQLite database I can't just brute force test each key after loop around for example... I think what I need is some sort of range tree that knows about all previously allocated handles (populating this on start up is fine). This seems to be a common(ish) sort of problem but it's not one that's solved by boost or the STL. Any pointers? Edit: Some additional clarification. I'm looking to have something of the order of 200k active handles in the system at any one time. Handles are deleted on a random basis.
You can't allocate more than 2^32. But you can reallocate used handles if they are released and the problem is to keep track of the free handles. A tree is a good way to store the free handles. Each node has a lowest and a highest handle, the left subtree contains the handles that are lesser than the lowest and the right subtree contains the handles that are greater than the highest. An example is: 6-9 / \ 2 15 / \ 0 4 If a handle is released, it is stored in the tree. For example, if 10 is released, the tree looks like: 6-10 / \ 2 15 / \ 0 4 If handle 5 is released, you can chose to optimize the tree because 4 can be added to the 5-10 node as wel: 5-10 / \ 2 15 / \ 0 4 To: 4-10 / \ 2 15 / 0 The allocation of a handle, searches for a leaf node with 1 handle and removes it from the tree. If there are no leaves with 1 handle, just use a leaf and decrement the side that is not connected to the parent: 4-10 / 1-2 In the above example we allocate 1 and not 2 because if 3 is released, you can combine it with 4 and you want to keep the number of nodes as low as possible. Below is a pseudocode algorithm. Some parts are left for the reader: Node = ( int lowest, highest; [Node] left, right) Node.Allocate() if TryFindLonelyLeaf(handle) return handle; else return FindLeafHandle(NULL); Node.TryFindLonelyLeaf(handle) if (left == NULL & right == NULL) if (lowest == highest) handle == lowest; return TRUE; else return FALSE; if (left != NULL & left.TryFindLonelyLeaf(handle)) if (left.lowest == handle) left == NULL; // Free node return TRUE; elsif (right != NULL & right.TryFindLonelyLeaf(handle)) if (right.lowest == handle) right = NULL; // Free node return TRUE; else return FALSE; Node.FindLeafHhandle(parent) if (left == NULL & right == NULL) if (parent == NULL | parent.right == this) handle = lowest; lowest++; else handle = highest; highest--; return handle; else if (left != NULL) return left.FindLeafHandle(); else // right != NULL return right.FindLeafHandle(); Node.DeAllocate(handle) Assert(handle<lowest or handle>highest); if (handle == lowest-1) lowest = CompactLeft(handle); elsif (handle == lowest+1) highest = CompactRight(handle); elsif (handle<lowest) if (left == NULL) left = (handle, handle, NULL, NULL); else left.DeAllocate(handle); elsif (handle>highest) if (right == NULL) right = (handle, handle, NULL, NULL); else right.DeAllocate(handle); else ERROR Node.CompactLeft(handle) if (highest == handle-1) handle = lowest; // deallocate node and replace with left subtree return handle; elsif (right != NULL) return right.CompactLeft(handle) else return handle; Node.CompactRight(handle) if (lowest == handle+1) handle = highest; // deallocate node and replace with right subtree return handle; elsif (left != NULL) return left.CompactRight(handle) else return handle;
1,413,239
1,413,246
const char* to LPTSTR
I am trying to call a function that accepts an LPTSTR as a parameter. I am calling it with a string literal, as in foo("bar"); I get an error that I "cannot convert parameter 1 from 'const char [3]' to 'LPTSTR'", but I have no idea why or how to fix it. Any help would be great.
You probably has UNICODE defined, and LPTSTR expands into wchar_t*. Use TEXT macro for string literals to avoid problems with that, e.g. foo(TEXT("bar")).
1,413,256
1,413,469
execl pipe without dup
I am trying to execute a program from a parent using execl. I do the normal pipe setup and fork. Here is the trick... I need my children (there can be an arbitrary number of children) to all communicate with the parent. Program "A" (parent) creates pipe forks and execl into "B" (child). In the main() function of program B I need to be able to read and write to the pipe. Is there any way to access my pipe file descriptors in the child process after the excel takes over and executes my child process? Thank you, ~Eric
execl(3) has no effect on file descriptors, with one exception It is possible to mark a file descriptor close-on-exec with fcntl(2), but generally the various flavors of execve(2) have no effect on open file descriptors and they remain open in children.
1,413,445
1,455,007
Reading a password from std::cin
I need to read a password from standard input and wanted std::cin not to echo the characters typed by the user... How can I disable the echo from std::cin? here is the code that I'm currently using: string passwd; cout << "Enter the password: "; getline( cin, passwd ); I'm looking for a OS agnostic way to do this. Here there are ways to do this in both Windows and *nix.
@wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like: #ifdef WIN32 #include <windows.h> #else #include <termios.h> #include <unistd.h> #endif void SetStdinEcho(bool enable = true) { #ifdef WIN32 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); DWORD mode; GetConsoleMode(hStdin, &mode); if( !enable ) mode &= ~ENABLE_ECHO_INPUT; else mode |= ENABLE_ECHO_INPUT; SetConsoleMode(hStdin, mode ); #else struct termios tty; tcgetattr(STDIN_FILENO, &tty); if( !enable ) tty.c_lflag &= ~ECHO; else tty.c_lflag |= ECHO; (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty); #endif } Sample usage: #include <iostream> #include <string> int main() { SetStdinEcho(false); std::string password; std::cin >> password; SetStdinEcho(true); std::cout << password << std::endl; return 0; }
1,413,486
1,413,495
Where to get peer review of code and how to get my code attention?
I'm just now learning to programming at age 17. It's hard for me to talk to other programmers as I'm just out of high school (which means I can't take programming courses). I know that I write terrible code, and not like Jeff Atwood terrible code, my code actually sucks. So where can I post some of my code and get real programmers to review it. I know if I had a question I could ask it on StackOverflow, but I want to post a whole class and get a review on it. The real problem here is that I'm not going to be writing the next great piece of Software. I'm going to be writing a really useless class, which will serve no other purpose than to teach me how to program. This code will never be used, ever! EVER! How can I get an advanced (or even intermediate) programmer to look at my code? Thanks in advance! ;-)
Look to the open source community. There are plenty of existing and new projects that would love an eager (if inexperienced) developer to offer support. Going this route offers two advantages: You get to see great code in action and learn from it Any changes you submit will be reviewed by an experienced developer and they will often give you excellent suggestions as to how to improve your code before it will be accepted Start by choosing a project in your language (there are a bunch in c++) and check out the code. You don't need to understand it all, but you must be able to understand at least a portion of it. If the project looks way to complicated, keep looking. Younger projects tend to have less code that you need to learn.
1,413,588
1,413,627
Ambiguous template, Code Warrior
The following code compiles in Visual C++ and gcc, but fails with Code Warrior The complaint is that the call to the template is ambiguous -- can't decide between doIt( M* ) and doIt( M const* ), even though in each case, the parameter is unambiguously cost or non-const. Irritatingly, if I supply the second template argument, it decides it is no longer ambiguous. template< typename T1, typename T2 > T1 const* doIt( T2 const* ); template< typename T1, typename T2 > T1* doIt( T2* ); class M {}; class N : public M {}; void f() { M* m1 = NULL; M const* m2 = NULL; doIt<N>( m1 ); // Fail doIt<N>( m2 ); // Fail doIt<N,M>( m1 ); // OK doIt<N,M>( m2 ); // OK } Is this just an error with the Code Warrior compiler? (Or and error with gcc/Visual C++).
It is an error with the codewarrior compiler. This is what should happen: template< typename T1, typename T2 > T1 const* doIt( T2 const* ); // 1 template< typename T1, typename T2 > T1* doIt( T2* ); // 2 class M {}; class N : public M {}; void f() { M* m1 = 0; M const* m2 = 0; doIt<N>( m1 ); // In the above call - the compiler does the following (post argument deduction) // 1) create a viable set of functions { N* doIt1<N,M>(const M*) , N* doIt2<N, M>(M*) } // 2) check the conversion sequences - M* -> M* is better than M* -> const M* // Since doIt2 has a "better" conversion sequence (hard to beat identity) it wins - no ambiguity doIt<N>( m2 ); // 1) Viable functions: { doIt1<N,M>(const M*), doIt2<N,const M>(const M*) } // 2) Conversion Sequence Ranking: both do identity - so both are good // 3) Check to see if the "mother" template of either candidate is more specialized // - Since doIt1 theoretically matches fewer types than doIt2, it is unambiguously more specialized (the standard specifies an algorithm to check this) // - so doIt1 wins } Hope that helps.
1,413,744
1,413,824
Help with boost bind/functions
I have this function signature I have to match typedef int (*lua_CFunction) (lua_State *L);//target sig Here's what I have so far: //somewhere else... ... registerFunction<LuaEngine>("testFunc", &LuaEngine::testFunc, this); ... //0 arg callback void funcCallback0(boost::function<void ()> func, lua_State *state) { func(); } template<typename SelfType> void registerFunction(const std::string &funcName, boost::function<void (SelfType*)> func, SelfType *self) { //funcToCall has to match lua_CFunction boost::function<void (lua_State *)> funcToCall = boost::bind(&LuaEngine::funcCallback0, this, boost::bind(func, self), _1); lua_register(_luaState, funcName.c_str(), funcToCall); } However, at lua_register(_luaState..., it's still complaining about conversion issues Error 1 error C2664: 'lua_pushcclosure' : cannot convert parameter 2 from 'boost::function' to 'lua_CFunction' Anyone know how this can be solved?
This cannot be solved directly. Lua API wants a plain function pointers from you - that's just a code pointer, and nothing else. Meanwhile, boost::function is a function object, and there's no way it could possibly be convertible to a plain function pointer, because - roughly speaking - it captures not just the code, but also the state. In your example, the captured state is the value of self. So it has a code pointer for the code, and some data - and the target API expects just the code pointer.
1,413,768
1,420,326
I want to start developing CGI, but I am very new at this
I want to develop my next web project in C++ as FastCGI but I don't know how to start and google wasn't very friendly about this. I really don't know much about fastCGI or others libraries that makes cgi persistent... Tried to read some stuff, but it seems to be used along Linux with all those .configure Makefiles etc... can anyone give me a basic tutorial but kinda detailed about this? I have windows vista sp1 and IIS is configured to accept CGI, I have Visual Studio 2008 and DevC++ too. I downloaded the kit from fastcgi.com but its hard to understand the basics of it. A real simple howto on building a hello world, using fastcgi(any library that I can use persistent code) would be very nice. The basics, seriously, like I don't know if I can just include the files from the a fastcgi project to my project and compile both together, if that will work with my IIS. Even if that would work, I don't know which one I should build from fastCGI dev kit, there is a cgi-fcgi and libfcgi folders with files in them and there is Makefiles placed in almost all folders -_-"... I know that CGI in C++ is dificult to develop because it doesn't use templates and because you must take care of memory managment... But I want to give it a try. I am kinda tired of scripting languages and their restrictions/limitations. Sorry my english, I hope I was clear enough. Thanks, Joe
I would not recommend you to use FastCGI with IIS. IIS support of FastCGI is very limited -- it allows communication only over pipes and only one request is passed to process. FastCGI was added to IIS to somehow connect PHP and several other technologies to IIS. If you want to create web applications in C++ I would recommend you to use non-MS development environment. About programming. There are few tools to work with C++ for web, especially for MS environment: You may work directly with libfcgi and parse queries on your own -- quite a hard job but for very simple tasks it is fine. You may use some higher level libraries like CgiCC -- it is good for some basic stuff like forms, cookies but it is still quite limited. You may use a full MVC web framework like CppCMS. But I would not recommend you to work in Windows environment for this purposes. You may also try Wt for "GUI-over-Web" development style.
1,413,832
1,413,850
Calling constructor from another class
If I have a class like this: typedef union { __m128 quad; float numbers[4]; } Data class foo { public: foo() : m_Data() {} Data m_Data; }; and a class like this: class bar { public: bar() : m_Data() {} foo m_Data; } is foo's constructor called when making an instance of bar? Because when I try to use bar's m_Data's quad in bar it seems to be uninitialized, even though it has values in numbers[4]. :\ Specifically, this crashes: m_Data.quad = _mm_mul_ps(m_Data.quad, a_Other.m_Data.quad) Any help would be appreciated. :)
You have to declare your constructor to be public, otherwise you are not allowing anyone to instantiate your class if you declare it as private member.
1,413,878
1,413,886
Is it ok to use wcout to print char*?
Consider this line: std::wcout << "Hello World!"; Is it OK to pass char* or char to wide stream?
Both are ok because the wide stream has multiple overloads.
1,414,043
1,414,353
How to hide "Cancel" button in QInputDialog in QT using C++?
#include <QtGui> int main (int argc, char* argv[]) { QApplication app(argc, argv); QTextStream cout(stdout, QIODevice::WriteOnly); // Declarations of variables int answer = 0; do { // local variables to the loop: int factArg = 0; int fact(1); factArg = QInputDialog::getInteger(0, "Factorial Calculator", "Factorial of:"); cout << "User entered: " << factArg << endl; int i=2; while (i <= factArg) { fact = fact * i; ++i; } QString response = QString("The factorial of %1 is %2.\n%3") .arg(factArg).arg(fact) .arg("Do you want to compute another factorial?"); answer = QMessageBox::question(0, "Play again?", response, QMessageBox::Yes | QMessageBox::No ,QMessageBox::Yes); } while (answer == QMessageBox::Yes); return EXIT_SUCCESS; } In this program, i dont to have Input window(4th line of do-while loop) to have cancel button. How do i do that? I have just started learning QT. So, sorry if its a very basic question. And also how do i make use of cancel button to stop the application.. Bcos, right now CANCEL button does nothing.
QInputDialog is given as a convenience class that provides a quick and easy way to ask for an input and as such, does not allow for much customization. I don't see anything in the documentation to indicate that you can change the layout of the window. I would suggest just designing your own dialog by extending QDialog. This will take more time, but will allow you to customize the form. If you do want to determine if the cancel button was pressed in the QInputDialog, you must pass a pointer to a bool into the getInteger() function as the 8th argument. do{ bool ok; factArg = QInputDialog::getInteger(0, "Factorial Calculator", "Factorial of:", value, minValue, maxValue, step, &ok); if(!ok) { //cancel was pressed, break out of the loop break; } // // Do your processing based on input // } while (some_condition); If ok returns as false, the user clicked cancel and you can break out of your loop. You can see what value, minValue, maxValue, and step mean in the documentation: QInputDialog documentation
1,414,187
1,415,424
PostMessage for cross application messages
I'm trying to send a keystroke to another application. I can successfully find the window handle since using SendMessage worked exactly as intended. However, when I switched the SendMessage over to PostMessage, the application no longer received the messages. I did, however, find a workaround by using HWND_BROADCAST as the window handle, and it works fine, but isn't the ideal way to go about it. What I'm asking is, I have a valid hWnd, how can I send it messages using PostMessage and not SendMessage? Edit This is what I'm trying to do. HWND Target = FindWindow(0, "Window Title Goes Here"); LPARAM lParam = (1 | (57<<16)); // OEM Code and Repeat for WM_KEYDOWN WPARAM wParam = VK_SPACE; PostMessage(HWND_BROADCAST, WM_KEYDOWN, wParam, lParam); // Works PostMessage(Target, WM_KEYDOWN, wParam, lParam); // Doesn't Work SendMessage(Target, WM_KEYDOWN, wParam, lParam); // Works, but I need Post
The PostMessage function does not work when the message numbers between 0 and WM_USER-1. Use RegisterWindowMessage function to register your own messages.
1,414,506
1,414,520
Protected data in parent class not available in child class?
I am confused: I thought protected data was read/writable by the children of a given class in C++. The below snippet fails to compile in MS Compiler class A { protected: int data; }; class B : public A { public: B(A &a) { data = a.data; } }; int main() { A a; B b = a; return 0; } Error Message: Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. demoFail.cpp demoFail.cpp(12) : error C2248: 'A::data' : cannot access protected member declared in class 'A' demoFail.cpp(4) : see declaration of 'A::data' demoFail.cpp(2) : see declaration of 'A' What am I doing wrong?
According to TC++PL, pg 404: A derived class can access a base class’ protected members only for objects of its own type.... This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes. Of course, here's an easy way to fix this for your case: class A { protected: int data; }; class B : public A { public: B(const A &a) : A(a) { } }; int main() { A a; B b = a; return 0; }
1,414,897
1,432,272
Using GCC's C++0x mode in production?
Is anyone using the GCC 4.4.0 C++0x support in production? I'm thinking about using it with the latest MinGW, but I'm not sure if it's mature enough. I'm interested in: TR1 support auto initializer lists
IMHO, TR1 support and auto are safe to use. In the case of auto it was one of the first features to be included into the standard and is a relatively small change to the language. I would therefore have no problem using it. I would be a bit more hesitant about using initializer lists. On some other forums (eg. comp.lang.c++.moderated) there are questions about their behaviour and its possible that they may change closer to the release of the standard.
1,415,095
1,415,103
DoEvents equivalent for C++?
I'm new to native c++. Right now, I made it so when I press the left mouse button, it has a for loop that does InvalidateRect and draws a rectangle, and increments X by the box size each time it iterates. But, C++ is so much faster and efficient at drawing than C# that, it draws all this instantly. What I would like is for it to invalidate the rectangle, show the rectangle, wait 50ms, then continue the loop. I tried Sleep(50) but it still waits until painting is done before showing the result. I also tried PeekMessage but it did not change anything. Any help would be appreciated. Thanks
DoEvents basically translates as: void DoEvents() { MSG msg; BOOL result; while ( ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE ) ) { result = ::GetMessage(&msg, NULL, 0, 0); if (result == 0) // WM_QUIT { ::PostQuitMessage(msg.wParam); break; } else if (result == -1) { // Handle errors/exit application, etc. } else { ::TranslateMessage(&msg); :: DispatchMessage(&msg); } } }
1,415,388
1,415,406
C++ class dependencies
I'm having some problems with my class because they both depends on each other, to one can't be declared without the other one being declared. class block: GtkEventBox { public: block(board board,guint x,guint y): image("block.png") { this.board = board; this.x = x; this.y = y; board.attach(this,x,y,x+1,y+1); } void move(guint x,guint y) { board.remove(this); this.x = x; this.y = y; board.attach(this,x,y,x+1,y+1); } private: guint x, y; board board; GtkImage image; }; class board: Gtk::Table { public: board(): Gtk::Table(25,20) { blocks_c = 0; } void addBlock(guint x,guint y) { blocks_a[blocks_c++] = new block(this,x,y); } private: block* blocks_a[24]; int blocks_c; }; As you can see the "block" class needs to know what a "board" is and vice versa. Thanks in advance!
Define "board" before "block" and forward declare the "block" class. Also, move the implementation of the board functions out of the class definition. // forward declare block class class block; // declare board class class board: Gtk::Table { public: board(); void addBlock(guint x,guint y); private: block* blocks_a[24]; int blocks_c; }; // declare block class class block: GtkEventBox { public: block(board board,guint x,guint y); void move(guint x,guint y); private: guint x, y; board board; GtkImage image; }; // define member functions (implementation) here...
1,415,538
5,034,489
Using #include to load OpenCL code
I've seen this done long ago with hlsl/glsl shader code -- using an #include on the source code file that pastes the code into a char* so that no file IO happens at runtime. If I were to represent it as pseudo-code, it would look a little like this: #define CLSourceToString(filename) " #include "filename" " const char* kernel = CLSourceToString("kernel.cl"); Now of course that #define isn't going to work because it'll just try to use those quotation marks to start strings.
See the bullet physics engines use of OpenCL for how to do this to a kernel. In C++ / C source #define MSTRINGIFY(A) #A char* stringifiedSourceCL = #include "VectorAddKernels.cl" In the OpenCL source MSTRINGIFY( __kernel void VectorAdd(__global float8* c) { // snipped out OpenCL code... return; } );
1,415,569
1,415,686
String table encoding vs. gzip compression
In my application, I need to store and transmit data that contains many repeating string values (think entity names in an XML document). I have two proposed solutions: A) create a string table to be stored along the document, and then use index references (using multi-byte encoding) in the document body, or B) simply compress the document using gzip or a similar compression algorithm. Which one is likely going to perform better in terms of speed and data size? (Obviously, this depends on the quality of the implementations, but assume that option A builds an array of strings dynamically and encodes the document body in some reasonable fashion). Also, if option B, do you recommend a more potentially suitable compression method other than gzip?
gzip is only a good algorithm when the transmission/storage cost is not too high compared to the cost of CPU time. You can get better compression ratios with bzip2, 7zip, and especialy for natural language, various PPM algorithms. Of course, it's not only computation (and static vs. dynamic memory requirement) vs. compression ratio that matters - different compression formats allow varying degrees of efficient random access seeking, low latency stream decoding, and concatenation of zipped data (e.g. cat a.gz b.gz | gunzip -c is the same as gunzip -c a.gz;gunzip -c b.gz
1,415,608
1,415,639
C++ Custom compare function for list::sort
Hi I'm having trouble compiling a simple piece of code. I am creating a class which implements a Deck of cards, and I want to create a shuffle method using the list::short method. Relevant code: deck.h #ifndef _DECK_H #define _DECK_H #include <list> #include <ostream> #include "Card.h" #include "RandomGenerator.h" using namespace std; class Deck { private: static const int CARD_NUMBER = Card::CARDS_PER_SUIT*Card::SUIT_NUMBER; list<Card *> *cards; RandomGenerator rg; public: Deck(); ~Deck(); void shuffle(); private: bool const compareRandom(const Card *a, const Card *b); }; #endif /* _DECK_H */ deck.cc: #include "Deck.h" /** * Fills the deck with a set of 52 cards */ Deck::Deck() { cards = new list<Card *>(); for(int i = 0; i < CARD_NUMBER; i++) cards->push_back( new Card( Card::Suit(int(i/Card::CARDS_PER_SUIT)), i%Card::CARDS_PER_SUIT) ); } Deck::~Deck() { gather(); for(list<Card *>::iterator c = cards->begin(); c != cards->end(); c++) delete *c; delete cards; } bool const Deck::compareRandom(const Card *a, const Card *b) { return rg.randomBool(); } void Deck::shuffle() { cards->sort(compareRandom); } The compiler shows the next message (ignore line numbers): Deck.cc: In member function ‘void Deck::shuffle()’: Deck.cc:66: error: no matching function for call to ‘std::list<Card*, std::allocator<Card*> >::sort(<unresolved overloaded function type>)’ /usr/include/c++/4.3/bits/list.tcc:303: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = Card*, _Alloc = std::allocator<Card*>] /usr/include/c++/4.3/bits/list.tcc:380: note: void std::list<_Tp, _Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = const bool (Deck::*)(const Card*, const Card*), _Tp = Card*, _Alloc = std::allocator<Card*>] The problem has to be on the compareRandom reference that I'm not using correctly, I cant find googling the answer to this problem. Thanks in advance.
Can I say something :) First, don't store a pointer to Card, just store the cards directly in the container. If you insist on storing pointers to them for any reason, use shared_ptr<Card> from Boost. Second, you can use std::random_shuffle and pass your random-number-generator to it instead of implementing your your shuffle function. May I say something again :) This is what I have in mind, unless you have to use list for whatever reason, although I don't see that reason. #include <iostream> #include <vector> #include <deque> #include <algorithm> class Card { // ... }; int main() { typedef std::vector<Card> Deck; Deck deck; // ... fill deck with cards. // There is an optional third parameter, // if you need to pass YOUR random-number-generator! // If you do, I recommend Boost implementation. std::random_shuffle(deck.begin(), deck.end()); } I like to deal with containers directly in C++, though you may not like it. Also, if you see that std::vector has performance issues in your case, you could just replace the typedef with std::deque: typedef std::deque<Card> Deck;
1,415,656
1,415,953
Simple Qt Application won't compile on OS X
I've downloaded the Qt SDK and am trying to get started on my first Qt application using Qt Creator. Using the wizard from the opening splash screen I selected "Qt4 Gui Application" and it threw together a little project for me. When I try to build that project (without making any changes) I get build errors: Running build steps for project BlockGame... Configuration unchanged, skipping QMake step. Starting: /usr/bin/make -w make: Entering directory `/Users/mikemorton/BlockGame' g++ -headerpad_max_install_names -o BlockGame.app/Contents/MacOS/BlockGame main.o mainwindow.o moc_mainwindow.o -F/Library/Frameworks -L/Library/Frameworks -framework QtGui -framework Carbon -framework AppKit -framework QtCore -lz -lm -framework ApplicationServices /usr/bin/ld: /Library/Frameworks/QtGui.framework/QtGui load command 6 unknown cmd field /usr/bin/ld: /Library/Frameworks/QtCore.framework/QtCore load command 5 unknown cmd field collect2: ld returned 1 exit status make: *** [BlockGame.app/Contents/MacOS/BlockGame] Error 1 make: Leaving directory `/Users/mikemorton/BlockGame' Exited with code 2. Error while building project BlockGame When executing build step 'Make' I have no idea why it would give this error when I haven't changed anything in the default project. I'm not trying to build from the command line, just using Qt Creator. Any help appreciated.
I managed to solve this by reinstalling the developer tools. I guess something had messed up my version of ld.
1,415,690
1,415,735
Problem solving in C++ with STL
I am preparing for a programming competition in witch we solve programming problems in c++. Looking at the former year solutions, they seem quite easy (not more than ~30 lines of code). I realised that they are widely using the STL for easy manipulating - vectors, sets, maps, lists and also the algorithms available in STL. Any site for beginners like me who want to learn the features of STL and its use in solving problems ? Thank you in advance.
As well as Scott Meyer's excellent book "Effective STL" which has been recommended above, I can't recommend highly enough the excellent book Accelerated C++ by Andrew Koenig and Barbara E. Moo. The book starts by having you use STL very early in the book explaining their uses in the context of initially simple problems. This book treats C++ as its own language and not as C with bits bolted on, the mechanics of defining a class aren't explained until later in the book.
1,415,755
1,415,780
How to read and write bits to a byte array
I have a unsigned char buffer, and I'm wondering how I would write and read signed and unsigned bits to this byte buffer. In the Source Engine there is a class named bf_write, which two main methods (used by WriteString, WriteChar, WriteLong, etc.) use two functions named WriteUBitLong and WriteSBitLong. Thanks in advance
If the number of bits is a compile-time constant: #include <bitset> ... std::bitset<100> b; b[2]=true; If it's not, use Boost.dynamic_bitset Or, if you're desperate, std::vector, which is indeed a packed bit vector: #include <vector> ... std::vector<bool> b(100); b[2]=true; You seem to want to use a library that requires bit vectors packed in an array of bytes. Without knowing exactly what order it places the bits in, I can only note that: 1) all of the above will probably use at least 32-bit ints with bits ordered least->most or most->least significant 2) on little endian (Intel/AMD) CPUs, this means that the memory occupied by the bytes an array of ints may not be consistent with the ordering of bits within the int. if it's "bit 0 is the lsb of int 0, ... bit 32 is the lsb of int 1, ..." then that's the same in little endian as "bit 0 is the lsb of char 0, ... bit 32 is the lsb of char 4 ...", in which case you can just cast a pointer to the int array to a pointer to char array 3) supposing the native order of bytes in your bit set / vector isn't exactly what the library needs, then you have to either have to create your own that has the layout they want, or transcribe a copy into their layout. a) if the order of bits within a byte is different, a 256 entry lookup table giving the byte with bits reversed would be efficient. you could generate the table with a small routine. b) to reverse bytes from little<->big endian: inline void endian_swap(unsigned short& x) { x = (x>>8) | (x<<8); } inline void endian_swap(unsigned int& x) { x = (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24); } inline void endian_swap(unsigned long long& x) { x = (x>>56) | ((x<<40) & 0x00FF000000000000) | ((x<<24) & 0x0000FF0000000000) | ((x<<8) & 0x000000FF00000000) | ((x>>8) & 0x00000000FF000000) | ((x>>24) & 0x0000000000FF0000) | ((x>>40) & 0x000000000000FF00) | (x<<56); } To get/set a particular bit within a word, with bit #0 in the least significant bit of word 0: typedef unsigned char block_t; const unsigned block_bits=8; inline void set_bit(block_t *d,unsigned i) { unsigned b=i/block_bits; unsigned bit=i-(block_bits*b); // same as i%b block_t &bl=d[b]; bl|=(1<<bit); // or bit with 1 (others anded w/ 0) } inline void clear_bit(block_t *d,unsigned i) { unsigned b=i/block_bits; unsigned bit=i-(block_bits*b); // same as i%b block_t &bl=d[b]; bl&=(~(1<<bit)); // and bit with 0 (other bits anded w/ 1) } inline void modify_bit(block_t *d,unsigned i,bool val) { if (val) set_bit(d,i) else clear_bit(d,i); } inline bool get_bit(block_t const* d,unsigned i) { unsigned b=i/block_bits; unsigned bit=i-(block_bits*b); // same as i%b return d[b]&(1<<bit); } Obviously if the rule for bit organization differs, you have to change the above. Using the widest possible int your CPU processes efficiently as block_t is best (dont' forget to change block_bits), unless the endianness doesn't work out w/ the library you're using.