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
778,085
778,124
How to name a thread in Linux?
I have a multithreaded Linux application written in C/C++. I have chosen names for my threads. To aid debugging, I would like these names to be visible in GDB, "top", etc. Is this possible, and if so how? (There are plenty of reasons to know the thread name. Right now I want to know which thread is taking up 50% CPU (as reported by 'top'). And when debugging I often need to switch to a different thread - currently I have to do "thread apply all bt" then look through pages of backtrace output to find the right thread). The Windows solution is here; what's the Linux one?
Posix Threads? This evidently won't compile, but it will give you an idea of where to go hunting. I'm not even sure its the right PR_ command, but i think it is. It's been a while... #include <sys/prctl.h> prctl(PR_SET_NAME,"<null> terminated string",0,0,0)
778,378
778,397
How to write bitset data to a file?
I have a std::bitset that I'd like to write to a file, bit for bit, but of course fstream's write function doesn't support this. I can't think of another way besides converting each 8-bit group to a char using string and writing that... Anyone know of a good way?
Try: #include <bitset> #include <fstream> int main() { using namespace std; const bitset<12> x(2730ul); cout << "x = " << x << endl; ofstream ofs("C:\\test.txt"); // write as txt if (ofs) { // easy way, use the stream insertion operator ofs << x << endl; // using fstream::write() string s = x.to_string(); ofs.write(s.c_str(), s.length()); } return 0; }
778,431
778,531
How do I use C++ in flex and bison?
I have a project for school where we need to use flex and bison. I want to use C++ so that I have access to STL and my own classes that I wrote. We were provided with the following Makefile: CC = gcc CFLAGS = -g OBJs = parse.tab.o symtab.o attr.o lex.yy.o default: parser parser: ${OBJs} ${CC} ${CFLAGS} ${OBJs} -o parser -lfl lex.yy.c: scan.l parse.tab.h attr.h flex -i scan.l parse.tab.c: parse.y attr.h symtab.h bison -dv parse.y parse.tab.h: parse.tab.c clean: rm -f parser lex.yy.c *.o parse.tab.[ch] parse.output depend: makedepend -I. *.c scan.l and parse.y have some initial flex/bison stuff to generate the scanner and parser. I need to add my own stuff to those files. symtab.{h, c} is supposed to be a implementation of a symbol table. attr.{h, c} are for some attribute magic. I want to make symtab.c a .cc file so I can use STL. I also have other reasons for wanting to use C++. I tried to use a parse.ypp file, so that a .cpp file would be generated. But the problem is that I'm not getting the right .h file. I changed the Makefile to look like this: CC = g++ # Change gcc to g++ CFLAGS = -g OBJs = lex.yy.o parse.tab.o symtab.o attr.o default: lex.yy.c parser # added lex.yy.c so I could just keep lex stuff in C since I don't really need C++ there parser: ${OBJs} ${CC} ${CFLAGS} ${OBJs} -o parser -lfl lex.yy.o: scan.l parse.tab.h attr.h # added this rule to use gcc instead of g++ gcc -c -o lex.yy.o lex.yy.c lex.yy.c: scan.l parse.tab.h attr.h flex -i scan.l parse.tab.cpp: parse.ypp attr.h symtab.h bison -dv parse.ypp parse.tab.h: parse.tab.cpp # I want a parse.tab.h but I get parse.tab.hpp clean: rm -f parser lex.yy.c *.o parse.tab.cpp parse.tab.h parse.output depend: makedepend -I. *.c Can someone tell me what I need to add or do to get C++ working? It should be noted I added some stuff in the .y (or .ypp) file to deal with moving from C to C++. In particular, I had to declare some stuff as extern. My main problem is that when I run make, scan.l has a bunch of syntax errors, and they seem to be because it cannot include parse.tab.h (because it is never generated).
You don't need to do anything with flex or bison to use C++, I have done it many times. You just have to make sure you use g++, not gcc. Your problems are with the Makefile, not the code.
778,475
778,605
PInvoke an Array of a Byte Arrays
I have the following C code: const BYTE* Items[3]; Items[0] = item1; Items[1] = item2; Items[2] = item3; int result = Generalize(3, Items); with Generalize having a signature of int __stdcall Generalize(INT count, const BYTE * const * items); What is the best way to make that call with PInvoke?
I can't guarantee this is the best way, but it's the first way I'd try. [DllImport("<unknown>", EntryPoint="Generalize", CallingConvention=CallingConvention.StdCall)] public static extern int Generalize(int count, IntPtr[] items); public static void CallGeneralize() { var itemCount = 3; var items = new IntPtr[itemCount]; items[0] = item1; // where itemX is allocated by Marshal.AllocHGlobal(*) items[1] = item2; items[2] = item3; var result = Generalize(itemCount, items); }
778,802
778,870
C++ Header file that declares a class and methods but not members?
Is it possible to make a C++ header file (.h) that declares a class, and its public methods, but does not define the private members in that class? I found a few pages that say you should declare the class and all its members in the header file, then define the methods separately in you cpp file. I ask because I want to have a class that is defined in a Win32 DLL, and I want it to be properly encapsulated: the internal implementation of that class might change, including its members, but these changes should not affect code that uses the class. I guess that if I had this, then it would make it impossible for the compiler to know the size of my objects ahead of time. But that should be fine, as long as the compiler is smart enough to use the constructor and just pass around pointers to the location in memory where my object is stored, and never let me run "sizeof(MyClass)". Update: Thanks to everyone who answered! It seems like the pimpl idiom is a good way to achieve what I was talking about. I'm going to do something similar: My Win32 DLL file will have a bunch of separate functions like this: void * __stdcall DogCreate(); int __stdcall DogGetWeight(void * this); void __stdcall DogSetWeight(void * this, int weight); This is the typical way the Microsoft writes their DLL files so I think there is probably good reason for it. But I want to take advantage of the nice syntax C++ has for classes, so I'll write a wrapper class to wrap up all of these functions. It will have one member, which will be "void * pimpl". This wrapper class will be so simple that I might as well just declare it AND define it in the header file. But this wrapper class really has no purposes other than making the C++ code look pretty as far as I can tell.
I think what you are looking for is something called the "pimpl idiom". To understand how this works, you need to understand that in C++ you can forward declare something like so. class CWidget; // Widget will exist sometime in the future CWidget* aWidget; // An address (integer) to something that // isn't defined *yet* // later on define CWidget to be something concrete class CWidget { // methods and such }; So to forward declare means to promise to fully declare a type later. Its saying "there will be this thing called a CWidget, I promise. I'll tell you more about it later.". The rules of forward declaration say that you can define a pointer or a reference to something that has been forward declared. This is because pointers and references are really just addresses-a number where this yet-to-be-defined thing will be. Being able to declare a pointer to something without fully declaring it is convenient for a lot of reasons. Its useful here because you can use this to hide some of the internals of a class using the "pimpl" method. Pimpl means "pointer to implementation". So instead of "widget" you have a class that is the actual implementation. The class you are declaring in your header is just a pass-through to the CImpl class. Here's how it works: // Thing.h class CThing { public: // CThings methods and constructors... CThing(); void DoSomething(); int GetSomething(); ~CThing(); private: // CThing store's a pointer to some implementation class to // be defined later class CImpl; // forward declaration to CImpl CImpl* m_pimpl; // pointer to my implementation }; Thing.cpp has CThing's methods defined as pass-throughs to the impl: // Fully define Impl class CThing::CImpl { private: // all variables public: // methods inlined CImpl() { // constructor } void DoSomething() { // actual code that does something } //etc for all methods }; // CThing methods are just pass-throughs CThing::CThing() : m_pimpl(new CThing::CImpl()); { } CThing::~CThing() { delete m_pimpl; } int CThing::GetSomething() { return m_pimpl->GetSomething(); } void CThing::DoSomething() { m_impl->DoSomething(); } tada! You've hidden all the details in your cpp and your header file is a very tidy list of methods. Its a great thing. The only thing you might see different from the template above is that people may use boost::shared_ptr<> or other smart pointer for the impl. Something that deletes itself. Also, keep in mind this method comes with some annoyances. Debugging can be a tad bit annoying (extra level of redirection to step through). Its also a lot of overhead for creating a class. If you do this for every class, you'll get tired of all the typing :).
779,185
779,299
Conflict with DrawText function
I am developing a multi-platform application and in one component I have a class method called DrawText. Unfortunately, I get a linker error (on windows only) saying that there is an unresolved external symbol for a DrawTextW method of this class. I've seen this before with other methods ending in "Text" where it is looking for either a FooTextW or FooTextA method instead of the FooText method I defined. My assumption is that somewhere in the Windows headers there is a macro definition assigning FooText to FooTextW or FooTextA based on some other definition. Aside from renaming my function (which is what I did in the past), does anybody have any good ideas for getting around this issue? Thanks. Joe
Yes, this is a real problem with using Windows, and there's no way to turn it off since the headers all look like this: #ifdef UNICODE #define GetDlgItemText GetDlgItemTextW #else #define GetDlgItemText GetDlgItemTextA #endif So you're going to get the symbol defined either way. It would be very nice if you could #define something before #include'ing windows.h that turns this behavior off, but alas none exists.
779,282
779,297
How far does recursion execute into your function in C++?
I've written recursive functions with the guidance of a friend who is teaching me C++ (as a first language). However, I don't really understand what is going on. He helped me (and the SO community, as well) write a merge sort function. std::vector<int> mergeSort(std::vector<int> original) //code here to create two vectors, farray and sarray, out of the //original std::vector<int> original ; each is half the length, //note: if the size % 2 != 0, sarray takes the odd int farray = mergeSort(farray); sarray = mergeSort(sarray); //code here merges the two into a single, final sorted std::vector In this function, I assign: farray = mergeSort(farray); sarray = mergeSort(sarray); What exactly is happening here? It calls mergeSort with farray and sarray as parameters and changes the value. How far does mergeSort execute into itself recursively? Just upto the recursive function call?
Each time you call a function recursively, it effectively makes a new copy of the information it needs, and goes on. You could have a program that recurs "infinitely", ie, until it runs out of resources, usually stack space — the space in which those copies are going. That would look like void recur(){ recur(); } int main(){ recur(); exit(0); /* won't ever really get here.*/ } Obviously, this isn't very useful, so you want to write a program that has some limit on how often it recurs. Here's a really simple program that manages that: #include <iostream> using namespace std; void recurSome(int count){ cout << "RecurSome called with " << count << endl; if (count > 0){ recurSome(count-1); cout << "Back at " << count << endl; }else{ cout << "Bottom." << endl; } return; } int main(){ recurSome(10); exit(0); /* now it will get here. */ } If you compile and run that, say with: bash $ g++ -Wall -o rc recursome.cpp bash $ ./rc You'll get the results: RecurSome called with 10 RecurSome called with 9 RecurSome called with 8 RecurSome called with 7 RecurSome called with 6 RecurSome called with 5 RecurSome called with 4 RecurSome called with 3 RecurSome called with 2 RecurSome called with 1 RecurSome called with 0 Bottom. Back at 1 Back at 2 Back at 3 Back at 4 Back at 5 Back at 6 Back at 7 Back at 8 Back at 9 Back at 10 bash $ See how it gets called for 10, then 9, and so on, and then after it reaches the bottom, it shows it coming back for 1, then 2, and so on back up to 10? The basic rule is that every recursive function should have something that makes a base case, one which does call itself again. In this one, the base case is count == 0 and in fact we could have written this as a recursive definition recursome: if c = 0 : print bottom if c > 0 : print count, and recursome(c-1) You'll see many recursive definitions of that sort as you move on in math. Here's a somewhat niftier C version with better output: #include <stdio.h> #include <stdlib.h> int max = 10; void recurSome(int count){ printf("RecurSome %*c Called with %d\n", max-count+1, ' ', count); if (count > 0){ recurSome(count-1); printf("RecurSome %*c Back at %d\n", max-count+1, ' ', count); }else{ printf("RecurSome %*c Bottom.\n", 2*max, ' '); printf("RecurSome %*c Back at %d\n", max-count+1, ' ', count); } return; } int main(){ recurSome(max); exit(0); /* now it will get here. */ } Output: RecurSome Called with 10 RecurSome Called with 9 RecurSome Called with 8 RecurSome Called with 7 RecurSome Called with 6 RecurSome Called with 5 RecurSome Called with 4 RecurSome Called with 3 RecurSome Called with 2 RecurSome Called with 1 RecurSome Called with 0 RecurSome Bottom. RecurSome Back at 0 RecurSome Back at 1 RecurSome Back at 2 RecurSome Back at 3 RecurSome Back at 4 RecurSome Back at 5 RecurSome Back at 6 RecurSome Back at 7 RecurSome Back at 8 RecurSome Back at 9 RecurSome Back at 10
779,338
779,353
Suggestions of excellent examples of real C/C++ code
I'd like to study some good C/C++ code. The code should: be good in style and structure, presenting best practices be a real life program (not an example or toy) not too big so it doesn't takes ages to analyse it Windows and/or Unix I know there are 1000s of open source projects out there. But I'd like to hear your suggestions. I am Java programmer and I am curious how good project in c/c++ is structured (files), granularity of classes/functions/files, documentation/comments, build tools etc. Multiple suggestions are welcomed e.g. this is good windows example, that is good pure C etc.
I would specifically mention memcached. It's a great example of fairly short, readable code with a clear purpose. Second, I would recommend the Apache web server. It's a fantastically well-run open source project that you'll learn a lot from, both about the language, as well as general design practices and networking/threading.
779,448
779,475
C or C++ compiler for the Tandy 1000 PC SX?
I have my dad's old PC from the 1980's. It's a Tandy 1000 PC SX: This computer doesn't have a modem, but I have another PC that has Windows XP on it and it also has a 5 3/4 inch floppy drive. So where can I find a C/C++ compiler for this old PC?
Oh my God, I haven't seen one of those in forever. Okay, that's running a version of MS/DOS, no later than about MS/DOS 3 as I recall. First thing is to make sure you can read and write a floppy on the XP computer that the Tandy will read. You'll need to look for a fairly old version of Turbo C, even, I'd guess. You probably should look into the Tiny C Compiler.
779,580
779,611
Equivalent of CppUnit protectors for boost::test?
I've used both CppUnit and boost::test for C++ unittesting. Generally I prefer boost::test, mainly because the auto-test macros minimise the effort to setup tests. But there's one thing I really miss from CppUnit: the ability to register your own "protectors", instances of which automatically wrap all the run tests. (Technically, you install a test "listener", and that can wrap each test in a protector scope). I've found these invaluable in the past for monitoring unittests for unexpected side effects (e.g checking code hasn't changed the floating-point unit state flags). I can't see any equivalent in the boost::test documentation, although BOOST_FIXTURE_TEST_CASE maybe comes closest. Any suggestions for how to best achieve the same thing as CppUnit's protectors in boost::test ? (I haven't really looked into boost::test's implementation yet, but if it's anything like CppUnit it must use something very like protectors itself).
I've never used CppUnit, so not sure how protectors work. Are you looking for something that wraps individual tests, or the entire test suite? For the former, you could use fixtures as you mention, but as I understand it, fixtures should be considered "outside" the test. They set up whatever the test needs, and cleans it up afterwards. Any actual error-testing should be in the test itself, but can be easily implemented with RAII. Simply define a class which checks whatever you need in its destructor, and then create a local instance of it at the beginning of the test. Since it is constructed first, it gets destructed last, so it can easily check that the test hasn't modified any unexpected state. If you want it to check this after all the tests have executed, you probably want global fixtures
779,791
779,882
Performance: vector of classes or a class containing vectors
I have a class containing a number of double values. This is stored in a vector where the indices for the classes are important (they are referenced from elsewhere). The class looks something like this: Vector of classes class A { double count; double val; double sumA; double sumB; vector<double> sumVectorC; vector<double> sumVectorD; } vector<A> classes(10000); The code that needs to run as fast as possible is something like this: vector<double> result(classes.size()); for(int i = 0; i < classes.size(); i++) { result[i] += classes[i].sumA; vector<double>::iterator it = find(classes[i].sumVectorC.begin(), classes[i].sumVectorC.end(), testval); if(it != classes[i].sumVectorC.end()) result[i] += *it; } The alternative is instead of one giant loop, split the computation into two separate loops such as: for(int i = 0; i < classes.size(); i++) { result[i] += classes[i].sumA; } for(int i = 0; i < classes.size(); i++) { vector<double>::iterator it = find(classes[i].sumVectorC.begin(), classes[i].sumVectorC.end(), testval); if(it != classes[i].sumVectorC.end()) result[i] += *it; } or to store each member of the class in a vector like so: Class of vectors vector<double> classCounts; vector<double> classVal; ... vector<vector<double> > classSumVectorC; ... and then operate as: for(int i = 0; i < classes.size(); i++) { result[i] += classCounts[i]; ... } Which way would usually be faster (across x86/x64 platforms and compilers)? Are look-ahead and cache lines are the most important things to think about here? Update The reason I'm doing a linear search (i.e. find) here and not a hash map or binary search is because the sumVectors are very short, around 4 or 5 elements. Profiling showed a hash map was slower and a binary search was slightly slower.
As lothar says, you really should test it out. But to answer your last question, yes, cache misses will be a major concern here. Also, it seems that your first implementation would run into load-hit-store stalls as coded, but I'm not sure how much of a problem that is on x86 (it's a big problem on XBox 360 and PS3).
780,027
780,097
Why are many VMs written in C when they look like they have C++ features?
I noticed some not so old VM languages like Lua, NekoVM, and Potion written in C. It looked like they were reimplementing many C++ features. Is there a benefit to writing them in C rather than C++?
I know something about Lua. Lua is written in pure ANSI Standard C and compiles on any ANSI platform with no errors and no warnings. Thus Lua runs on almost any platform in the world, including things like Canon PowerShot cameras. It's a lot harder to get C++ to run on weird little embedded platforms. Lua is a high-performance VM, and because C cannot express method calls (which might be virtual or might not) and operator overloading, it is much easier to predict the performance of C code just by looking at the code. C++, especially with the template library, makes it a little too easy to burn resources without being aware of it. (A full implementation of Lua including not only VM but libraries fits in 145K of x86 object code. The whole language fits even in a tiny 256K cache, which you find at L2 on Intel i7 and L1 on older chips. Unless you really know what you're doing, it's much harder to write C++ that compiles to something this small.) These are two good reasons to write a VM in C.
780,041
780,044
Confusion about UDP/IP and sendto/recvfrom return values
I'm working with UDP sockets in C++ for the first time, and I'm not sure I understand how they work. I know that sendto/recvfrom and send/recv normally return the number of bytes actually sent or received. I've heard this value can be arbitrarily small (but at least 1), and depends on how much data is in the socket's buffer (when reading) or how much free space is left in the buffer (when writing). If sendto and recvfrom only guarantee that 1 byte will be sent or received at a time, and datagrams can be received out of order, how can any UDP protocol remain coherent? Doesn't this imply that the bytes in a message can be arbitrarily shuffled when I receive them? Is there a way to guarantee that a message gets sent or received all at once?
It's a little stronger than that. UDP does deliver a full package; the buffer size can be arbitrarily small, but it has to include all the data sent in the packet. But there's also a size limit: if you want to send a lot of data, you have to break it into packets and be able to reassemble them yourself. It's also no guaranteed delivery, so you have to check to make sure everything comes through. But since you can implement all of TCP with UDP, it has to be possible. usually, what you do with UDP is you make small packets that are discrete. Metaphorically, think of UDP like sending postcards and TCP like making a phone call. When you send a postcard, you have no guarantee of delivery, so you need to do something like have an acknowledgement come back. With a phone call, you know the connection exists, and you hear the answers right away.
780,156
780,230
Cross-platform memory allocator sbrk/virtualalloc
I am wondering if there is a cross-platform allocator that is one step lower than malloc/free. For example, I want something that would simply call sbrk in Linux and VirtualAlloc in Windows (There might be two more similar syscalls, but its just an example).
I'm not familiar with the functions in question but: #if defined (__WIN32__) #define F(X) VirtualAlloc(X) #elif defined (__LINUX__) /* or whatever linux's define is */ #define F(X) sbrk(X) #endif Not sure if the syntax is 100% (I'm new to macros & c), but the general idea should work.
780,283
780,293
Is Int32^ i = gcnew Int32() allocated on managed heap?
Basically I would like to know the difference between Int32^ i = gcnew Int32(); and Int32* i2 = new Int32(); I have written the following code: #include <stdio.h> #using <mscorlib.dll> using namespace System; int main(void) { Int32^ i = gcnew Int32(); Int32* i2 = new Int32(); printf("%p %d\n", i2, *i2); printf("%p %d\n", i, *i); return 0; } It gives the following output: 004158B8 0 00E1002C 0 It seems the two integer are allocated in two different memory locations. Is the gcnew Int32() allocated in managed heap? or directly on the stack?
In managed C++ new allocates on unmanaged heap, gcnew - on managed heap. Objects in the managed heap are eligible for garbage collection, while objects in the unmanaged heap are not. Pointers with ^ work like C# references - the runtime tracks them and uses for garbage collection, pointers with * work like normal C++ pointers.
780,349
780,383
Runtime optimization of static languages: JIT for C++?
Is anyone using JIT tricks to improve the runtime performance of statically compiled languages such as C++? It seems like hotspot analysis and branch prediction based on observations made during runtime could improve the performance of any code, but maybe there's some fundamental strategic reason why making such observations and implementing changes during runtime are only possible in virtual machines. I distinctly recall overhearing C++ compiler writers mutter "you can do that for programs written in C++ too" while listening to dynamic language enthusiasts talk about collecting statistics and rearranging code, but my web searches for evidence to support this memory have come up dry.
Profile guided optimization is different than runtime optimization. The optimization is still done offline, based on profiling information, but once the binary is shipped there is no ongoing optimization, so if the usage patterns of the profile-guided optimization phase don't accurately reflect real-world usage then the results will be imperfect, and the program also won't adapt to different usage patterns. You may be interesting in looking for information on HP's Dynamo, although that system focused on native binary -> native binary translation, although since C++ is almost exclusively compiled to native code I suppose that's exactly what you are looking for. You may also want to take a look at LLVM, which is a compiler framework and intermediate representation that supports JIT compilation and runtime optimization, although I'm not sure if there are actually any LLVM-based runtimes that can compile C++ and execute + runtime optimize it yet.
780,448
784,814
Debugging embedded Lua
How do you debug lua code embedded in a c++ application? From what I gather, either I need to buy a special IDE and link in their special lua runtime (ugh). Or I need to build a debug console in to the game engine, using the lua debug API calls. I am leaning toward writing my own debug console, but it seems like a lot of work. Time that I could better spend polishing the other portions of the game.
There are several tools floating around that can do at least parts of what you want. I have seen references to a VS plugin, there is a SciTE debugger extension in Lua for Windows, and there is the Kepler project's RemDebug, as well as their LuaEclipse. RemDebug may be on the track of what you need, as it was built to allow for debugging CGI scripts written in Lua. It does require access to the LuaSocket module to provide a communications channel between the target script and a controller as well as a couple of other modules. A bigger issue might be the ability to load arbitrary modules from within whatever sandbox the game engine has put around your scripts. If you have some control over the engine, then that won't be as big an issue. This isn't currently possible for developers of Adobe Lightroom plugins, for example, because Lightroom does not expose require inside the plugin's sandbox. A surprise to me has been how rarely I have felt a need for a debugger when working with Lua. I've built several small applications in it for various projects and have been surprised at how well a combination of complete stack backtraces and the occasional print call works to locate the bugs that require "strict" didn't prevent in the first place.
780,580
780,608
Why this sample works?
typedef pair<double, double> dd; const double epsilon = 1e-6; struct sort_by_polar_angle { dd center; // Constuctor of any type // Just find and store the center template<typename T> sort_by_polar_angle(T b, T e) { int count = 0; center = dd(0,0); while(b != e) { center.first += b->first; center.second += b->second; b++; count++; } double k = count ? (1.0/count) : 0; center.first *= k; center.second *= k; } // Compare two points, return true if the first one is earlier // than the second one looking by polar angle // Remember, that when writing comparator, you should // override not ‘operator <’ but ‘operator ()’ bool operator () (const dd& a, const dd& b) const { double p1 = atan2(a.second-center.second, a.first-center.first); double p2 = atan2(b.second-center.second, b.first-center.first); return p1 + epsilon < p2; } }; // ... vector < dd > points; sort(all(points), sort_by_polar_angle(all(points))); When sort_by_polar_angle() is called, is it function as a construnctor? How the overloaded operator () correctly used?
When you call sort_by_polar_angle() in the sort() function, you are creating a temporary object of type sort_by_polar_angle (i.e. its constructor is called). Inside the sort algorithm, the functor object you passed is used something like functor() which will be translated into functor.operator().
780,730
780,733
C/C++: Static function in header file, what does it mean?
I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
Is the function defined in the header file? So that the actual code is given directly in the function, like this: static int addTwo(int x) { return x + 2; } Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea. Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file. UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even: static inline int addTwo(int *x) { __add_two_superquickly(x); } Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro. The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.
780,805
780,818
Populate a static member container in c++
I've got a static class member which is some container, like (Foo.h) class Foo { ... private: static list<string> s_List; } I need to populate the list with a number of specific values. Actually it should be also const, but that might overcomplicate the problem further. All the class member functions are static, so initializing it in a constructor doesn't make sense.
a common solution is to do something like this: // header class Foo { ... private: static list<string> s_List; } // cpp list<string> init() { list<string> tmp; ... fill tmp with strings return tmp; } list<string> Foo::s_List(init()); the other method is like Neil Butterworth suggested.
781,001
781,383
What is the typical usage of boost any library?
What are the advantages of using boost.any library ? Could you please give me some real life examples ? Why the same functionality couldn't be achieved by having some generic type in the root of object's hierarchy and creating containers with that base type ?
I consider that Boost.Variant should always be preferred as it's non-intrusive and still calls for very structured programming. But i guess the main idea behind boost.any is to provide the equivalent of java and c# object types. It's a way of saying "yes we can" ! :-)
781,246
781,615
Wrapping a 3rd party DLL
I have a 3rd party DLL that needs to be loaded dynamically using LoadLibrary() and which uses the __cdecl calling convention. I need to be able to use the dll from VB6 so I've created a wrapper DLL of my own that uses the __stdcall calling convention and exports the functions that are needed. An additional requirement has now arrived and I am struggling to see how to manage; the wrapped DLL provides an API to another application and I need to connect to two instances of the application concurrently. This is a problem as the DLL has no concept of a session, a typical interaction would like like this: tpc_connect("service1") // Do some stuff tpc_disconnect() and what i need to be able to do is session1 = tpc_connect("service1") session2 = tpc_connect("service2") // Do some stuff with session1 // Do some stuff with session2 tpc_disconnect(session1) tpc_disconnect(session2) The main problem as I see it is that a single process can only be conected to one service, so the first solution I tried was to move the DLL wrapper out to a seperate process by creating an Out-Of-Process COM server using ATL. The problem I now have is that I only get a single instance of the COM sever. So my questions (finally) are is there a way to force a new instance of the ATL COM server to be created? Is this the best approach to the problem or can someone think of a better way to tackle this. Thanks Jackson
I suggest that you dump the COM server idea and go with copies of the original DLL. I have used this approach myself to get multiple instances of libraries that aren't threadsafe and don't support multiple instances. Since the files are different, Windows will load them all into separate address spaces and thus keep them separated for you. This is what I did: Add functions to the wrapper to create and destroy instances of the library. Change all other functions to take a pointer to the instance of the library that it is using. In the create instance function, first attempt to make a hard link to the original DLL using a random file name (i.e. use CreateHardLink). If that fails, then make a true copy of the DLL using a random name. You don't need to use the DLL extension if you don't want to. Dynamically load that copy of the DLL and function pointers and return a pointer to your internal structure. In the destroy function, just unload the DLL and delete it. Best to create the copy in the temporary directory so that it is obvious that it can be removed in event of a crash, although I am not sure if there are restrictions in Vista and later on loading DLLs from the temp dir. This all works perfectly for me.
781,256
781,375
Implementing zoom controls in MFC
I am working on a 'print preview' facility to show an overview of a slide with rectangular arrays of sample spots on it. The slides typically measure 25 x 75 mm and the spot samples are typically 0.1 mm in diameter. There is usually a 2mm gap around the perimeter of the slide where no spots are printed. The distance between spots (pitches) is accurate to 0.01mm. Pitches of 0.20 and 0.29 mm for example would need to differentiated in the pixels. Representing the spots themselves, 100% accuracy is probably not crucial at this stage as long as the spots are visible and don't overlap. I would appreciate advice on what techniques to use in order to create a bitmap representation of the slide/spots and to view the slide layout using arbitrary levels of magnification. This does not have to be sophisticated - a 1:1 representation plus a smaller and larger magnification to start with. I probably cannot zoom out too much as the spots will become too small to be represented. For larger magnifications I will probably need to know about implementing horizontal / vertical scroll controls as well, but I will tackle this later. I would like to find out about any programming and scaling techniques that I should be aware of in order to properly implement a zoom facility. I have recently been playing with the StretchBlt function to alter image sizes and it seems ok, however any other relevant information would be useful. Cheers.
Let's start from the beginning: why aren't you using ::AFXPrintPreview() and the rest of the print preview facilities of MFC? 'slides' and 'spots' are specific to your industry I think - are they relevant to the question or is it just for illustration? StretchBlt() isn't going to do you much good because it will only let you do pixel-level 'zooming', what you need is to draw a certain part of your control with a higher level of precision. Even if you're not going to use the MFC print preview stuff, have a look at it to see how it can be done. Windows control have all the functionality you need for scrolling and scaling. They are in the device context: SetWindowExt(), SetViewportExt(), SetViewportOrg() etc. Look under 'Coordinate Functions' of the 'CDC Members' page of MSDN. That being said, I have once implemented zooming and scrolling 'manually', by keeping track of the scrollbar position, zooming commands of my control, etc. It was a pain in the ass and looking back, I should have used the Windows facilities. They aren't easy to use either, though, that why I thought I could do it better myself in the first place - turns out I was wrong :) Finally, although I can't tell for sure from your question if you're really in that boat, don't think in terms of physical distances (millimeters etc). The first thing you want to get right is to draw the shape onto the screen, with the right proportions between the elements. Then you want to zoom in/out. Finally, it's only when you get to the printing part that physical measures come into play. The only thing you need to figure out there (slightly simplifying here) is 'what is the correct zoom ratio I need to get the required output'. This is a bit tricky but has very little to do with what seems to be the first part of your question (how to draw your component to the screen). If you're having troubles, don't hesitate to post more specific questions. I have print preview and printing code here as an example of the 'generic' parts of the printing process, although the specifics are obviously different for every application.
781,494
783,729
How do a specify a library file dependency for qmake in Qt?
Have a SomeLib.pro file that contains: CONFIG += debug TEMPLATE = lib TARGET = SomeLib .. Then in a dependent SomeApp.pro: .. debug:LIBS += -lSomeLib_debug .. How can I force SomeApp to build if I touched SomeLib in qmake?
It's ugly because you need to give the exact library file name, but this should work: TARGETDEPS += libfoo.a
781,533
781,649
Weird linker error on Borland C++ Builder 6
I've been trying to compile a Borland C++ Builder 6 project, but linker dies with exact following error: [Linker Fatal Error] Fatal: Unable to open file '.OBJ' Strange thing about it is that it doesn't give any file name except the extension. It looks like an internal bug, though googling for it didn't give any results. Has anyone encountered this error? == SOLVED == It was actually an invalid compiler directive in one of the sourcefiles which caused linker command line to be corrupted. Thanks for help.
Check for illegal whitespace characters in your Linker command line. If you don't find any, post your linker command line here (Off the top of my head found in Project -> Options -> Linker -> Command Line).
781,760
781,785
Copy constructor with pointers
I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor. To learn that, I have made the following simple code. It compiles, but gives me runtime error when performing the copy constructor. I am trying to copy just the value from the pointer of the copied object, but avoiding assigning the same address. So, what's wrong here? class TRY{ public: TRY(); ~TRY(); TRY(TRY const &); int *pointer; void setPointer(int); }; void TRY::setPointer(int a){ *pointer = a; return; } TRY::TRY(){} TRY::~TRY(){} TRY::TRY(TRY const & copyTRY){ int a = *copyTRY.pointer; *pointer = a; } int main(){ TRY a; a.setPointer(5); TRY b = a; b.setPointer(8); cout << "Address of object a = " << &a << endl; cout << "Address of object b = " << &b << endl; cout << "Address of a.pointer = " << a.pointer << endl; cout << "Address of b.pointer = " << b.pointer << endl; cout << "Value in a.pointer = " << *a.pointer << endl; cout << "Value in b.pointer = " << *b.pointer << endl; return 0; } I'll be using this concept for other classes with lots of pointers in it, where I need to copy all values from on object to the other. Copying is initially necessary for this code, so I would like to keep the copying possibility (I won't be hiding the copy constructor as private). Besides, the real class I need to implement has like 10 pointers, and it might be changing with time. Isn't there a somewhat smarter way to have a deep copy constructor in C++?...
With the statement int* pointer you have just defined a pointer but has not allocated any memory. First you should make it point to a proper memory location by allocating some memory like this: int* pointer = new int. Then in the copy constructor again you have to allocate the memory for the copied object. Also, don't forget to release the memory using delete in the destructor. I hope this example helps: class B { public: B(); B(const B& b); ~B(); void setVal(int val); private: int* m_p; }; B::B() { //Allocate the memory to hold an int m_p = new int; *m_p = 0; } B::B(const B& b) { //Allocate the memory first m_p = new int; //Then copy the value from the passed object *m_p = *b.m_p; } B::~B() { //Release the memory allocated delete m_p; m_p = NULL; } void B::setVal(int val) { *m_p = val; }
781,792
781,851
How do I debug a single .cpp file in Visual Studio?
Is there any way to debug a single file in Visual Studio.NET? I'm still a noob with C++, but I want to start learning how to get comfortable with the debugger, and as of right now I am writing really small files. It seems if there is only one source file, it won't let me debug, but the moment I add another one, I can. I am using VS.net 2008.
It doesn't want another source file, it wants a project file. Visual Studio needs a bunch of information to know how to compile and debug your source code. Things like which optimization settings to use, where to look for the boost headers, that sort of thing. Try this: go to File->New->Project... and pick a win32 console application. In the next wizard, go to Application Settings, and check "Empty Project", and hit OK. Now you have empty project and solution files which you can copy/paste wherever you want them; to debug, just open the .sln file, drag in your single .cpp file, and hit F5.
781,907
781,924
Generating object file to separate directory using g++ compiler - C++
I use the following code to compile a cpp file to object file. g++ -c main.cpp Above code generates the .o fles in same directory where main.cpp resides. Suppose I have a folder named obj and need to generate the object files there, how could I write it? How can I see the compiler switches supported by g++ and it's usages? Any help would be great
Suppose I have a folder named obj and need to generate the object files there, how do I write? Use: g++ -c main.cpp -o obj/main.o How can I see the compiler switches supported by g++ and it's usages? If you are on a *nix system use: man g++ or use info g++
782,316
782,369
C++ HTML generation classes
A question prompted by jbar's question. In scripting languages like Python, Ruby, and Perl, there are libraries that simplify generating dynamic HTML. (For example, the cgi module in Ruby.) Are there any similar packages for C++? I don't know of one, and at least some desultory googling didn't reveal one.
http://www.webtoolkit.eu/wt#/ I don't know anything about it, but their web-page is clean and the introduction sounds like exactly what you're looking for... Wt (pronounced 'witty') is a C++ library and application server for developing and deploying web applications. It is not a 'framework', which enforces a way of programming, but a library. ... In contrast, a web application developed with Wt is written in only one compiled language (C++), from which the library generates the necessary HTML/XHTML, Javascript, CGI, SVG/VML/Canvas and AJAX code.
782,955
782,983
getting XML data from Xerces (c++)
I am a latecomer to XML - have to parse an XML file. Our company is using xerces already so I managed to cobble together a sample app (SAX) that displays all the data in a file. However, after parsing is complete I was expecting to be able to call the parser or some other entity that had an internal representation of the file and iterate through the fields/data. Basically I want to be able to hand it some key or other string(s) and get back strings or collections of key/value pairs. I do not see that. It seems pretty obvious to me that that is a good thing to do. Am I missing something? Is the DOM parsing what I want, or does that fall short too?
Xerces provides both SAX and DOM processing. SAX parsing doesn't construct a model, so once parsing is finished there is nothing to examine or iterate through. DOM processing produces a tree-structured model which gives you what you want.
783,018
783,953
Howto elegantly extract a 2D rectangular region from a C++ vector
The problem is pretty basic. (I am puzzled why the search didn't find anything) I have a rectangular "picture" that stores it's pixel color line after line in a std::vector I want to copy a rectangular region out of that picture. How would I elegantly code this in c++? My first try: template <class T> std::vector<T> copyRectFromVector(const std::vector<T>& vec, std::size_t startx, std::size_t starty, std::size_t endx, std::size_t endy, std::size_t fieldWidth, std::size_t fieldHeight) { using namespace std; vector<T> ret((endx-startx)*(endy-starty)+10); // 10: chickenfactor // checks if the given parameters make sense: if (vec.size() < fieldWidth*endy) { cerr << "Error: CopyRectFromVector: vector to small to contain rectangular region!" << std::endl; return ret; } // do the copying line by line: vector<T>::const_iterator vecIt = vec.begin(); vector<T>::forward_iterator retIt = ret.end(); vecIt += startx + (starty*fieldWidth); for(int i=starty; i < endy; ++i) { std::copy(vecIt, vecIt + endx - startx, retIt); } return ret; } does not even compile..... Addit: Clarification: I know how to do this "by hand". It is not a problem as such. But I would love some c++ stl iterator magic that does the same, but faster and... more c++ stylish. Addition: I give the algorithm the pictureDataVector, the width and height of the picture and a rectangle denoting the region that I want to copy out of the picture. The return value should be a new vector with the contents of the rectangle. Think of it as opening your favorite image editor, and copy a rectangular region out of that. The Picture is stored as a long 1D array(vector) of pixelcolors.
Your question asks for a C++ way of copying a rectangular field of elements in some container. You have a fairly close example of doing so and will get more in the answers. Let's generalize, though: You want an iterator that travels a rectangular range of elements over some range of elements. So, how about write a sort of adapter that sits on any container and provides this special iterator. Gonna go broad strokes with the code here: vector<pixels> my_picture; point selTopLeft(10,10), selBotRight(40, 50); int picWidth(640), picHeight(480); rectangular_selection<vector<pixels> > selection1(my_picture.begin(), my_picture.end(), picWidth, picHeight, selTopLeft, selBotRight); // Now you can use stl algorithms on your rectangular range vector<pixels> rect_copy = std::copy(selection1.begin(), selection1.end()); // or maybe you don't want to copy, you want // to modify the selection in place std::for_each (selection1.begin(), selection1.end(), invert_color); I'm sure this is totally do-able, but I'm not comfortable coding stl-style template stuff off-the-cuff. If I have some time and you're interested, I may re-edit a rough-draft later, since this is an interesting concept. See this SO question's answer for inspiration.
783,073
783,095
Processing messages is too slow, resulting in a jerky, unresponsive UI - how can I use multiple threads to alleviate this?
I'm having trouble keeping my app responsive to user actions. Therefore, I'd like to split message processing between multiple threads. Can I simply create several threads, reading from the same message queue in all of them, and letting which ever one is able process each message? If so, how can this be accomplished? If not, can you suggest another way of resolving this problem?
You cannot have more than one thread which interacts with the message pump or any UI elements. That way lies madness. If there are long processing tasks which can be farmed out to worker threads, you can do it that way, but you'll have to use another thread-safe queue to manage them.
783,212
783,242
Find QWidget of single instance Qt application
I'm trying to create a single instance Qt application and I'm at the point this works, but now I want to focus the already started instance when a second is started. QWidget::find(g_hWnd) should return the widget but it fails and crashes on w->show(); Any thoughts? #pragma data_seg("Shared") HWND g_hWnd = NULL; #pragma data_seg() #pragma comment(linker,"/section:Shared,rws") int main(int argc, char *argv[]) { if (g_hWnd) { QWidget* w = QWidget::find(g_hWnd); w->show(); return 0; } else { QApplication a(argc, argv); mainWindow w; w.show(); g_hWnd = a.topLevelWidgets().at(0)->winId(); //or w.winId()? return a.exec(); } } edit: I now see Trolltech released the QtSingleApplication class under LGPL.
You should use the qtsingleapplication API edit- It's a separate download see here for both LGPL and Commercial editions
783,260
787,833
How can I use a User Defined Type (UDT) in a COM server?
I have a COM server with a method currently returning an integer: [ object, uuid("..."), dual, helpstring("IMyCOMServer Interface"), pointer_default(unique) ] __interface IMyCOMServer : IDispatch { [id(1), helpstring("method MyQuery")] HRESULT MyQuery([in] BSTR instr, [out,retval] int* outint); }; This compiles fine, but I'd rather return an enum: (this code is actually above the interface definition) typedef [ uuid("..."), v1_enum, helpstring("Enum") ] enum { value_a, value_b, value_c } MyEnum; Which again compile fine of its own right, but as soon as I change the int* to MyEnum* in the interface and implementation, I get linker errors: [id(1), helpstring("method MyQuery")] HRESULT MyQuery([in] BSTR instr, [out,retval] MyEnum* outint); error MIDL2025 : syntax error : expecting a type specification near "MyEnum" Whichever way I do it, I can't get it to compile. Thanks to Euro Micelli it turns out that the real problem is that my User Defined Type (the enum) wasn't making it into the generated .IDL file. Judging by forum queries online, this seems to be a common problem. A blog article Star Tech: UDT (User Defined Types) and COM guided me down the right path. It seems that a workaround is needed when using attributed ATL. In summary, I made the following changes: Created udt.idl: import "oaidl.idl"; import "ocidl.idl"; [ uuid("..."), v1_enum, helpstring("Enum") ] typedef enum MyEnum { value_a, value_b, value_c } MyEnum_t; [ version(1.0), uuid(...), helpstring(...) ] library MyLibrary { enum MyEnum; } Added the following line prior to the module attribute in the main .cpp file so that the above IDL gets imported into the generated file: [importidl("udt.idl")];
(This is adapted from an actual IDL, so I know it works) [uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX), v1_enum, helpstring("Enum")] enum MyEnum { value_a, value_b, value_c } ; Plus, in your Library section you must include the enum as well, or the enum won't be exported to the type library: library MyLib { enum MyEnum; ... };
783,310
783,314
Are there any tools to detect buffer overflow on Visual C++ 6.0?
I've been having crash problems due to heap problems, so I guess a buffer overflow is happening somewhere. How do I detect it?
I use Compuware BoundsChecker as a tool for error detection in VC6. It can pick up buffer overruns. You can also try PageHeap, a tool for windows.
783,354
783,664
Windows forms control library; Managed and Unamanaged
The windows forms control library project (C++) I writes uses an unmanaged dll. The unmanaged dll has a header file (a Cheshire cat). And I just include it in the control library project. And calls functions in the unmanaged dll (of course with proper marshaling). This compiles and builds. The problem is when I go ahead to add the control to the tool box of my scaffolding, which is a Managed C++ winform application, VS2005 complains that it is not a .Net module. I have seen people converting using MFC dlls as windows forms controls. What am I doing wrong?.
Maybe it's because VS2005 does not find your native .DLL. This .DLL is searched in the "normal" manner for native .DLLs: Current directory (I think it is mostly the start-up dir of VS) App direcotry (somewhere in %ProgramFiles%\Microsoft Visual Studio...) %PATH% dirs. You could try to put your native DLL somewhere in the above mentioned dirs and try if you get better results. I would absolutely recommend to make your native part static and statically link it into your .NET project (if that is possible) because it would avoid the native .DLL finding problem. (This is what I did because of the many problems. For example we have a Translator tool [SDL Passolo] that can handle .NET DLLs and pack them into translator packages including all referenced DLLs...but only .NET DLLs but not native DLLs!).
783,592
783,616
SQLite3 object not understood?
Now I'm geting an error: 1>c:\development\document_manager\document_manager\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sqlite3' with #pragma once #include "sqlite3.h" class storage_manager { sqlite3 db; sqlite3** db_pp; public: void open() { sqlite3_open("data.db", db_pp); } }; Old Question: Hi everyone. I downloaded sqlite-amalgamation-3_6_13.zip from http://www.sqlite.org/download.html, but I'm not able to compile it in my project. I receive many errors like: c:\pathtoproject\sqlite3.c(11337) : error C2440: '=' : cannot convert from 'void *' to 'char *' Conversion from 'void*' to pointer to non-'void' requires an explicit cast c:\pathtoproject\sqlite3.c(12023) : error C2440: '=' : cannot convert from 'void *' to 'sqlite3_int64 *' Conversion from 'void*' to pointer to non-'void' requires an explicit cast What do I need to do to compile my project properly? Thanks! Edit: I don't want to compile the whole program as C, I just want to compile three files as c, is this possible? EDIT: FIXED! I created an new project.
It looks like you might be trying to compile a C program using a C++ compiler. While there is a lot of C code which is also valid C++, they are different languages. Your compiler may have some switch or setting to compile C code. Check your compiler documentation.
783,623
1,121,397
Boost, Shared Memory and Vectors
I need to share a stack of strings between processes (possibly more complex objects in the future). I've decided to use boost::interprocess but I can't get it to work. I'm sure it's because I'm not understanding something. I followed their example, but I would really appreciate it if someone with experience with using that library can have a look at my code and tell me what's wrong. The problem is it seems to work but after a few iterations I get all kinds of exceptions both on the reader process and sometimes on the writer process. Here's a simplified version of my implementation: using namespace boost::interprocess; class SharedMemoryWrapper { public: SharedMemoryWrapper(const std::string & name, bool server) : m_name(name), m_server(server) { if (server) { named_mutex::remove("named_mutex"); shared_memory_object::remove(m_name.c_str()); m_segment = new managed_shared_memory (create_only,name.c_str(),65536); m_stackAllocator = new StringStackAllocator(m_segment->get_segment_manager()); m_stack = m_segment->construct<StringStack>("MyStack")(*m_stackAllocator); } else { m_segment = new managed_shared_memory(open_only ,name.c_str()); m_stack = m_segment->find<StringStack>("MyStack").first; } m_mutex = new named_mutex(open_or_create, "named_mutex"); } ~SharedMemoryWrapper() { if (m_server) { named_mutex::remove("named_mutex"); m_segment->destroy<StringStack>("MyStack"); delete m_stackAllocator; shared_memory_object::remove(m_name.c_str()); } delete m_mutex; delete m_segment; } void push(const std::string & in) { scoped_lock<named_mutex> lock(*m_mutex); boost::interprocess::string inStr(in.c_str()); m_stack->push_back(inStr); } std::string pop() { scoped_lock<named_mutex> lock(*m_mutex); std::string result = ""; if (m_stack->size() > 0) { result = std::string(m_stack->begin()->c_str()); m_stack->erase(m_stack->begin()); } return result; } private: typedef boost::interprocess::allocator<boost::interprocess::string, boost::interprocess::managed_shared_memory::segment_manager> StringStackAllocator; typedef boost::interprocess::vector<boost::interprocess::string, StringStackAllocator> StringStack; bool m_server; std::string m_name; boost::interprocess::managed_shared_memory * m_segment; StringStackAllocator * m_stackAllocator; StringStack * m_stack; boost::interprocess::named_mutex * m_mutex; }; EDIT Edited to use named_mutex. Original code was using interprocess_mutex which is incorrect, but that wasn't the problem. EDIT2 I should also note that things work up to a point. The writer process can push several small strings (or one very large string) before the reader breaks. The reader breaks in a way that the line m_stack->begin() does not refer to a valid string. It's garbage. And then further execution throws an exception. EDIT3 I have modified the class to use boost::interprocess::string rather than std::string. Still the reader fails with invalid memory address. Here is the reader/writer //reader process SharedMemoryWrapper mem("MyMemory", true); std::string myString; int x = 5; do { myString = mem.pop(); if (myString != "") { std::cout << myString << std::endl; } } while (1); //while (myString != ""); //writer SharedMemoryWrapper mem("MyMemory", false); for (int i = 0; i < 1000000000; i++) { std::stringstream ss; ss << i; //causes failure after few thousand iterations //ss << "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" << i; //causes immediate failure mem.push(ss.str()); } return 0;
There are several things that leaped out at me about your implementation. One was the use of a pointer to the named mutex object, whereas the documentation of most boost libraries tends to bend over backwards to not use a pointer. This leads me to ask for a reference to the program snippet you worked from in building your own test case, as I have had similar misadventures and sometimes the only way out was to go back to the exemplar and work forward one step at a time until I come across the breaking change. The other thing that seems questionable is your allocation of a 65k block for shared memory, and then in your test code, looping to 1000000000, pushing a string onto your stack each iteration. With a modern PC able to execute 1000 instructions per microsecond and more, and operating systems like Windows still doling out execution quanta in 15 millisecond. chunks, it won't take long to overflow that stack. That would be my first guess as to why things are haywire. P.S. I just returned from fixing my name to something resembling my actual identity. Then the irony hit that my answer to your question has been staring us both in the face from the upper left hand corner of the browser page! (That is, of course, presuming I was correct, which is so often not the case in this biz.)
783,864
783,889
std::map<tstring<std::map<tstring, unsigned int>> assignment fail
basically i have (state, state code) pairs, that are subsets of country [USA] -> [VT] -> 32 so i'm using std::map<tstring<std::map<tstring, unsigned int>> but i'm having trouble with assignment of the state code for(std::map<tstring, std::map<tstring, unsigned int>>::const_iterator it = countrylist.begin(); it != countrylist.end(); ++it) { foundCountry = !it->first.compare(_T("USA")); //find USA if(foundCountry) it->second[_T("MN")] = 5; //Assignment fails } error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>'
operator[] on std::map is non-const, because it creates the entry if it doesn't already exist. So you can't use a const_iterator in this way. You can use find() on const maps, but that still won't let you modify their values. And Smashery is right, you're doing the first lookup in a strange way considering that you have a map. Since you're clearly modifying the thing, what's wrong with this? countryList[_T("USA")][_T("MN")] = 5;
783,944
784,328
How do I allocate a std::string on the stack using glibc's string implementation?
int main(void) { std::string foo("foo"); } My understanding is that the above code uses the default allocator to call new. So even though the std::string foo is allocated on the stack the internal buffer inside of foo is allocated on the heap. How can I create a string that is allocated entirely on the stack?
I wanted to do just this myself recently and found the following code illuminating: Chronium's stack_container.h It defines a new std::allocator which can provide stack-based allocation for the initial allocation of storage for STL containers. I wound up finding a different way to solve my particular problem, so I didn't actually use the code myself, but perhaps it will be useful to you. Do be sure to read the comments in the code regarding usage and caveats. To those who have questioned the utility and sanity of doing this, consider: Oftentimes you know a priori that your string has a reasonable maximum size. For example, if the string is going to store a decimal-formatted 32-bit integer,you know that you do not need more than 11 characters to do so. There is no need for a string that can dynamically grow to unlimited size in that case. Allocating from the stack is faster in many cases than allocating from the heap. If the string is created and destroyed frequently (suppose it is a local variable in a commonly used utility function), allocating from the stack instead of the heap will avoid fragmentation-inducing churn in the heap allocator. For applications that use a lot of memory, this could be a game changer. Some people have commented that a string that uses stack-based allocation will not be a std::string as if this somehow diminishes its utility. True, you can't use the two interchangeably, so you won't be able to pass your stackstring to functions expecting a std::string. But (if you do it right), you will be able to use all the same member functions on your stackstring that you use now on std::string, like find_first_of(), append(), etc. begin() and end() will still work fine, so you'll be able to use many of the STL algorithms. Sure, it won't be std::string in the strictest sense, but it will still be a "string" in the practical sense, and it will still be quite useful.
784,247
784,278
How can I make my mouse control the camera like a FPS using OpenGL/SDL?
I've created this basic 3D Demo using OpenGL/SDL. I handled the keyboard callback so I can "strafe" left and right using 'a' and 's' and move forward and backward using 's' and 'w'. However, I would like to now make it so I can control the direction my camera is "looking" based off my mouse movements. Just like in a FPS shooter when you move the mouse around it makes the camera look around in various directions. Does anyone have any idea how I could utilize the mouse callbacks to "points" the camera class correctly when I move the mouse? #include "SDL.h" #include "Camera.h" Camera cam; Scene scn; //<<<<<<<<<<<<<<<<<myKeyboard>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void myKeyboard(unsigned char key, int x, int y) { switch(key) { case 's': cam.slide(0.0, 0.0, 0.2); break; case 'w': cam.slide(0.0, 0.0, -0.2); break; case 'a': cam.yaw(-1.0); break; case 'd': cam.yaw(1.0); break; case 27: exit(0); } glClear(GL_COLOR_BUFFER_BIT); glutPostRedisplay(); } void displaySDL( void ) { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); scn.drawSceneOpenGL(); glFlush(); glutSwapBuffers(); } int main( int argc, char* argv[] ) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 100); glutCreateWindow("SDL Sence With Camera"); glutKeyboardFunc(myKeyboard); glutDisplayFunc(displaySDL); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glViewport(0, 0, 640, 480); scn.read("fig5_63.dat"); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); scn.makeLightsOpenGL(); cam.set(2.3, 1.3, 2.0, 0, 0.25, 0, 0, 1, 0); cam.setShape(30.0f, 64.0f/48.0f, 0.5f, 50.0f); glutMainLoop(); return 0; } This is a tar with my SDL file, and the file I pasted above and my Camera class. http://www.filedropper.com/fpsdemotar If someone can give me some tips for what algorithm I should use when processing mouse callbacks in terms of pointing the camera I would appreciate it. Thanks!
Mouse moving up/down -> pitch, Mouse moving right/left -> yaw. I do not believe having your 'a' and 'd' keys be yaw is accurate. Actually, your whole setup is a bit odd to me, since from a geometric standpoint, I view the coordinate as (x, y, z). You set s and w to go "up" and "down" (z), instead of "forward" and "back" (y). I see it as a xy graph that has been set flat on a table and you are looking at it from above. Moving close to it decreases z, which is coming out of the plane. Here is how I would have it setup: w -> slide(0, 0.2, 0); // y s -> slide(0, -0.2, 0); a -> slide(-0.2, 0, 0); // x d -> slide(0.2, 0, 0); //The following goes in your mouse event handler or something: pitch(newMouseLocation.y - oldMouseLocation.y); // mouse y is related to pitch yaw(newMouseLocaiton.x - oldMouseLocation.x); // mouse x is related to yaw I realize that you do not need to follow this coordinate convention, but it just seems more intuitive for me. I hope this helps.
784,330
784,342
RAII and uninitalized values
Just a simple question: if I had a simple vector class: class Vector { public: float x; float y; float z; }; Doesnt the RAII concept apply here as well? i.e. to provide a constructor to initialize all values to some values (to prevent uninitialized value being used). EDIT or to provide a constructor that explicitly asks the user to initialize the member variables before the object can be obstantiated. i.e. class Vector { public: float x; float y; float z; public: Vector( float x_, float y_, float z_ ) : x( x_ ), y( y_ ), z( z_ ) { // Code to check pre-condition; } }; Should RAII be used to help programmer forgetting to initialize the value before it's used, or is that the developer's responsibility? Or is that the wrong way of looking at RAII? I intentionally made this example ridiculously simple. My real question was to answer, for example, a composite class such as: class VectorField { public: Vector top; Vector bottom; Vector back; // a lot more! }; As you can see...if I had to write a constructor to initialize every single member, it's quite tedious. Thoughts?
The "R" in RAII stands for Resource. Not everything is a resource. Many classes, such as std::vector, are self-initializing. You don't need to worry about those. POD types are not self initializing, so it makes sense to initialize them to some useful value.
784,379
789,805
Why does gcov report 0% coverage on a header file for a well used class?
I'm attempting to measure test coverage for the first time using gcov. Now that I'm past the initial learning curve, things seem to be going well, except for one little snag. I expect that it boils down to a lack of understanding on my part, so I'm hoping someone familiar with gcov can explain what's going on. The issue is that I have one particular header file showing 0% coverage. However the only thing in that header is a class declaration for a well-used class. In addition, The implementation file for the class shows 100% coverage, and I can point to 5 different tests where I know for a fact that the class is being successfully instantiated. So why would gcov report 0% coverage on the class, and how can I fix it? -- edit -- As lacqui pointed out below, if the header has no executable code, it shouldn't be included in coverage calculations. And in fact, out of all of my classes, that particular header file is the only one that gcov is trying to generate coverage information for. I've done a line-by-line comparison with the other headers, and the biggest difference I found was that this particular header does not have an explicit constructor or destructor, while the others do. In an attempt to minimize the differences between the files, I added an explicit ctor and dtor to the problem class. However, this did not make any difference.
It looks like I've sorted out the problem. As I expected, it's more of a lack-of-experience issue, than anything. As it turns out, gcov was only finding a subset of the available tracefiles, and was therefore reporting only part of the total results. Finding and adding the rest of the tracefiles resolved the issue. For any that are curious, the problematic header file still shows up in the output. In fact, all of the other header files do too, even though they contain no executable code. However, they all show 90+% coverage.
784,445
784,477
How could simply calling Pitch() and Yaw() cause the camera to eventually Roll()?
I'm coding a basic OpenGL game and I've got some code that handles the mouse in terms of moving the camera. I'm using the following method: int windowWidth = 640; int windowHeight = 480; int oldMouseX = -1; int oldMouseY = -1; void mousePassiveHandler(int x, int y) { int snapThreshold = 50; if (oldMouseX != -1 && oldMouseY != -1) { cam.yaw((x - oldMouseX)/10.0); cam.pitch((y - oldMouseY)/10.0); oldMouseX = x; oldMouseY = y; if ((fabs(x - (windowWidth / 2)) > snapThreshold) || (fabs(y - (windowHeight / 2)) > snapThreshold)) { oldMouseX = windowWidth / 2; oldMouseY = windowHeight / 2; glutWarpPointer(windowWidth / 2, windowHeight / 2); } } else { oldMouseX = windowWidth / 2; oldMouseY = windowHeight / 2; glutWarpPointer(windowWidth / 2, windowHeight / 2); } glutPostRedisplay(); } However, after looking around in circles you'll find the camera starts to "roll" (rotate). Since I'm only calling Pitch and Yaw, I don't see how this is possible. Here is the code I'm using for my Camera class: http://pastebin.com/m20d2b01e As far as I know, my camera "rolling" shouldn't happen. It should simply pitch up and down or yaw left and right. NOT roll. What could be causing this?
Congratulations -- you have discovered Lie group theory! Yes, it's possible. The outcome of a series of transformations depends on the order in which they're executed. Doing a pitch followed by a yaw is not the same as a doing a yaw, followed by a pitch. In fact, in the limit of infinitesimally small yaws and pitches, the difference amounts to a pure roll; the general case is a little more complicated. (Physicists call this the "commutation relationships of the rotational group".) If you're familiar with rotation matrices, you can work it out quite easily.
784,469
784,489
makefile not building updated part of the program - C++
I am new to makefiles and facing some issue with it. I have created the following makefile. It works correctly. But when I modify the main.cpp and run make, it says "everything is up to date". I need to do a make clean and run make again, everything will work. Looks like there is some issue with this makefile and I can't figure it out where it is going wrong. Can anyone help me to find out where is the error in this makefile and why it is not building changed files? #Main makefile which does the build CFLAGS = CC = g++ PROG = fooexe #each module will append the source files to here SRC := #including the description include foo/module.mk OBJ := $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC))) main.o #linking the program fooexe: $(OBJ) $(CC) -o $(PROG) $(OBJ) %.o: $(CC) -c $(SRC) -o $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC))) main.o: $(CC) -c main.cpp depend: makedepend -- $(CFLAGS) -- $(SRC) .PHONY:clean clean: find . -name "*.o" | xargs rm -vf rm -vf fooexe
Normally the .o file needs to have a dependency on the corresponding .cpp file. I think this is the syntax, but not 100% sure: %.o : %.cpp $(CC) ... main.o : main.cpp $(CC) ...
784,533
784,540
Reverse that Math function
I need to reverse a function with hard Math operations, I'm asking here to check if it's even possible, eventually for help. public static UInt32 Func_4(UInt32 P, UInt32 X, UInt32 G) { UInt64 result = 1; UInt64 mult = G; if (X == 0) return 1; while (X != 0) { if ((X & 1) != 0) result = (mult * result) % P; X = X >> 1; mult = (mult * mult) % P; } return (UInt32)result; } By "Reversing" I mean this: I know G, I know P, I know the result. I need X. I tried to translate it again this morning while my mind was clear, but I failed. Is it even possible? Thank you in advance.
It looks like your Func_4() function calculates GX mod P. What you're asking for is a solution to the discrete logarithm problem, but no efficient algorithm is known.
784,781
784,789
Static libraries, dynamic libraries, DLLs, entry points, headers ... how to get out of this alive?
I recently had to program C++ under Windows for an University project, and I'm pretty confused about static and dynamic libraries system, what the compiler needs, what the linker needs, how to build a library ... is there any good document about this out there? I'm pretty confused about the *nix library system as well (so, dylibs, the ar tool, how to compile them ...), can you point a review document about the current library techniques on the various architectures? Note: due to my poor knowledge this message could contain wrong concepts, feel free to edit it. Thank you Feel free to add more reference, I will add them to the summary. References Since most of you posted *nix or Windows specific references I will summarize here the best ones, I will mark as accepted answer the Wikipedia one, because is a good start point (and has references inside too) to get introduced to this stuff. Program Library Howto (Unix) Dynamic-Link Libraries (from MSDN) (Windows) DLL Information (StackOverflow) (Windows) Programming in C (Unix) An Overview of Compiling and Linking (Windows)
Start with Wikipedia - plenty of information there, and lots of links to other useful resources. P.S. But perhaps it would be better to just ask a specific question about the problem you're currently having. Learning how to solve it may go a long way to teaching you the general concepts.
784,997
892,607
Launching email application (MAPI) from C# (with attachment)
In the past I have used MAPISendMail to launch Outlook (or whatever the desired MAPI email application was) from a C++ application with a file attachment. (Similar to say Microsoft Word's Send Email functionality). I need to do the equivalent from a C# application and to have it work when running on XP, Vista, Server 2008 (and Windows 7 I suppose). MAPISendMail is a no go under Vista/2008 as it always returns MAPI_ E_FAILURE when Outlook is running and MAPI is not supported in managed code. Even after checking this fix: http://support.microsoft.com/kb/939718 I can't get it to reliably work. I know that Microsoft Word & Adobe Reader 9 can both launch Outlook with an attachment under Vista. A C# compatible solution would be preferred but I'd be happy with anything that works (doesn't have to use MAPI). I can't seem to find what the current "solution" is. None of the existing answers on Stack Overflow seem to cover this either. Edit: I am aware MAPI and C# do not work together, so I will take a C/C++ solution that works in Vista and Server 2008 when NOT running as administrator. See Adobe Reader 9 & Microsoft Word as examples that work.
At work we have successfully done this using VSTO. Here is a snippet of some lines we have running on VISTA with Outlook 2007: (the code is in VB.net). Note that the usage is security locked when doing certain things to the outlook object. (to address, body and other properties marked as security risks). We use a 3rd party component (Redemption) to go around this security. If you dont use a security manager of some sort, outlook will give a little popup that something outside is trying to access it and you can give it access in a period of time. The import of the Outlook interface. Imports Outlook = Microsoft.Office.Interop.Outlook This example is to give you some direction, not a full working example. dim MailItem As Microsoft.Office.Interop.Outlook.MailItem ' Lets initialize outlook object ' MailItem = OutlookSession.Application.CreateItem(Outlook.OlItemType.olMailItem) MailItem.To = mailto MailItem.Subject = communication.Subject MailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML MailItem.HTMLBody = htmlBody MailItem.Attachments.Add(filename, Outlook.OlAttachmentType.olByValue) ' If True is supplied to Display it will act as modal and is executed sequential. ' SafeMail.Display(True) The OutlookSession in the above example is coming from this Property: Public ReadOnly Property OutlookSession() As Outlook.NameSpace Get If Not OutlookApplication Is Nothing Then Return OutlookApplication.GetNamespace ("MAPI") Else Return Nothing End If End Get End Property As you can see it is using MAPI inside for this. Good luck with it.
785,097
785,129
How do I implement a Bézier curve in C++?
I'd like to implement a Bézier curve. I've done this in C# before, but I'm totally unfamiliar with the C++ libraries. How should I go about creating a quadratic curve? void printQuadCurve(float delta, Vector2f p0, Vector2f p1, Vector2f p2); Clearly we'd need to use linear interpolation, but does this exist in the standard math library? If not, where can I find it? I'm using Linux.
Did you use a C# library earlier? In C++, no standard library function for Bezier curves is available (yet). You can of course roll your own (CodeProject sample) or look for a math library. This blogpost explains the idea nicely but in Actionscript. Translation should not be much of a problem.
785,480
785,514
Good patterns for a C/C++ plugin-based system?
When developing a C/C++ (=2?) plugin based framework with shared objects/dynamic libraries that need to support live swapping what examples would be helpful to look at for implementation details? Thanks. Note: live swapping is the key point here, no need to restart the system is a requirement
If you are on POSIX, dlopen(), dlsym() and dlclose() are all you need. See man dlsym for details and examples. There is a good article about loading dynamic libraries, and plugin infrastructure is an example. EDIT OP added Windows as requirement so this approach won't help since Windows isn't POSIX-compliant. However there are similar functions in WinAPI - see here.
785,503
799,517
COM MFC application don't show window
I have a MFC application with ATL support, the idea is when someone creates an instance of my interface declared in the mfc application, this instantiation creates and displays a window. This all works fine if the com client is the cmd.exe, i made a quick com client that instance the interface and when this instances occur the window is displayed as desired. But if this instantiation is done in another com objects (for example atl server objects (services)) the window is not displayed. Note that the mfc process is created under the DcomLaunch process but no window is displayed. Everything works fine but the window is not show in my desktop. Two questions: 1) why my window is not displayed in this situation? 2) when i create the same interface with my console app, only one process of the mfc application is created, no mater how many console app i start, and if the service try to instantiate more than one object, more than one mfc process are created! why is this, how can i avoid this. How can i make that the first mfc process is allways the same one that responds to the client calls? (i think this is all due to security settings... but i already try to change some and nothing...) Thanks Nuno
In general a service cannot create windows. Pre-Vista you can enable a service to interact with the desktop (for example, open a window) via the "Allow service to interact with desktop" check-box on the "Log On" tag of the given services properties. If you're targetting Vista, this isn't an option. However, given this is the DcomLaunch service you're dealing with, you clearly don't want to do that. Even if it was your own service you wrote most anyone would advise against you doing this anyway for a few reasons (in no particular order): The UI created would be only accessible in session 0 Creating a window creates an attack service into your (probably) privileged process since any other process the user runs can interact with the service's window. Again, since the above only works pre-Vista, and is a Bad Idea anyway, the generally accepted "best practice" for a service that wants to expose a UI is to have a separate application that contains the UI which communicates with the service using whatever IPC mechanism you choose to use.
785,581
785,610
How to ensure that a program is running and restart it if needed?
I developed a software (in C++) which needs to be continuously running. That basically means that it has to be restarted each time it stops. I was thinking about using cron jobs to check every minutes if it is still alive, but there might be a cleaner way or standard way of doing this. Thanks in advance
Fedora and Ubuntu use upstart, which has a the ability to automatically restart your deamon if it exits.
785,598
785,635
How to send a link to an application, like Spotify does
When we save a level in our editor, we create a log file of any errors it contains. These consist basically of an error message and a path that allows the user to find the erronous item in a tree view. What I want is to make that path a link, something like < a href="editor://path/to/gameobject" > Click to see object in editor< /a > The SO questions I've seen regarding this seems to point to this msdn page: http://msdn.microsoft.com/en-us/library/aa767914.aspx But from what I can tell, it will spawn a new instance of the application. What I want to do is to simply "call" our editor somehow. One way to do it, I guess, is to spawn it, and in the beginning check if there's already an instance running, and if so, send the commandline to it. Is that the best way to do it? If so, any ideas on how to do it best? What are otherwise some ways that this could be done? Also: does the msdn solution work across browsers? Our editor runs in Windows only, but people use IE, Fx, GC and Opera.
If you need the link to work in any viewer, yes, registering a protocol handler is the best way. As for launching the editor, you could implement it as an out-of-process COM server, but if you've already got command line parsing sorted, you might as well use a window message or named pipe to pass that to the editor. If you're sending a window message, you could use FindWindow (with a unique class name) to check for a running instance.
785,686
785,695
Semicolon after class declaration braces
In C++ classes, why the semi-colon after the closing brace? I regularly forget it and get compiler errors, and hence lost time. Seems somewhat superfluous to me, which is unlikely to be the case. Do people really do things like: class MyClass { . . . } MyInstance; I get it from a C compatibility point of view for structs and enums, but since classes aren't part of the C language I guess it's primarily there the keep consistency between similar declaration constructs. What I was looking for was more related to design rationale rather than being able to change anything, although a good code completion IDE might trap this before compilation.
The semi-colon after the closing brace in a type declaration is required by the language. It's been that way since the earliest versions of C. And yes, people do indeed do the declaration you just put up there. It's useful for creating scoped types inside of methods. void Example() { struct { int x; } s1; s1.x = 42; struct ADifferentType { int x; }; } In this case, I think it's clear why the semi-colons are needed. As to why it's needed in the more general case of declaring in the header file I'm unsure. My guess is that it's historical and was done to make writing the compiler easier.
785,814
786,485
Boost serialization in Qt: is it a proper way?
I'm thinking about serializing data in an application which is Qt-based. Essentially what I'm going to serialize is my hierarchical model, which is composed of different classes that derive from, say, TreeModelItem: class TreeModelItem { protected: QList<TreeModelItem *> m_children; //... }; Should I study boost::serialization and go on with it? Is there any hidden wall I can hit by the way? E.g. while (de)serializing child elements, or when restoring custom singal-slot connections? I hope for the advice of experts.
QDataStream supports (de)serialization of some popular Qt objects. You can check which ones here. The "Qt" way would be to use that. However, there's nothing preventing you from using boost, but you will have to implement the serialization for basic objects such as QList all over again, which can be tiresome. Note that if you have custom objects, such as your TreeModelItem, you would have to provide an operator<< of your own. Regarding the serialization of signals/slots: afaik Qt doesn't support this atm, and I believe the Qt team has made it this way intentionally. If you're interested why, maybe this read can be helpful.
786,093
786,114
Does using SecureZeroMemory() really help to make the application more secure?
There's a SecureZeroMemory() function in WinAPI that is designed for erasing the memory used for storing passwords/encryption keys/similar stuff when the buffer is no longer needed. It differs from ZeroMemory() in that its call will not be optimized out by the compiler. Is it really so necessary to erase the memory used for storing sensitive data? Does it really make the application more secure? I understand that data could be written into swapfile or into hibernation file and that other processes could possibly read my program's memory. But the same could happen with the data when it is still in use. Why is use, then erase better than just use?
It does. Hibernation file is not encrypted, for example. And if you don't securely clear the memory, you might end up with trouble. It's just a single example, though. You should always hold secret stuff in memory only as long as needed.
786,131
786,162
How to maintain a list of functions in C++/STL?
Before asking you my question directly, I'm going to describe the nature of my prolem. I'm coding a 2D simulation using C++/OpenGL with the GLFW library. And I need to manage a lot of threads properly. In GLFW we have to call the function: thread = glfwCreateThread(ThreadFunc, NULL); (the first parameter is the function that'll execute the thread, and the second represents the parameters of this function). And glfwCreateThread, has to be called every time! (ie: in each cycle). This way of working, doesn't really help me, because it breaks the way i'm building my code because i need to create threads out of the main loop scope. So I'm creating a ThreadManager class, that'll have the following prototype : class ThreadManager { public: ThreadManager(); void AddThread(void*, void GLFWCALL (*pt2Func)(void*)); void DeleteThread(void GLFWCALL (*pt2Func)(void*)); void ExecuteAllThreads(); private: vector<void GLFWCALL (*pt2Func)(void*)> list_functions; // some attributs }; So for example, if I want to add a specific thread I'll just need to call AddThread with the specific parameters, and the specific function. And the goal is just to be able to call: ExecuteAllThreads(); inside the main loop scope. But for this i need to have something like: void ExecuteAllThreads() { vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter_end = list_functions.end(); for(vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter = list_functions.begin(); iter != iter_end; ++iter) { thread = glfwCreateThread(&(iter*), param); } } And inside AddThread, I'll just have to add the function referenced by the pt2Func to the vector : list_functions. Alright, this is the general idea of what i want to do.. is it the right way to go ? You have a better idea ? How to do this, really ? (I mean the problem is the syntax, i'm not sure how to do this). Thank you !
You need to create threads in each simulation cycle? That sounds suspicious. Create your threads once, and reuse them. Thread creation isn't a cheap operation. You definitely don't want to do that in every iteration step. If possible, I'd recommend you use Boost.Thread for threads instead, to give you type safety and other handy features. Threading is complicated enough without throwing away type safety and working against a primitive C API. That said, what you're asking is possible, although it gets messy. First, you need to store the arguments for the functions as well, so your class looks something like this: class ThreadManager { public: typedef void GLFWCALL (*pt2Func)(void*); // Just a convenience typedef typedef std::vector<std::pair<pt2Func, void*> > func_vector; ThreadManager(); void AddThread(void*, pt2Func); void DeleteThread(pt2Func); void ExecuteAllThreads(); private: func_vector list_functions; }; And then ExecuteAllThreads: void ExecuteAllThreads() { func_vector::const_iterator iter_end = list_functions.end(); for(func_vector::const_iterator iter = list_functions.begin(); iter != iter_end; ++iter) { thread = glfwCreateThread(iter->first, iter->second); } } And of course inside AddThread you'd have to add a pair of function pointer and argument to the vector. Note that Boost.Thread would solve most of this a lot cleaner, since it expects a thread to be a functor (which can hold state, and therefore doesn't need explicit arguments). Your thread function could be defined something like this: class MyThread { MyThread(/* Pass whatever arguments you want in the constructor, and store them in the object as members */); void operator()() { // The actual thread function } }; And since the operator() doesn't take any parameters, it becomes a lot simpler to start the thread.
786,182
786,760
How should I link a data Class to my GUI code (to display attributes of object, in C++)?
I have a class (in C++), call it Data, that has thousands of instances (objects) when the code is run. I have a widget (in Qt), call it DataWidget that displays attributes of the objects. To rapidly build the widget I simply wrote the object attributes to a file and had the widget parse the file for the attributes - this approach works, but isn't scalable or pretty. To be more clear my requirements are: 1 - DataWidget should be able to display multiple, different, Data object's attributes at a time 2 - DataWidget should be able to display thousands of Data objects per second 3 - DataWidget should be run along side the code that generates new Data objects 4 - each Data object needs to be permanently saved to file/database Currently, the GUI is created and the DataWidget is created then the experiment runs and generates thousands of Data objects (periodically writing some of them to file). After the experiment runs the DataWidget displays the last Data object written to file (they are written to XML files). With my current file approach I can satisfy (1) by grabbing more than one file after the experiment runs. Since the experiment isn't tied to DataWidget, there is no concurrency, so I can't do (3) until I add a signal that informs the DataWidget that a new file exists. I haven't moved forward with this approach for 2 reasons: Firstly, even though the files aren't immediately written to disk, I can't imagine that this method is scalable unless I implement a caching system - but, this seems like I'm reinvent the wheel? Secondly, Data is a wrapper for a graph data-structure and I'm using Graphml (via Boost Graph Library i.e. write_graphml()) to write the structure to XML files, and to read the structure back in with Boost's read_graphml() requires me to read the file back into a Data object ... which means the experiment portion of the program encodes the object into XML, writes the XML to a file (but hopefully in memory and not to disk), then the DataWidget reads the XML from a file and decodes it into an object! It seems to me like I should be using a database which would handle all the caching etc. Moreover, it seems like I should be able to skip the file/database step and pass the Data to the DataWidget in the program (perhaps pass it a reference to a list of Data). Yet, I also want to save the Data to file to the file/database step isn't entirely pointless - I'm just using it in the wrong way at the wrong time. What is the better approach given my requirements? Are there any general resources and/or guidelines for handling and displaying data like this?
I see you're using Qt. This is good because Qt 4.0 and later includes a powerful model/view framework. And I think this is what you want. Model/View Basically, have your Data class inherit and implement QAbstractItemModel, or a different Qt Model class, depending on the kind of model you want. Then set your view widget (most likely a QListView) to use Data for its model. There are lots of examples at their site and this solution scales nicely with large data sets. Added: This model test code from labs.trolltech.com comes in real handy: http://labs.trolltech.com/page/Projects/Itemview/Modeltest
786,417
786,553
Is there an ORM (Object Relational Mapper) framework that supports C++ and C#
I'm looking for an ORM that will allow me to write a C# user interface and a C++ service. Both need to access data from the same database. Ideally I want C# and C++ classes to be generated from the database schema that I can then program against. The database will probably be SQLServer, but that hasn't been decided yet. Note: I'm doing this in a windows environment, but for reasons I don't want to go into, I can't actually use COM, so a COM solution isn't an option. This is similar to this question: ORM (object relational manager) solution with multiple programming language support However, that wasn't answered well enough, and I can't raise a bounty on it.
Unfortunately this may not be of any help to you, but if you give up on trying to find a pre-build solution, it's not that terribly difficult to develop an in-house version that only supports what you need. We have an in-house data definition language that we use to generate the SQL schema for our data, and ORM classes for native C++ and .NET. The only real trick is comparing the generated schema with what's already in the database to make migrations to the next version easier.
786,547
786,586
What is a good way to recover from a fread() failure?
If a call to fread() returns 0 and ferror() indicates an error (vs. EOF), is it OK to retry the read or is it better to close and reopen the file? I can't start over entirely -- the input file has been partially processed in a way that can't be undone (say I'm writing out a chunk at a time to a socket and, due to existing protocol, have no way of telling the remote end, "never mind, I need to start over"). I could fclose() and fopen() the file, fseek() past the data already processed, and continue the fread()-ing from there, but is all that necessary?
There's no "one size fits all" solution, since different errors can require different handling. Errors from fread() are unusual; if you're calling it correctly, an error may indicate a situation that has left the FILE* in a weird error state. In that case you're best off calling fclose(), fopen(), fseek() to get things back in a good state. If you're coding for something that's happening, please mention the actual errors you're getting from ferror()...
786,555
786,567
C++ stream to memory
how can I create std::ostream and std::istream objects to point to a piece of memory I allocated and manage (I don't want the stream to free my memory). I was looking at using rdbuf()->pubsetbuf() to modify one of the other streams - say sstringstream. However I think streambuf used by stringstream will free the buffer afterwards? Basically I'm trying to serialize some things to shared memory. Thanks.
Take a look at the bufferstream class in the Boost.Interprocess library: The bufferstream classes offer iostream interface with direct formatting in a fixed size memory buffer with protection against buffer overflows.
786,558
786,572
How to get round VC++ Runtime requirement in a dll?
I wrote a dll in VS2008 that I use in my C# application,but my users don't like the fact they need both .NET framework and VC++ Runtime. Is there a way I could avoid the 'must-have' VC++ Runtime in my C++ dll?
You can build your dll with the runtime linked statically (/MT instead of /MD - Under properties->Configuration Properties->C/C++->Code Generation->Runtime Library).
786,566
787,115
Adding an item to Internet Explorer's right-click context menu
I'm trying to add a new entry into Internet Explorer's right-click context menu. I understand that this can be achieved by creating an HTML file containing JavaScript, and then linking to this from a location in the registry. I have also read that you can also add the HTML to a resource file and compile it into a DLL (see the Microsoft KB: Adding Entries to the Standard Context Menu). This is where I have started to hit problems. Here is a bit of background about what I have done so far. I have the following JavaScript in the file C:\test.htm: <script type="text/javascript"> alert('Hello, world!'); </script> I have added a new REG_SZ value 'c:\test.htm' in the registry at the following location: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt If I now restart IE, my new menu item appears in the context menu. If I select my new menu item, my message box alert appears as expected. So far so good. However, I can't seem to access the script if it's in a DLL. Here are the steps I have taken: Created a new Visual C++ Class Library project in VS 2005 named 'IETest' in c:\IETest Imported my C:\test.htm file into the default app.rc resource file. I have changed the ID to be TEST Compiled the DLL in debug mode Altered the registry entry to read res://C:\IETest\debug\IETest.dll/TEST If I now restart IE and try again, the message box does not appear when I right-click and select my new context menu entry. I have also tried a release build of the DLL without any luck, and also tried replacing the last forward slash with a comma and altering the path single-backslashes to double-slashes. I can only presume that I've done something wrong when creating my DLL. Can anyone point me in the right direction? Is there any way I can examine the compiled DLL to examine the resources and associated IDs? Thanks.
Have you tried having the ID be TEST.html? My guess is that IE doesn't know how to handle the file because it doesn't have an extension listed, but this is totally a guess based off the fact that's how certain MS .dlls identify them (i.e. res://c:\windows\system32\shdoclc.dll/navcancl.htm) The only other thing I can think of is to make sure your resources are of type 23. ResourceHacker can view the resource files like you want: http://angusj.com/resourcehacker/
786,951
787,843
stringstream unsigned conversion broken?
Consider this program: #include <iostream> #include <string> #include <sstream> #include <cassert> int main() { std::istringstream stream( "-1" ); unsigned short n = 0; stream >> n; assert( stream.fail() && n == 0 ); std::cout << "can't convert -1 to unsigned short" << std::endl; return 0; } I tried this on gcc (version 4.0.1 Apple Inc. build 5490) on OS X 10.5.6 and the assertion is true; it fails to convert -1 to an unsigned short. In Visual Studio 2005 (and 2008) however, the assertion fails and the resulting value of n is the same as what you would expect from an compiler generated implicit conversion - i.e "-1" is 65535, "-2" is 65534, etc. But then it gets weird at "-32769" which converts to 32767. Who's right and who's wrong here? (And what the hell's going on with -32769??)
The behaviour claimed by GCC in Max Lybbert's post is based on the tables om the C++ Standard that map iostream behaviour onto printf/scanf converters (or at least that;'s my reading). However, the scanf behaviour of g++ seems to be different from the istream behavior: #include <iostream> #include <cstdio> using namespace std;; int main() { unsigned short n = 0; if ( ! sscanf( "-1", "%hu", &n ) ) { cout << "conversion failed\n"; } else { cout << n << endl; } } actually prints 65535.
786,984
786,991
How can I control my PC's fan speed using C++ in Vista?
How can I use C++ to control CPU fan speed in Windows Vista Ultimate? I would like to use ACPI.
ACPI: You need to learn about and use the WMI - Windows system management interface. Here are a few resources that will give you clues on where to start: SetSpeed Method of the CIM_Fan Class WMI C++ Application Examples Example: Calling a Provider Method Note that some motherboards don't support fan speed changes, and even those that do may not expose this to the WMI. In the best case you may still have to detect the motherboard type and talk to the fan management controllers directly. No ACPI: If you don't want to use ACPI then you're going to have to write your own code to access the SMBUS on the motherboard, and then control the fan controller chips. Check out the program motherboard monitor for clues on how to get started. It's nontrivial, since every motherboard and bios is different.
787,164
787,231
Boost Regex - Where are the matching strings stored?
I`m writing a web spider and want to use boost regex library instead of crafting some complicated parsing functions. I took a look at this example: #include <string> #include <map> #include <boost/regex.hpp> // purpose: // takes the contents of a file in the form of a string // and searches for all the C++ class definitions, storing // their locations in a map of strings/int's typedef std::map<std::string, int, std::less<std::string> > map_type; boost::regex expression( "^(template[[:space:]]*<[^;:{]+>[[:space:]]*)?" "(class|struct)[[:space:]]*" "(\\<\\w+\\>([[:blank:]]*\\([^)]*\\))?" "[[:space:]]*)*(\\<\\w*\\>)[[:space:]]*" "(<[^;:{]+>[[:space:]]*)?(\\{|:[^;\\{()]*\\{)"); void IndexClasses(map_type& m, const std::string& file) { std::string::const_iterator start, end; start = file.begin(); end = file.end(); boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; while(regex_search(start, end, what, expression, flags)) { // what[0] contains the whole string // what[5] contains the class name. // what[6] contains the template specialisation if any. // add class name and position to map: m[std::string(what[5].first, what[5].second) + std::string(what[6].first, what[6].second)] = what[5].first - file.begin(); // update search position: start = what[0].second; // update flags: flags |= boost::match_prev_avail; flags |= boost::match_not_bob; } } but, it's somewhat obfuscated (it's my first try with boost ;)) and I can't seem to find the actual location of the matching strings. So my question is - how do I get the location of all matches?
as the comments in the code suggest, what[0] contains the entire string. so what[0].first will point to the beginning of the match in every iteration of the loop. and in general to get the i'th group you could use: string s(what[i].first, what[i].second); to read more about the class match_results, check this link.
787,288
789,367
Problem when disabling checked iterators in vs2008 SP1 (_HAS_ITERATOR_DEBUGGING=0)
I've been having some trouble with vs2008 SP1 running in debug mode when I try to disable checked iterators. The following program reproduces the problem (a crash in the string destructor): #define _HAS_ITERATOR_DEBUGGING 0 #include <sstream> int do_stuff(std::string const& text) { std::string::const_iterator i(text.end()); return 0; } int main() { std::ostringstream os; os << "some_text"; return do_stuff(os.str()); } I'd found a similar post on gamdev.net that discussed having this problem in vs2005. The example program in that post compiles for me on 2008 SP1 as is - but when I modded it to use ostringstream, I was able to get the problem. From poking around in the debugger, it looks like the library pops iterators off the stack, then later tries to use them in _Orphan_All, which is some kind of iterator checking cleanup code... Can anyone else reproduce this problem or tell me what's going on? Thanks!
I've just tried this in VS2008 on Windows XP and got a warning regarding a buffer overflow, both on a pre- and a post-SP1 VS2008. Interestingly enough the problem seems to be centred around passing the string into do_stuff either by reference or by value - if I use the original code, it complains about the buffer overflow but if I pass the string in by value, it runs fine. This is with the multithreaded debug DLL runtime. The error disappears when you like against the static MT Debug runtime. In both cases, precompiled headers were turned off and the files that normally generate the precompiled headers have been removed from the project. After reading this article on MSDN I'm wondering if the problem stems from the fact that several C++ standard library classes are actually residing in the runtime library if you build with the debug DLL runtimes (just try to link a VS2008-generated binary against an earlier library and watch out for the unresolved externals to confirm this).
787,375
787,395
Why would you want to use C# if its slower than C++?
I'm looking for a new language to learn after C++ and Java. I was going to try C#, but a bunch of people say its really slow because its a high level language. So why would anybody use C#? Isn't C++ much faster? Does it make development easier, but just have a slower final product? Also, what can C# be used for? You use it with a lot of .NET stuff on windows, and with ASP.NET, but what are other situations where one would use C#? Will there be a lot of job opportunities for it?
Who exactly is this "bunch of people"? What are they comparing it against? For the vast majority of things, C++ is not "much faster" than C#. It certainly has benefits in various situations, particularly where you want more deterministic memory handling, but in my experience the bottleneck in most applications isn't in places where C++ would help. As spoulson says, a lot of performance is in the design instead of the exact implementation - and there, it helps to be able to try different designs easily. Why would we use C# when it's a bit slower than C++? Because it's generally reckoned (i.e. some disagree :) to be a lot easier to develop in without shooting yourself in the foot. As for what C# can be used for... what do you want to use it for? Unless you want to develop drivers and kernels, it may well be fine for you. (Even OS development has some folks using C#...) Job opportunities? Loads. Downsides? Well, .NET itself is only available on Microsoft platforms. There's Mono, but it doesn't have quite the same degree of portability as Java (no doubt another "slow" language according to the same bunch of people).
787,417
793,385
Why would you write something like this? (intentionally not using delete [] on an array)
I came across this kind of code once in a while - I suspect the creator is/was afraid that table delete would iterate over the table and "cost performance" (which imho will not be done either way)... is there any real benefit one might get/consider/imagine from not using the the table delete here? myClass** table = new myClass* [size]; ... //some code that does not reallocate or change the value of the table pointer ;) delete table; // no [] intentionally
There's really no reason to write like that and a serious reason to never do so. It's true that for types with trivial destructors (like raw pointers in your case) there's no need to know the actual number of elements in the array and so the compiler might decide to map new[] and delete[] onto new and delete to reduce the overhead. If it decides this way you can't stop it without extra steps taken, so this compiler optimization will take place without your notice and will be free. At the same time someone using your code might wish to overload the global operators new and delete (and new[] and delete[] as well). If that happens you run into big trouble because this is when you may really need the difference between the delete and delete[]. Add to this that this compiler-dependent optimization is unportable. So this is the case when you get no benefits displacing delete[] with delete but risk big time relying into undefined behaviour.
787,448
787,467
Marshalling reference-types from C++ to C#
I want to invoke the following C++ function (exported by a DLL) from C#: void createVm( const jace::VmLoader& loader, const jace::OptionList& options, bool ignoreUnrecognized = true ); I've found documentation for marshaling primitives from C++ to C# but I'm not sure how to handle reference-types or non-pritmive types such as VmLoader or OptionList (both of which are classes). I'm trying to wrap a C++ API with a C# layer, delegating to the underlying C++ code for the actual method implementation. Any ideas?
AFAIK, PInvoking into a function with C++ constructs is not a supported operation. You could probably get it to work but I think you'll find problems. What is supported is writing a simple C wrapper function which calls into your C++ function. PInvoke into the wrapper function instead and that will do the trick.
787,481
787,508
SQLite3 trouble under VC9
I imported sqlite3.c sqlite3.h into my project - and I'm having trouble compiling it. Errors: 1>c:\...\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sqlite3' 1>storage_manager.cpp 1>c:\...\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sqlite3' 1>ui_manager.cpp 1>c:\...\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sqlite3' Code: #pragma once #include "sqlite3.h" class storage_manager { sqlite3 db; sqlite3** db_pp; public: void open() { sqlite3_open("data.db", db_pp); } };
I just noticed you try to create a stack variable of type sqlite3 called db. That won't work, as sqlite3 is a handle and you can only have a pointer variable. You need then to pass the address of that pointer variable to sqlite3_open. @Neil Butterworth spotted it a bit earlier than me :-)
787,533
787,539
Is #pragma once a safe include guard?
I've read that there is some compiler optimization when using #pragma once which can result in faster compilation. I recognize that is non-standard, and thus could pose a cross-platform compatibility issue. Is this something that is supported by most modern compilers on non-windows platforms (gcc)? I want to avoid platform compilation issues, but also want to avoid the extra work of fallback guards: #pragma once #ifndef HEADER_H #define HEADER_H ... #endif // HEADER_H Should I be concerned? Should I expend any further mental energy on this?
Using #pragma once should work on any modern compiler, but I don't see any reason not to use a standard #ifndef include guard. It works just fine. The one caveat is that GCC didn't support #pragma once before version 3.4. I also found that, at least on GCC, it recognizes the standard #ifndef include guard and optimizes it, so it shouldn't be much slower than #pragma once.
787,598
787,694
How to perform atomic 64b read on x86 (Pentium and above)?
I would like to perform and atomic read of 64b aligned 64b data on x86 platform (Pentium or above guaranteed). Is there a way to do this? (And no, I do not want to use a critical section or a mutex for this, I want this to be lock-free).
Use the Interlocked operations, here's some sample code: LONGLONG AtomicRead(LONGLONG* p) { return InterlockedCompareExchange64(p, 0, 0); } This does the compare exchange against zero and sets p to zero if it's already equal to zero -ie, it's a noop. InterlockedCompareExchange returns the original 64 bit value pointed to by p.
787,809
788,973
How to clean up a complex QList?
I'm using a rather complex QList in a derivation of QAbstractTableModel to store data: class MyTableModel : public QAbstractTableModel { Q_OBJECT QList<QHash<int, QHash<int, QVariant> *> *> m_data; /*...*/ }; MyTableModel::~TMusicTableModel() { /* Should I deallocate QList items? */ } MyTableModel::setData(int row, int col, int type, QVariant value) { /* inserting a new data field */ QHash<int, QHash<int, QVariant> *> *row_hash = new QHash<int, QHash<int, QVariant> *>(); QHash<int, QVariant> *role_hash = new QHash<int, QVariant>(); type_hash->insert(type, value); row_hash->insert(col, type_hash); m_data.insert(row, row_hash); return true; } I'm wondering if the QList and QHashes take care of the deallaction or if I should do it. The documentation is not very informative in this case.
Because you're creating the sub items with "new", you do have to deallocate them yourself. See the qDeleteAll function for a quick way of doing so. Is there a reason why you're using new to create these hashs? (Your code is obviously just a snippet, so the pointers could be used and passed around elsewhere.) Generally, it's much simpler to just construct them on the stack so that destruction happens automatically.
787,906
787,939
C++ operator overloading resolution ambiguity
Am trying to move an antique C++ code base from gcc 3.2 to gcc 4.1, as I have run into a few issues. Of all the issues, the following is left me clueless (I guess I spent too much time with Java or I might have forgotten the basics of C++ :-P ). I have a template class template < class T > class XVector < T > { ... template < class T > T XVector < T >::getIncrement () { ... } template < class T > int XVector < T >::getValue (size_t index, T& value) { ... //The problematic line value = (T) (first_value + getIncrement()) * (long) (index - first_index); .... } } This class is based on the STL std::vector. I have a second class TypeValue and its defined as below which can hold one of int, long and their unsigned variants, float, double, std::string. Also overloads almost all possible operators. class TypeValue { union { long* _int_value; double* _real_value; string* _text_value; } _value; TypeValue(); explicit TypeValue(long _long); explicit TypeValue(int _int); explicit TypeValue(unsigned long _ulong); ... //similarly for all the remaining supported types. TypeValue(const TypeValue& ) //Copy constructor virtual TypeValue& operator=(const TypeValue &rhs); TypeValue& operator+ (TypeValue& )const; TypeValue& operator* (TypeValue& )const; ... //For all the basic operators operator long() const; operator int() const; operator unsigned long() const; operator unsigned int() const; ... } And finally I have another class, lets call it the build_breaker, which creates an object as XVector < TypeValue > a_variable;. Now when I compile this on gcc 3.2 this compiles without any problems. But when I try compiling this on gcc 4.1 I get errors saying ambigous overload for operator* in the class XVector and the candidates being operator*(long int, long int) operator*(int, long int) operator*(long unsigned int, long int) operator*(unsigned int, long int) operator*(double, long int) operator*(float, long int) If the compiler said it had problems finding a match for T * long, that would have made sense, but, why is it trying to typecast it to native type and then perform the arithmetic operation? Please help me on this. Thanks in advance.
The second operand type is long [int]. The first is TypeValue, I expect, but there is no operator* that takes those two exact types. There are lots of other type combinations for that operator, though, which the compiler can select by doing an implicit conversion on the first operand. The language allows the compiler to do that to try to find a match. But which of the many conversions should it choose? The compiler has no way to choose whether int is better than long int. (You might argue that since the second operand is long int, that should be the preferred conversion target, but that's not the way things work.) So, some advice: First, don't supply so many implicit conversions. Since the class can only hold long, double, and string, those are the only three conversions I'd supply. That alone probably won't solve your problem, but it may reduce the size of the error output and make other things more manageable. Instead of converting (index - first_index) to type long, consider converting it to type T (i.e., TypeValue) instead, since that seems to be the operation you really wanted to perform in the first place.
788,080
788,161
Automatically sorting on insert in QTreeWidget
I have a QTreeWidget that I insert items in, and the user can select a column to sort it. As the items are being inserted, they just get appended to the end instead of having the sort being done automatically. If I click the header to switch between ascending/descending it will sort the current items. I figured I could call sortItems() and use the column that is returned from sortColumn(), but I am unable to see how I can see if the user is doing an ascending or descending sort. I'm not worried about the efficiency of this, so I don't want to wait until the insertions are done and then do the sort. I'd like a real-time sorted list. Thanks!
If your tree widget is called treeWidget, you should be able to call the header() method, which is from QTreeWidget's parent QTreeView, then sortIndicatorOrder() from the QHeaderView class: treeWidget->header()->sortIndicatorOrder() With this, you know the user's current sort order, and you can apply your sort on insert according to this.
788,482
788,497
delete[] supplied a modified new-ed pointer. Undefined Behaviour?
I saw some code as below during a peer-code-review session: char *s = new char[3]; *s++ = 'a'; *s++ = 'b'; *s++='\0'; delete []s; // this may or may not crash on some or any day !! Firstly, I know that in Standard C++, pointing to one-past the array-size is O.K. though accessing it results in undefined behaviour. So I believe the last line *s++='\0' is fine. But if I recall correctly, the C++ standard mandates that delete should be supplied the same pointer that new returned. This I believe means that the returned pointer must not be tampered-with. I guess it is because new might keep some housekeeping info before the returned address that delete might use. Moving the new'd pointer might make this inaccessible. Is it undefined behaviour or implementation-defined or unspecified? Can anyone confirm this please? Preferably by pointing to the correct place in the C++ Standard. In the freely available draft version of the draft C++ Standard (Draft_SC22-N-4411.pdf) has the details in section 5.3.5. I got it from Bjarne's homepage.
From the C++ Standard, section 5.3.5/2: the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behaviour is undefined
788,703
788,745
Initializing a vector before main() in C++
I want to be able to initialize a vector of a size 'SIZE' before main. Normally I would do static vector<int> myVector(4,100); int main() { // Here I have a vector of size 4 with all the entries equal to 100 } But the problem is that I would like to initialize the first item of the vector to be of a certain value, and the other to another value. Is there an easy way to do this?
Here's alternative solution: #include <vector> static std::vector<int> myVector(4,100); bool init() { myVector[0] = 42; return true; } bool initresult = init(); int main() { ; }
788,814
788,825
Writing a simple parser
I need to write a simple parser to a sort of Domain Specific Language. It needs to have basic arithmatics with proper operators evaluation order and a syntax to call functions of the underlying environment which can be overloaded. What is the simplest way to write such a parser? Is there something I can adapt or use out of the box? I'm writing in C++.
Take a look at Boost Spirit.
788,940
788,946
How to synchronize SVN revision and version ressources of EXE/DLL files?
Say I have some C++ project which builds an exe or dll file. The project is checked into a SVN repository. I want to automatically synchronize the revision from SVN with the version resource embedded in my exe/dll file, i.e. the version should be something like $major.$minor.$svn_revision. Any ideas on how to achieve this? Are there any out-of-the-box solutions available?
If you have TortoiseSVN installed, then there is a program installed with it, SubWCRev. If, in your file, you have this value: $WCREV$ Then it'll be replaced with the highest committed revision number if you execute something like this: SubWCRev .\ yourfile.txt.template yourfile.txt This will copy from yourfile.txt.template, do the substitutions, and write to yourfile.txt. Note that there's a lot of other macros you can use as well, if you execute SubWCRev without any arguments, it'll list them all on the console.
788,953
788,969
What happens if my app is out of memory?
If my application is out of memory when i call new() i will get exception and malloc() i will get 0 pointer. But what if i call a method with some local variables? They occupy memory too. Is there some way to reserve memory for "normal" variables? So that even though new() throws exception i can just catch it, fix stuff and still call methods like usual.
The compiler knows how much of memory per stack you need. However, sufficiently high number of stacks (caused due to recursion) will crash your program -- there probably isn't another way to fix this. The standard has an interesting annexure called Implementation Quantities. This is non-normative (informative) and hence should not be treated as the absolute truth, but provides you with a fair idea.
789,061
789,442
How to create separate library for include in C++/Eclipse
I've gotten some C++ code to work with the TinyXML parser. However, to do this I had to include the source code from TinyXML with my regular source code. I'd like to have TinyXML included as a separate library. I'm using Eclipse with the Cygwin C++ compiler. What's a good way to do this?
I assume you want to separate the library from your own project's source code... but you don't know how to build when the library is not in the same folder. Assuming your library has precompiled *.lib and *.h files: Move the library source code to a separate directory Menubar "project" Menu "properties" will open a dialog box for all the project properties there will be a list on the left. List item "C/C++ Build" will change the GUI and show you all the options for gcc's compiler/linker/assembler ( I never do assembly... so I never do anything with the assembler ). [1] GCC C Compiler --> Directories: Green plus icon [2] --> Specify the path of your *.h files Your compiler should now be happy ( but you will fail linking because the linker doesn't know what the actual definitions of each function are ) GCC C Linker --> Libraries: Library search path (-L) --> Green plus icon --> Specify the path of your *.lib files Libraries (-l) --> Green plus icon --> Specify the name of each library you are using Your linker should now be happy and your code should compile [Footnote - 1] The GUI C/C++ build pane is a wrapper for gcc's command line compiler/linker... it is just making it easier to use because it shows you everything visually. [Footnote - 2] The '+' icon is what will tell the compiler where your libraries *.h include files are located. The compiler needs the *.h files to know what function prototypes your library has before it compiles. Assuming you have the actual ( not compiled ) *.c and *.h: Do the same steps above except in step 7. At step 7. you need to make sure the library's *.c files are seen by Eclipse's "managed make". If it doesn't see the source code then you need to specify where the source is so that it will compile it.
789,159
789,199
How do I find the shortest path that covers all nodes in a directed cyclic graph?
I need an example of the shortest path of a directed cyclic graph from one node (it should reach to all nodes of the graph from a node that will be the input). Please if there is an example, I need it in C++, or the algorithm.
EDIT: Oops, misread the question. Thanks @jfclavette for picking this up. Old answer is at the end. The problem you're trying to solve is called the Travelling salesman problem. There are many potential solutions, but it's NP-complete so you won't be able to solve for large graphs. Old answer: What you're trying to find is called the girth of a graph. It can be solved by setting the distances from a node to itself to infinity and using the Floyd-Warshall algorithm. The length of the shortest cycle from node i is then just the entry in position ii.
789,278
789,330
Differences between UNIX and Windows development
I've been programming in C and C++ in Linux for around 3 years, and recently have been interested in developing commercial software for businesses. Let's say I've found a niche where I think I could be successful, but that they only use Windows. I have no experience whatsoever with the Windows API, however. I have a few questions: Should I learn .NET? Do I need to learn C# in order to use .NET, or can I stick with C++? What is the sentiment about compiling using GCC under Cygwin with the --no-cygwin option? I'm interested in portability, and I'm worried that if I start writing for VC++, I might get bound to Windows. Where is a good place to do my essential reading? What else can you tell me about transitioning from Linux to Windows programming?
I faced exactly the same questions and I am so happy I tried .NET. I hope this info can help you: Should I learn .NET? I would highly recomment it. Do I need to learn C# in order to use .NET, or can I stick with C++? You can stick with C++ but I am sure you will love to learn C#, please try it. You will be able to mix them too. The main challenge with .NET is to learn all the libraries that are out there to help you out (so you do not need to reinvent the wheel). Use msdn often and try to get a map of the fundamental classes and assemblies. It is a fun experience if you come from C++ you should not have major problems. Where is a good place to do my essential reading? I would start with something light, check the free Visual Studio tools, software and examples here, go to the MSDN documentation and compile some of the examples in MSDN (how to access files,...). As you can see you will find C# and C++ examples side by side. Then of course books like C# via CLR will eventually need to be read. Portability Be sure you run your code in Mono and multiple platforms. Future investment Investing on learning the .NET framework will pay back. Today is costly to learn all the new tools out there, with .NET you know you can evolve. New features and languages appear but the fundamental classes remain so your time/effort investment is more under control.
789,402
789,414
typeid() returns extra characters in g++
class foo { public: void say_type_name() { std::cout << typeid(this).name() << std::endl; } }; int main() { foo f;; f.say_type_name(); } Above code prints P3foo on my ubuntu machine with g++. I am not getting why it is printing P3foo instead of just foo. If I change the code like std::cout << typeid(*this).name() << std::endl; it prints 3foo. Any thoughts?
Because it is a pointer to foo. And foo has 3 characters. So it becomes P3foo. The other one has type foo, so it becomes 3foo. Note that the text is implementation dependent, and in this case GCC just gives you the internal, mangled name. Enter that mangled name into the program c++filt to get the unmangled name: $ c++filt -t P3foo foo*
789,421
789,433
C++ static global objects workarounds?
I have a C++ program that crashed due to a bug. It would not even get to main as a NULL pointer was accessed in one of its static global object's contructor functions. To make matters worse the pointer was NULL but should have been set by another global static variable. I think I can wrap those globals in a function that sets global pointers to the objects. I know that need to redesign the globals out. I also know that the order of global static objects is not known. I remain curious--is there is a good accepted method to control the order of static global object initialization? SIMPLIFIED EXAMPLE (REMOVED ERROR CHECKING LOGGING ETC) [game.cpp] Point UpperLeft(-1024.1024); //Global Evilness int InitializeGobals() { ... } int main (int argc, char ** argv) { if (!InitializeGame()) Die("Initialization Failure"); WriteHighScore(UpperLeft); } I want to specify the all the static objects in order using: [prposedgame.cpp] Point *UpperLeft; int InitializeGobals() { Point IGUpperLeft = new Point(-1024.1024); UpperLeft = &IGUpperLeft; ... } int main (int argc, char ** argv) { if (!InitializeGame()) Die("Initialization Failure"); WriteHighScore(UpperLeft); } [NOT REALLY RELEVANT BUT MAY HELP UNDERSTANDING THE PROBLEM] [Point.cpp] Point::Point() { x = 0; y = 0; } Point::Point(int nx, int ny) { x = nx; y = ny; strcpy(text,0); //0 should have been set by another global static object } [Point.h] #ifndef POINT_H #define POINT_H class Point { public: Point(); Point(int nx, int ny); int getX(); int getY(); int getText(*pcbuff); private: int x; int y; char text[2]; }; #endif
One way to control the instantiation of static objects is to use construct on first use idiom as explained in this FAQ
789,426
789,451
Rotate a string in c++?
I'm looking for a way to rotate a string in c++. I spend all of my time in python, so my c++ is very rusty. Here is what I want it to do: if I have a string 'abcde' I want it changed to 'bcdea' (first character moved to the end). Here is how I did it in python: def rotate(s): return s[1:] + s[:1] I'm not sure how to do it in cpp. Maybe use an array of chars?
I recommend std::rotate: std::rotate(s.begin(), s.begin() + 1, s.end());
789,448
789,458
C++ Explicit Superclass Constructor Problem While Using Header Files
I seem to be having a very frustrating time with an inherited class calling an explicit superclass constructor. I just can't seem to get the syntax right! All the examples I have seen on the matter so far do not separate out the header and in-line class definition (using {}'s) from forward-declarations with a header file, so I'm not sure of how to cover the syntax between the .h and .cc files. Any help would be appreciated! Here is the error the compiler gives me (gcc) : serverconnection.h: In constructor "ServerConnection::ServerConnection(std::string, std::string)": serverconnection.h:25: error: expected `{' at end of input serverconnection.cc: At global scope: serverconnection.cc:20: error: redefinition of "ServerConnection::ServerConnection(std::string, unsigned int, short unsigned int, PacketSender*, int)" serverconnection.h:25: error: "ServerConnection::ServerConnection(std::string, unsigned int, short unsigned int, PacketSender*, int)" previously defined here serverconnection.cc: In constructor "ServerConnection::ServerConnection(std::string, std::string)": serverconnection.cc:20: error: no matching function for call to "Connection::Connection()" I understand that it is trying to call the default Connection constructor, Connection(), as it just doesn't understand my syntax. Here is the code: connection.h : class Connection { public: Connection(string myOwnArg); }; connection.cc : #include "connection.h" Connection::Connection(string myOwnArg) { //do my constructor stuff } serverconnection.h : #include "connection.h" class ServerConnection : public Connection { public: ServerConnection(string myOwnArg, string superClassArg) : Connection(superClassArg); }; serverconnection.cc : #include "serverconnection.h" #include "connection.h" ServerConnection::ServerConnection(string myOwnArg, string superClassArg) { //do my constructor stuff } Thanks so much in advance!
You don't put the initializer list in the class declaration, but in the function defininition. Remove it from the header, and in your .cc file: #include "serverconnection.h" #include "connection.h" ServerConnection::ServerConnection(string myOwnArg, string superClassArg) : Connection(superClassArg) { //do my constructor stuff }
789,532
789,567
QList and shared_ptr
What do you think? Is this correct or are there memory leaks? Source: #include <QList.h> #include <boost/shared_ptr.hpp> #include <iostream> class A { private: int m_data; public: A(int value=0) { m_data = value; } ~A() { std::cout << "destroying A(" << m_data << ")" << std::endl; } operator int() const { return m_data; } }; int _tmain(int argc, _TCHAR* argv[]) { QList<boost::shared_ptr<A> > list; list.append(boost::shared_ptr<A>(new A(6))); std::cout << int(*(list.at(0))) << std::endl; return 0; } Output: 6 destroying A(6)
It seems correct. Boost's shared_ptr is a reference counting pointer. Reference counting is able to reclaim memory if there are no circular references between objects. In your case, objects of class A do not reference any other objects. Thus, you can use shared_ptr without worries. Also, the ownership semantics allow shared_ptrs to be used in STL (and Qt) containers.
789,611
789,624
Embedding data inside a c++ application
Is there a platform-independent method to embed file data into a c++ program? For instance, I am making a game, and the levels are stored in text format. But I don't want to distribute those text files with the game itself. What are my options?
This has been asked here before. Basically, you just name the data with an accessible symbol. I like this method best: You can always write a small program or script to convert your text file into a header > > file and run it as part of your build process.
789,656
799,451
What's wrong with my KD-Tree? (K=2)
More specifically, there's something wrong with my nearest neighbor search. I've confirmed that the tree is built correctly, and that all the helper functions work as expected. Note this differs slightly from standard KD-trees in that I'm looking for the closest 3 points. struct Node { unsigned int axis; Point* obj; struct Node* left; struct Node* right; }; void _findClosest(struct Node* current, Point* to, Point** first, Point** second, Point** third, unsigned int depth) { if(current == NULL) return; if(current->left == NULL && current->right == NULL) { //_setOrder updates first, second, and third so that they point to //objects that are closest to "to", given an object and the current //current first, second, and third. _setOrder(to, current->obj, first, second, third); return; } unsigned int axis = depth % 2; struct Node* other = NULL; if(to->getValue(axis) < current->obj->getValue(axis)) { other = current->right; _findClosest(current->left, to, first, second, third, depth+1); } else { other = current->left; _findClosest(current->right, to, first, second, third, depth+1); } _setOrder(to, current->obj, first, second, third); if(other == NULL) return; double searchToBest = _largestDistance(to, *first, *second, *third); double searchToSplit = _distance(to, current->obj, current->axis); //This branch is ALWAYS taken, so this devolves into an O(n) search if(searchToBest >= searchToSplit) { _findClosest(other, to, first, second, third, depth+1); } } I imagine I'm just misunderstanding the data structure/algorithm in some way. Minor details: -if the distance functions are called on NULL objects, they return std::numberic_limits::max() -this is called on the root of the KD-tree, with a depth of 0, and *first = *second = *third = NULL -axis = 0 corresponds to X, axis = 1 corresponds to Y The problem is that every node is visited, rather than seeing the expected reductions from exploiting tree properties. Whatever the flaw is, it makes this a O(n) search.
This line is wrong: double searchToSplit = _distance(to, current->obj, current->axis); You want axis, not current->axis.
789,659
789,680
What is the best approach for a Java developer to learn C++
I consider myself an experienced Java developer and am planning to get started with learning C++. If you had same experience, i.e learn C++ after Java, I would like to hear your thoughts on what is the best approach at doing this. [Update] "the best approach" was not well quantified. What I am looking for is to leverage my existing java knowledge and programming experience so that I can quickly ramp up on C++.
I've taught C++ to Java people, even though I learned them the other direction. Are you comfortable with C? If not, read Kernighan and Ritchie. Many many peculiarities of C++ are explained by the desire for C++ to be a "Better C" with C's basic expression syntax. You should get Stroustrup. I think well of Thinking in C++ by Bruce Eckels. I've used The C++ FAQ Book, by Cline, Lomow, and Girou; I refer to it pretty often. Marshall Cline has C++ FAQ content on his site, too. Update You might also look at C++ for Java Programmers. I don't know the book but it looks decent.
789,817
790,109
How to use TinyXml to parse for a specific element
I would like to parse a group of elements out of a TinyXml output. Essentially, I need to pick out any port element's "portid" attribute of the port has a state of "open" (shown below for port 23). What's the best way to do this? Here's the (simplified) listing for the output from TinyXml: <?xml version="1.0" ?> <nmaprun> <host> <ports> <port protocol="tcp" portid="22"> <state state="filtered"/> </port> <port protocol="tcp" portid="23"> <state state="open "/> </port> <port protocol="tcp" portid="24"> <state state="filtered" /> </port> <port protocol="tcp" portid="25"> <state state="filtered" /> </port> <port protocol="tcp" portid="80"> <state state="filtered" /> </port> </ports> </host> </nmaprun>
This will roughly do it: TiXmlHandle docHandle( &doc ); TiXmlElement* child = docHandle.FirstChild( "nmaprun" ).FirstChild( "host" ).FirstChild( "ports" ).FirstChild( "port" ).ToElement(); int port; string state; for( child; child; child=child->NextSiblingElement() ) { port = atoi(child->Attribute( "portid")); TiXmlElement* state_el = child->FirstChild()->ToElement(); state = state_el->Attribute( "state" ); if ("filtered" == state) cout << "port: " << port << " is filtered! " << endl; else cout << "port: " << port << " is unfiltered! " << endl; }
789,954
790,050
boost::filter_iterator -- how would I do that with the STL?
I am passed an Iterator and I have to pass it on to another function -- but filtered so that certain elements are skipped (it's a range of pointers, and I want to filter out the NULL pointers). I googled for "stl filter iterator" to see how to do this, and boost::filter_iterator came up. That looks nice and I could use it, but could I do that with the good old STL as well? Without copying the elements into a new container, of course. I guess I'd have to create another iterator class that provides the necessary begin(), end() etc functions and does the filtering? So I'd exactly have to reimplement the boost iterator_filter...?
You are correct; you would essentially be recreating the filter iterator yourself. My advice would be to use Boost's filter_iterator. Boost has special status as c++'s most used external library; many c++ committee members have helped write libraries for boost. Its ubiquity essentially makes it almost-stl as is; there's really no reason to reinvent the wheel here.
790,239
876,160
Getting File Version Information fails -- But not for me
I am trying to get version information from a file. My code works perfectly for me, but fails on several others' machines. Because I can't reproduce the bug, I'm having quite a time finding the issue. Does anyone see anything majorly wrong with this? LPBYTE versionInformationBlock; struct LANGANDCODEPAGE { WORD wLanguage; WORD wCodePage; } *langBlockPointer; UINT translationsCount; void fileData::enumVersionInformationBlock() { bits.set(VERSIONINFOCHECKED); disable64.disableFS(); //Shut down WOW64 DWORD zero = 0; DWORD lengthOfVersionData = GetFileVersionInfoSize(getFileName().c_str(),&zero); if (!lengthOfVersionData) { disable64.enableFS(); return; } versionInformationBlock = new BYTE[lengthOfVersionData]; GetFileVersionInfo(getFileName().c_str(),zero,lengthOfVersionData,versionInformationBlock); VerQueryValue(versionInformationBlock,L"\\VarFileInfo\\Translation",(LPVOID*)&langBlockPointer,&translationsCount); translationsCount /= sizeof(struct LANGANDCODEPAGE); disable64.enableFS(); } std::wstring fileData::getVersionInformationString(const std::wstring& str) { if (!bits[VERSIONINFOCHECKED]) enumVersionInformationBlock(); if (!versionInformationBlock) return L"!VERINFO: NOT PE FILE!"; LPCTSTR retString; UINT retStringLength; std::wstring result; static const wchar_t hexChars[] = L"0123456789ABCDEF"; wchar_t hexLanguage[26] = L"\\StringFileInfo\\ \\"; for( size_t idx = 0; idx < translationsCount; idx++ ) { hexLanguage[16] = *(hexChars + ((langBlockPointer[idx].wLanguage >> 12) & 0x0F)); hexLanguage[17] = *(hexChars + ((langBlockPointer[idx].wLanguage >> 8 ) & 0x0F)); hexLanguage[18] = *(hexChars + ((langBlockPointer[idx].wLanguage >> 4 ) & 0x0F)); hexLanguage[19] = *(hexChars + ( langBlockPointer[idx].wLanguage & 0x0F)); hexLanguage[20] = *(hexChars + ((langBlockPointer[idx].wCodePage >> 12) & 0x0F)); hexLanguage[21] = *(hexChars + ((langBlockPointer[idx].wCodePage >> 8 ) & 0x0F)); hexLanguage[22] = *(hexChars + ((langBlockPointer[idx].wCodePage >> 4 ) & 0x0F)); hexLanguage[23] = *(hexChars + ( langBlockPointer[idx].wCodePage & 0x0F)); std::wstring targetResource(hexLanguage,25); targetResource.append(str); if (!VerQueryValue(versionInformationBlock,targetResource.c_str(),(LPVOID *)&retString,&retStringLength)) { return std::wstring(L"!DOESN'T APPER TO EXIST IN FILE! ERROR: ").append(boost::lexical_cast<std::wstring>(GetLastError())); } retStringLength--; if (!result.empty()) result.append(L" / "); std::wstring toAppend; toAppend.assign(retString,retStringLength); boost::algorithm::trim(toAppend); result.append(toAppend); } return result; } std::wstring fileData::getVerCompany() { return getVersionInformationString(L"CompanyName"); } ~fileData() { if (versionInformationBlock) delete [] versionInformationBlock; }; What's really bugging me is that it isn't throwing any of my error messages... it keeps returning garbage. Any ideas? Billy3
nvm. Seems Stackoverflow beats the heck out of me if it isn't answered..... Billy3
790,407
790,432
Debugging using gdb - Best practices
I am a beginner in GDB and I got it working correctly. However, I am wondering how this is used in big projects. I have a project where build is done using makefile and g++. For GDB to work, we need to compile with debug symbols on, right (g++ -g files)? Question Do I need to create a new target in makefile something like "debug", so that I can make a debug build like make debug. Is this the best practice? Suppose, I need to debug only foo.cpp and is it possible to generate debug symbols only for that other than building whole program including main? Any thoughts?
Not needed, although you may want to consider always building with -g (sometimes, you may even need to try and debug optimized (-O1, -O2, etc) code; why not leave -g on? For releases, you can always just run strip on the binary. Yes. Build just that file with -g .
790,494
790,531
What's the most brilliant use of templates you've ever encountered?
We all know the usual use of templates to design containers and we all know that you can do things with templates that will make your head spin. When I first encoutered static polymorphism I was really struck on what you can do with templates. It's obvious that templates are useful for more than for designing containers. I bought Andrei's "Modern C+ Design" but sadly haven't yet found the time or concentration to read it but I'm sure it offers a wealth of brilliant uses of templates. IMHO this is also a very clever use of templates. What's the most ingenious use of templates you've ever encountered?
boost's Spirit meta programming for creating a parser's grammar.
790,538
790,544
Adding values from file to a hash type structure in C++
I have a space separated file which contains some key->value pairs. These are to be loaded to a structure of the type given below: #define FV_PARAM1 "A" #define FV_PARAM2 "B" parameter_t & parameterFeatureVector ( parameter_t & param, int param1, int param2, ) { param.addParam(FV_PARAM1, param1); param.addParam(FV_PARAM2, param2); return param; } So to the above, I can pass the following values: parameterFeatureVector( 10, 20 ); And I would expect the same to get loaded to 'param' structure. The above values are taken from the file. How would I go about implementing the same. If the above is not clear, do feel free to get back on it.
I take it you are asking how to translate a name "A" to a specific structure field? If So, C++ has no built-in way of doing that - you have to write a function: void Add( parameter_t & p, const std::string & name, int value ) { if ( name == "A" ) { p.param1 = value; } else if ( name == "B" ) { p.param2 = value; } else if ( .... ) { // more name tests here } } However, I would suggest not doing that, and instead use a map: std::map <std::string, int> params; you can then say things like: params["A"] = 42;
790,552
790,593
Calling a function with different number of threads passed to the application
I have a function which needs to be invoked with a different number of threads each time (am doing some performance calculation, so need to know when the performance starts deteriorating). Example is given below: getTime() { return 0; } int main() { boost::threadpool::thread_pool<> threads(nThreads); for(int j = 0; j <= nLines; j++){ threads.schedule(boost::bind(&getTime, nThreads, 1)); } threads.wait(); } Where, nThreads: A value given at the command line My question is, would this give me the desired result, as to would this call the 'getTime' function with 'nThreads' each time the for loop is accessed by the program? Or do I need some other method to find out the same? what i really want to do is this: boost::threadpool::thread_pool<> threads(nThreads); // start a new thread that calls the "getTime" function for(int j = 0; j <= nLines; j++){ //threads.schedule(boost::bind(&getTime, nThreads, 1)); threads.schedule(boost::bind(&getTime, 0, nLines, pc)); } (not sure which of the above is correct.) the getTime() function is to be run with a specified number of lines which i get from a text file and give each line to a api, whose performance i wish to calculate. but this is unrelated to the question i have. i wish to call a function with different number of threads each time and calculate how much time it took each thread to finish. what was the total time taken with 1 thread, what was the total time taken by 2 threads to finish, etc.
If i understand correctly, what you really want to do is something like this : int main() { int nbThreads = 20; boost::threadpool::thread_pool<> threads(nbThreads); for(int threadId = 0; threadId <= nbThreads ; ++threadId) { threads.schedule(getTime); } threads.wait(); } If i am right, you don't need to use boost::bind here. Note that Boost.ThreadPool is not part of Boost (yet? it ). It will be reviewed, but no review date has been planned yet.
790,553
790,704
Thread-safe C++ stack
I'm new to C++ and am writing a multi-threaded app whereby different writers will be pushing objects onto a stack and readers pulling them off the stack (or at least pushing the pointer to an object).. Are there any structures built-into C++ which can handle this without adding locking code etc.? If not, what about the Boost libraries? EDIT: Hi. Thanks for the initial great answers. I guess one reason I thought this could be built-in was that I was thinking purely in x86 space and thought that a PUSH/POP of pointers should be an atomic action at the instruction level. I'm not sure if my initial hunch is true or not, but I guess this would not necessarily be true across all platforms. Though if running on x86, do you get atomic PUSHes and POPs to the stack and if so, does this essentially make it lock-free?
Yep: Boost.Thread is great, and should fit your needs very well. (These days, many people say that you could almost count Boost as built-in functionality.) There is still no class that you could use out-of-the-box, but once you have the synchronization primitives at hand, it really is quite simple to implement your own thread-safe wrapper around, for example, std::stack. It could look something like this (not implementing every method...): template <typename T> class MyThreadSafeStack { public: void push(const T& item) { boost::mutex::scoped_lock lock(m_mutex); m_stack.push(item); } void pop() { boost::mutex::scoped_lock lock(m_mutex); m_stack.pop(); } T top() const { // note that we shouldn't return a reference, // because another thread might pop() this // object in the meanwhile boost::mutex::scoped_lock lock(m_mutex); return m_stack.top(); } private: mutable boost::mutex m_mutex; std::stack<T> m_stack; } If you are new to C++, please learn about RAII. Relevant to this case, Boost.Thread has the "scoped lock" classes to make it difficult to shoot yourself in the leg by forgetting to release a lock. If you ever find yourself writing code like this: void doStuff() { myLock.lock(); if (!condition) { reportError(); myLock.unlock(); return; } try { doStuffThatMayThrow(); } catch (std::exception& e) { myLock.unlock(); throw e; } doMoreStuff(); myLock.unlock(); } , then you should just say no, and go RAII instead (syntax not directly from Boost): void doStuff() { scoped_lock lock; if (!condition) { reportError(); return; } doStuffThatMayThrow(); doMoreStuff(); } The point is that when the scoped_lock object goes out of scope, its destructor releases the resource -- in this case, the lock. This will always happen, no matter whether you exit the scope by throwing an exception, or by executing the odd return statement that your colleague sneakily added in the middle of your function, or simply by reaching the end of the function.