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
7,241,870
7,241,893
Killing a process leaves zombie process to haunt me... :(
I have a program wherein i use fork. In the child process, i just login to a remote server and executes a command. In the parent process, i wait for the child to finish its task. If it doesnot finish it in a predetermined amount of time, i kill the child process using kill(child_pid, SIGTERM). But i have noticed that t...
Even if you kill the child, you still need to wait for it.
7,241,871
7,242,021
Loading a file into a vector<char>
I would like to load the contents of a text file into a vector<char> (or into any char input iterator, if that is possible). Currently my code looks like this: std::vector<char> vec; std::ifstream file("test.txt"); assert(file.is_open()); while (!(file.eof() || file.fail())) { char buffer[100]; file.read(buffer...
Another approach, using rdbuf() to read the whole file to a std::stringstream first: #include <fstream> #include <sstream> #include <vector> #include <string> // for check: #include <algorithm> #include <iterator> #include <iostream> int main() { std::ifstream file("test.cc"); std::ostringstream ss; ss << fi...
7,241,993
7,242,294
Is it smart to replace boost::thread and boost::mutex with c++11 equivalents?
Motivation: reason why I'm considering it is that my genius project manager thinks that boost is another dependency and that it is horrible because "you depend on it"(I tried explaining the quality of boost, then gave up after some time :( ). Smaller reason why I would like to do it is that I would like to learn c++11...
There are several differences between Boost.Thread and the C++11 standard thread library: Boost supports thread cancellation, C++11 threads do not C++11 supports std::async, but Boost does not Boost has a boost::shared_mutex for multiple-reader/single-writer locking. The analogous std::shared_timed_mutex is available ...
7,242,002
7,242,102
Putting arrays into another array
How do I store a list of arrays into another set of array? I tried this way but it doesn't work. float data1[5] = {150.0, 203.0, 165.0, 4.0, 36.0}; float data2[5] = {249.0, 255.0, 253.0, 104.0, 2.0}; float allData[2] = {data1, data2}; cout << allData[1][2] << endl; //this should print 253.0 but it has error This...
You should use vectors (this example is in C++11): std::vector<float> data1 = {150.0, 203.0, 165.0, 4.0, 36.0}; std::vector<float> data2 = {249.0, 255.0, 253.0, 104.0, 2.0}; std::vector<std::vector<float>> allData = {data1, data2}; std::cout << allData[0][0] << std::endl; Note: possibly you want to store pointers to ...
7,242,225
7,243,809
Why OpenGL fog just doesn't appear?
This is how I enable fog in OpenGL: float fog_colour[4] = {1,1,1,1}; glEnable(GL_FOG); glFogf(GL_FOG_MODE,GL_EXP2); glFogfv(GL_FOG_COLOR,fog_colour); glFogf(GL_FOG_DENSITY,0.5); glHint(GL_FOG_HINT,GL_NICEST); glFogf(GL_FOG_START,0.1); glFogf(GL_FOG_END,100); Every object is in the range 0.1-100, but fog just doesn't a...
The problem is the GL_EXP2 mode. If you check the formula for the fog blending factor in GL_EXP2 mode: f = e ^ ((-density * z) ^2) (clamped to [0..1]) The fog curve is adjusted exclusively with the density parameter. If your range is 0.1-100, I would recommend a density of about 0.001. Anyway, for testing fog is bett...
7,242,271
7,242,321
C++ Align by structure size or largest alignment requirement among its members?
Take this structure for example: struct Packing { int x; // 4-byte align int y; // 4-byte align short int z; // 2-byte align char m; // 1-byte align; char _pad[1]; // explicit padding }; The sizeof this structure is 12-bytes. So should store this struct in addresses multiples of the struct si...
The optimal alignment for a struct is equal to the largest alignment for any of the struct's members. In this case that is 4. Update The above assumes that the primary operation you perform on the struct is accessing its members. See the comments to Necrolis's answer for more discussion. In short I suspect that the rea...
7,242,354
7,242,628
Checking if caller and parameter are the same
For example I have four classes like: class A; class B{ protected: void check(const A &a); }; class C : public A, public B; class D : public B; Now I would like to write check function that does nothing if the caller and parameter are the same: void B::check(const A &a){ if(*this != a){ //do something ...
This would work if you add a virtual destructor to A: void B::check(const A &a) { if (dynamic_cast<const B*>(&a) == this) { std::cout << "same object" << std::endl; } }
7,242,430
7,243,745
PE problem - with a packer
I am trying ti make my own packer, and my packer works fine with executable compiled VC++ 6, but when I try to pack executable compiled with VC++ 8, the executable will crash. So I wanted to know if there is any change in the PE structure in the new versions of C++?
There has been no change to the PE File format, and as commenters above point out it is not related to your problem. It sounds like your packer is dependent on the VC++6 runtime libraries and as such when it unpacks something that is expecting VC++8 libraries bad things happen. The solution would be to make your packer...
7,242,493
7,242,592
How to create a memory leak in C++?
I was just wondering how you could create a system memory leak using C++. I have done some googling on this but not much came up, I am aware that it is not really feasible to do it in C# as it is managed code but wondered if there was a simple way to do this with C++? I just thought it would be interesting to see how m...
A memory leak occurs when you call new without calling a corresponding delete later. As illustrated in this sample code: int main() { // OK int * p = new int; delete p; // Memory leak int * q = new int; // no delete }
7,242,512
7,242,723
opening a file (and closing it later) only if flag is set
In my program I have currently a piece of code that looks like this void foo() { // defining local variables for (long i =0; i<maxiterations; i++) { // here the core of the code is executed // for each iteration an object of a class is created and modified given the conditions imposed }...
suggestion: FILE* f = NULL; if (flag) f = openfile(); for (long i =0; i<maxiterations; i++) { // executing the same as before if (flag) savedata(i, f); // pass in filehandle, obviously the function would be modified } if (flag) closefile(f); //close file on handle passed.
7,242,647
7,242,692
Enforce a 2GB memory space for a 64-bit process
Rather a theoretical question -- would anyone know how it were possible to make sure a 64-bit process is allocated no more than 2GB of continuous memory. This came up during the porting of a 32-bit C++ application that does pointer arithmetic (bad!) and relies on subtraction results to fit on a 32-bit integer. Before f...
The C and C++ standards do not require calls to malloc() or operator new to return memory that is contiguous with previously-returned memory, and few modern systems would given how virtual memory is doled out in a process. You may be SOL on that front unless you can tell us which platform you're targetting (there may b...
7,242,667
7,242,789
How to resize std::vector with unique objects
I have a vector of objects. Each object has a boost::shared_ptr to a noncopyable object (a boost::signal). the object's default constructor creates the boost::signal object. struct FuncRef { typedef boost::signal0<void, > Func; boost::shared_ptr <Func> function; FuncRef(): function(new Func) { ...
The only way I can think of is to use reserve to make the vector allocate the memory you need (as @Jonathan answered). You can the use generate_n with an std::back_inserter to add the elements: FuncRef makeFuncRef() { return FuncRef(); } vec.reserve(vec.size() + n); std::generate(std::back_inserter(vec), n, makeFu...
7,242,916
7,244,209
Is a thread-safe queue a good approach?
I am looking for a way to optimize the following code, for an open source project that I develop, or make it more performant by moving the heavy work to another thread. void ProfilerCommunication::AddVisitPoint(ULONG uniqueId) { CScopedLock<CMutex> lock(m_mutexResults); m_pVisitPoints->points[m_pVisitPoints->co...
Okay I'll add my own answer - concurrent_queue works very well using the details described in this MSDN article I implemented concurrent queue (and tasks and my first C++ lambda expression :) ) I didn't spend long thinking though as it is a spike. inline void AddVisitPoint(ULONG uniqueId) { m_queue.push(uniqueId); } ....
7,243,545
7,243,743
Memory and irrationality and floating numbers
Some numbers can not be stored in "memory bits" as their binary representation would make them go endlessly. In binary 11.111011101110... this is not the exact number. I can't remember exactly what it is right now. But we can think of it "like an irrational number" in our base 10 that goes on infinitely after decimal ...
All integer numbers are represented precisely. You are talking about fractional and irrational numbers, right? Irrational numbers cant be represented by binary digits as like by decimal ones. So they can be represented only with specific precision. The problem with fractional numbers is that not every decimal number ca...
7,243,683
7,245,070
How to enable IRQ8 in my OS kernel?
I want to know that, how to enable IRQ8 (RTC) in my own Kernel written in C++. I already have the module for installing interrupt handlers. But after installing IRQ8 interrupt handlers it doesn't generate any interrupt. So how can i enable IRQ8 ? and after enabling it what interrupt it will generate ? I know that RTC g...
I'm assuming you're working with an x86-based architecture, and if that's so, then you're also working with a 8259A programmable interrupt controller. If that's the case, IRQ8 is located on the second slave PIC, which is typically wired through IRQ2 on the master PIC. You are basically going to have to program IRQ2 o...
7,243,723
7,243,810
Simple way to split a sequence of null-separated strings in C++
I have a series of strings stored in a single array, separated by nulls (for example ['f', 'o', 'o', '\0', 'b', 'a', 'r', '\0'...]), and I need to split this into a std::vector<std::string> or similar. I could just write a 10-line loop to do this using std::find or strlen (in fact I just did), but I'm wondering if ther...
My two cents : const char* p = str; std::vector<std::string> vector; do { vector.push_back(std::string(p)); p += vector.back().size() + 1; } while ( // whatever condition applies );
7,243,725
7,243,972
Why is my string assignment causing a segmentation fault?
I've tried to eliminate the common causes of seg faults such as dereferencing a null pointer, but I'm stumped. This error does not appear on my test machine in debug mode, but does appear on my production machine the release compile. Both are set to /O0 to eliminate that as a possibility. When I comment out the stri...
The problem may not be in the call to tempname.assign(). Pipelining can result in somewhat erroneous reports of where the demon really lies. This statement makes me think the demon lies elsewhere: When I overloaded my control block to take a char* directly controlBlock->setFileName( &fileName.byte[0] ), and removed th...
7,243,734
7,249,532
Converting a sequence of bytes to ASCII representation and vice-versa
Suppose we have a vector of uint8_t: { 0x12 0x34 0xab 0xcd }. I've found that I can use ostringstream in order to convert it to a string "1234abcd" (no spaces, no 0x prefixes). But I couldn't simply convert it back with istringstream, apparently since it has no spaces. hex + setw(2) manipulators didn't help. Are there ...
You can create a proxy object that reads precisely two characters from your istringstream struct U8 { unsigned int datum; friend std::istream& operator>>(std::istream&is, U8& u) { char s[3] = "xx"; if(!((is>>s[0]) && (is>>s[1]) && (std::istringstream(s) >> std::hex >> u.datum))) is.setstate(std::ios::...
7,243,758
7,243,806
Base class undefined when including header file in .cpp file
I have the following interface declared in C#: public interface ArtistInterface { bool Flag { get; set; } string Artist { get; set; } int App { get; set; } } And I want to implemented in C++/CLI: implementation.h public ref class Artist: public ArtistInterface { Artist(String^ name); Artist(Strin...
Your C++/CLI project needs to reference your C# project, or the DLL built from the C# project. You wouldn't see this error until you had something to compile in your C++/CLI project (i.e. a .cpp file). In Visual Studio, right-click on the C++/CLI project and select References. Click the Add New Reference... button. Cho...
7,243,851
7,250,012
Accessing parent functions from child form in c++
I have seen a couple of solutions to this problem in c# or PHP or even action script, but not in c++. I have a parent form which calls a child form by newing it and calling ShowWindow on it. I now need the child form to be able to call one of the parent form's (public) functions. My first thought was to pass the pare...
It appears that the best way to do this is as follows: Parent.h: class Child; class Parent{ public: Parent(){ //Constructor } Parent.cpp: #include Child.h //declare a child ie. Child chld = new Child(this); Child.h: class Parent; class Child{ public: Child(){ //Constructor } Child.cpp: #include Parent.h Parent prn...
7,244,030
7,244,233
GoF's implementation of the Prototype pattern
(This question is more for the people who have access to the book, It's hard to put it into context otherwise) I've been reading through the GoF's 'Design Patterns' book and there's a sentence that confuses me a little, under 'Creational Patterns->Prototype->Sample code' (page 124). Near the bottom of the page, there...
I gave an answer and totally rewrote it now :) Basically, the MazePrototypeFactory only knows about the base classes it can use. It doesn't know anything about any of the subclasses you are going to make, but it still should be able to put any possible subclass out there into the maze. The pattern basically ensures Maz...
7,244,363
7,244,420
Copy constructor not being called on function result
GCC inlines a statement -- no matter how hard I try to prevent it. I tried -fno-inline -O0 __attribute__ ((noinline)) dummy asm("") No success! Here the code: #include<iostream> using namespace std; struct A { A() {cout << "A::A()" <<endl; } A(const A& a) {cout << "A::A(copy)" <<endl; } A& operator=(const A& ...
No, this has nothing to do with the function being inlined. Inlining the function would not change observable behaviour. This is an optimization called copy elision that allows the compiler to avoid a copy by constructing the return value directly at the destination. You can disable it with the g++ flag -fno-elide-cons...
7,244,458
7,244,609
Access Windows Sound?
I'd like to know a couple of things: 1.) How do I check how much noise / how loud all noises coming from the computer (Windows) are? 2.) How do I adjust the Windows volume? Thanks!
waveOutGetVolume: http://msdn.microsoft.com/en-us/library/dd743864(VS.85).aspx waveOutSetVolume: http://msdn.microsoft.com/en-us/library/dd743874(v=VS.85).aspx See this knowledgebase article: http://support.microsoft.com/kb/139098
7,244,471
7,247,715
How to handle step-by-step refactory of some heavily used libraries?
I have a couple of libraries that were targetting multiple platforms, of which some realtime ones that did/do not have decent STL support, let alone tr1 or C++11. This means everything uses the library's own string/array/list/younameit classes. Now these platforms are getting abandoned in favour of 'pure' C++11 and STL...
Don't duplicate classes. Let your old project run, and fork it somewhere. Of course, use unit testing and source control. Then, I'd go for a depth-first approach, a bit at a time. Change one class at a time to adapt it to the new coding standards, and solve all compiler errors that result. This means in particular that...
7,244,504
7,244,583
The program does not give the desired output . Wrong implementation of FIFO ?
This is a FIFO program using linked list . The program does not give the desired output but generates a long loop which stops after sometime and there is a message that the program has stopped working. What is the problem ? #include <iostream> using namespace std; struct node { int data; struct node* previ...
You are constructing queues and then abandoning them. You fail to update dataNode_P_A, so that you are not constructing a list so much as a tassel. You invoke dataNode_P_A++ when you clearly don't know what it means. You have written a long, complicated piece of code without testing it along the way. You should start o...
7,244,645
7,244,824
Porting VC++'s __try/__except EXCEPTION_STACK_OVERFLOW to MinGW
I am trying to port some code using VC++'s try-except statement to MinGW: bool success = true; __try { //... } __except ((EXCEPTION_STACK_OVERFLOW == GetExceptionCode()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { success = false; _resetstkoflw(); } return success; I...
You would need to manually call the Windows API functions which register exception handling; namely, AddVectoredExceptionHandler. Note that by using MinGW which does not respect SEH exceptions, throwing any SEH exception or attempting to catch any such exception will result in undefined behavior, because the normal C++...
7,244,881
7,244,962
compare two boost::function
void ff(int){} void Unscribe(const boost::function<void(int)>& f) { std::map<int, boost::function<void(int)> > map; map[0] = ff; if( map[0] == f) { } } Unscribe( ff ); I would like to be able to compare two boost::function with the same signature. What should I modified to get this code co...
You can't. Read the boost function FAQ's first entry: Why can't I compare boost::function objects with operator== or operator!=? Comparison between boost::function objects cannot be implemented "well", and therefore will not be implemented. ...
7,245,169
7,245,208
Creating a text label with a transparent background using WinAPI
Is it possible to create a label with a transparent background within a window using only WinAPI commands? I am trying to add an image to a Dialog window that will serve as a background image and then display text upon that image. Everything I have tried so far shows the text label on top of the background image with a...
I've found something that appears to be working, though since I am very new to programming in pure WinAPI this could well be very bad practice and I would have no idea! I am handling the WM_CTLCOLORSTATIC message as shown: case WM_CTLCOLORSTATIC: hdcStatic = (HDC) wParam; SetTextColor(hdcStatic, RGB(0,0,0)); ...
7,245,205
7,245,317
Flex4/AIR with NativeProcess: How to pass an image to the native process?
I am trying to make an AIR application, that needs to pass an image (.jpg/.png) to a C++ app, that does number crunching.(this needs to be done very often, like every 2-3 seconds.) I've managed to pass the image by saving it to disk via AIR, then opening this file with the C++ program (and passing the filename as an ar...
There are several ways to transmit data between two processes. One of the most efficient, and easy to setup, is to use TCP sockets. It means that your C/C++ will for (TCP/HTTP) requests, and that your AIR program will send the request with all data inside.
7,245,217
7,246,701
Libraries available for native modules
Applications for Android devices are written in Java. I also know of the existence of the NDK (Native Development Kit). I have a library written in C++ that uses: stl containers c++ i/o (streams etc..) memory allocation/deallocation using new etc... Are all this things available to the programmer that want to use the...
Yes, low level I/O is possible. fopen/fread are available from the first NDK release. istream/ostream are available since NDK r5 when STLport and GNU stl were added.
7,245,235
7,245,564
Syntax of C++ templates with function type parameters
I'm used to seeing syntax like this for function pointers int (*pointer_name) (float, char *); void call_function (void (*)(int), int); In some C++03 functional libraries I see types used this way: abc::function<void(*)(int,float)> f; In C++11's std::function I see the type given this way std::function<void(int,float...
std::function (and its inspiration, boost::function) does not only store function pointers. It can also store function objects. In that sense, passing a function signature as a template parameter is similar to how a smart pointer usually take the type of the pointee as a template parameter, not a pointer type! Contrast...
7,245,404
7,245,602
Reference to member function?
I recently find out that there is a reference-to-function concept in C++ :). So as there are pointer-to-function and pointer-to-member-function different types. The question arises. Is there a "reference-to-member-function" concept? I tried to compile the following code, but GCC 3.4.6 gives an error. #include <iostream...
There is no such a thing called reference to member in C++. The language specification explicitly says in a note (§8.3.3/3 - 2003) that, A pointer to member shall not point to a static member of a class (9.4), a member with reference type, or “cv void.” [Note: see also 5.3 and 5.5. The type “pointer to member” is dist...
7,245,411
7,245,438
C++ , winapi Compare two WCHAR * strings
I want to compare two WCHAR* strings. How to do it? P.S. I would like to ignore case while comparing. I know you can use strcmpi but it id not working for WCHAR*.
For case sensitive comparison, look at wcscmp For case insensitive comparison, look at _wcsicmp
7,245,817
7,259,675
Converting float to 32-bit hexadecimal C++
Could anyone please tell me if there is any code to convert floating point number to hexadecimal format? For Ex: float num = 70.482 and hexadecimal function should return 428CF6C9. If there are any codes already done before on this, kindly link me. Cheers.
something like this is the floattohex conversion i use.. (it also performs a bit swap, if you dont need this take it out) CString Class::FloatToHex(float* yourfloat) { unsigned char ch[4]; Cstring output; memcpy(ch,yourfloat,sizeof(float)); output.Format("%X%X%X%X",ch[3],ch[2],ch[1],ch[0]); return output; }
7,245,829
7,245,858
pointer to function assignment
Why the assignment without '&' is compiling in the following code? I compiled the code with GCC 3.4.6. Is it right to assign without &, or this is a "feature" of GCC? void func() { } int main() { typedef void (*F)(); F f; f = &func; // the way of assigning pointer to function. f = func; // this is also worki...
This is perfectly ok. Both statements are totally equivalent. The function lvalue is converted to a pointer to function through a standard conversion. §4.3/1: An lvalue of function type T can be converted to an rvalue of type “pointer to T.” The result is a pointer to the function.
7,245,962
7,254,691
Add application manifest to a win32 application in eclipse
How do I add an application manifest to a Win32 application being developed in Eclipse ? I want to add a manifest in order to use version 6 of Comctl32.dll which, according to this article is necessary to create form controls with a Windows XP visual style. I'm using MingW32 toolchain with eclipse.
To answer my own question: Add CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "YourApp.exe.manifest" to the .rc file before you compile it with MinGW resource compiler, windres
7,246,076
7,246,124
How can a delete[] operation crash while the destructor succeeds? (in C++)
I have a class Foo, which has a (simple) destructor. Some other class contains an array of Foo objects (called foolist), in the destructor of that class, I do: delete[] foolist; This crashes (gdb shows that it crashes in this exact line). However, by using printouts I see that all the elements in foolist are finishing...
The delete operator performs 2 functions under the hood Run Destructors Free Memory Given the printout confirms #1 is happening the most likely cause is a crash during the actual freeing of memory (the message indicates this as well). This typically indicates that the memory is being corrupted by another part of you...
7,246,414
7,246,470
Requirement for explicit type conversion
For static_cast, Is it true that, unless there exist a built-in type conversion function, you cannot use static_cast to perform conversion. But you can do a reinterpret_cast for a type, considering the return type is valid. int main() { WORD word; HWND hwnd = static_cast<HWND>(word); // error HWND hwnd = re...
reinterpret_cast just allows you to convert completely unrelated types. It just treats the chunk of memory as another type. So it is very unsafe to use it, since it just doesn't give you any compile or runtime errors but just causes (usually) crash static_cast provides compile time check of validity of an cast. If an t...
7,246,420
7,246,699
Changing .NET 4 Runtime Activation Policy For Dll Within C++ Code
We've developed a C# 4.0 module that needs to be accessed from an unmanaged C++ program (as well as a Fortran program). The DLL gets loaded correctly and the method is available to the C++ program, but an exception gets thrown when calling the method that points to the C# code. For a visualization: [Unmanaged C++ / For...
From my understanding, this is not possible. The issue is that, the configuration setting you need to apply (useLegacyV2RuntimeActivationPolicy) is basically saying "for this entire application, no matter what the assembly requests, use CLR 4 instead. If you could apply it to a single DLL, you'd be violating the goals ...
7,246,512
7,246,573
"#ifdef" inside a macro
Possible Duplicate: #ifdef inside #define How do I use the character "#" successfully inside a Macro? It screams when I do something like that: #define DO(WHAT) \ #ifdef DEBUG \ MyObj->WHAT() \ #endif \
You can't do that. You have to do something like this: #ifdef DEBUG #define DO(WHAT) MyObj->WHAT() #else #define DO(WHAT) do { } while(0) #endif The do { } while(0) avoids empty statements. See this question, for example.
7,246,544
7,247,463
What are the differences between gluProject and glhProject?
I don't know why the wiki of opengl.org says "gluProject" in title but in the code is "glhProject". Any differences?
It uses glh because the person who wrote that Wiki page wrote the glh library. And technically, it's not accurate, since those are not how gluProject and gluUnproject are implemented. I'm strongly considering deleting this page from the wiki, so thanks for pointing it out.
7,246,588
7,246,817
What is the best way to port a C++ library to C#?
I have a (header only) C++ library that I am looking to port to C#. It is a wrapper of the win api which I have made for a certain purpose. I want to port it to C# because I want to develop it further using C#. What is the most efficient (and easiest?) way to port it. Please note that I do not want something hectic bec...
It depends very much on how big your lib is, how it is structured, how your memory allocation looks like, how much you made use of libs not available in C# (like the C++ std lib), how much C++ template programming you have used etc. Different strategies may be try to port (parts of) it automatically by some code gener...
7,246,756
7,246,836
Android and the NDK/librarys
I have now admitted defeat that you cannot use/build a good audio pitch function without using the NDK. Now my question is does anyone know of any good pitch changing code either in a library or some source code for the NDK?
You could have a look at the MicDroid app that does auto-tune, sources available on GitHub: https://github.com/intervigilium/MicDroid some more info here: http://forum.xda-developers.com/showthread.php?t=721388
7,246,976
7,246,993
Why does this if executes while I have not given any input?
Here is my code snippet: int a; if(a=8) cout<<"Its right"; else cout<<"Not at all"; getch(); return(0); I'm getting the output Its right while I've not give any input there its just a assignment to the a=8. **Borland Compiler** gives the following 2 warnings and executes the code. 1: Possible incorrect assign...
When you write: if(a=8) You're assigning 8 to the variable a, and returning a, so you're effectively writing: a = 8; if(a) This is non-zero, and hence treated as "true". I (and the compiler) suspect you intended to write (note == instead of =): if(a==8) This is why you get the warnings. (Note that, in this case, a ...
7,246,996
7,247,082
How does this meta-programming compile down?
Here's an example from wikipedia that displays C++ template meta-programming: template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo() { int x = Factor...
Well, here's the generated assembly from GCC: ; command line used: gcc -c -S -fmasm-intel test.cpp .file "test.cpp" .intel_syntax noprefix .text .globl __Z3foov .def __Z3foov; .scl 2; .type 32; .endef __Z3foov: LFB0: push ebp LCFI0: mov ebp, esp LCFI1: sub esp, 16 LCFI2: ...
7,247,087
7,247,264
access a member of class using vector
I have a class defined as typedef std::string Name; typedef int Age; typedef std::string Level; class Employee { public: // Employee (arguments); // virtual ~Employee (); void name(Name const & name) { name_ = name; } Name name() const { return name_; } void age(Age const & age) { age_ = age; } ...
Unless I'm misinterpreting your question, this is simple enough. it is an iterator over the vector of Employee. *it is the Employee it-> lets you access members of that Employee e.g.: it->name() So, if you want to build a map of employee level to Employee, you can do this: std::map<Level, Employee> employeeMap; fo...
7,247,147
9,445,649
Can I Use mysql_real_connect to Connect to a Server Without Mentioning the Database Using MySQL/C?
I'm working on a CGI application written using C++ with the C MySQL adapter. I'm trying to run a query on two databases, so I want to connect to a MySQL server without choosing a default database. Is this possible? I'm using mysql_real_connect().
mysql_real_connect() can take a NULL parameter for the database paramter, and this selects the default. Just ensure that the user has no default database set.
7,247,153
7,247,173
Is default destructor of POD static?
I'm compiling with /Wall, and getting the warning C4100: 'ptr' : unreferenced formal parameter warning. The warning seems to be caused by calling the destructor on MSVC's std::_Container_proxy, which has a default destructor. My Code: template<class T> class linear_allocator { //...other declarations... static...
This is a known bug in Visual C++: "Visual C++ gives unexpected warning C4100 on explicit call to object destructor". The warning can be safely ignored (or suppressed via #pragma warning or /Wd4100).
7,247,284
7,247,421
Beginner LuaPlus Metatables Question
I'm brand new to Lua/LuaPlus and trying to figure out how metatables work. In this code taken from the manual: LuaObject metaTableObj = state->GetGlobals().CreateTable("MultiObjectMetaTable"); metaTableObj.SetObject("__index", metaTableObj); metaTableObj.RegisterObjectFunctor("Print", &MultiObject::Print); In the firs...
This is not standard Lua, it looks like you're using some C++ wrapper that I'm unfamiliar with, but I can make some guesses In the first line we create a new table, but the second line is a little confusing. In this table we just created, we are setting the element with key __index equal to the table itself. Why i...
7,247,394
7,247,612
C++ wrapper DLLs to static LIBs
I have some statically compiled libraries (.lib) that I use in my project, which is written in C++ and built on both Windows and Linux. At my project's entry-point to these libraries, I use just one or two functions from the 'main' library in the static library suite, really (but I'm sure that these functions call many...
"Convert a library to another library type" seems easy, but it is not. There is no straight-forward step-by-step way to do this because C++ and DLLs do not play well together at all, and your code will need to be adapted to support a DLL interface. A concise way to describe the problem is this: A .lib's interface is C...
7,247,405
7,247,461
Read text file and display data in C++
I want to read a text file and display the data. The problem is that the while loop has no end and does not display anything. What's wrong? #include <iostream> #include <fstream> #include <string> #include <vector> #include <limits> /* text file example: john 3453 23 james 87 1 mike 9...
It seems you forgot to ever call read_passenger, so your loop keeps printing the default (empty) value of current.name again and again. (You should get lots and lots of newlines, though, which isn't exactly "does not display anything').
7,247,601
7,247,638
How to exit Win32 application via API?
I have a C++ Win32 application written using Win32 API and I wish to force it to exit in one of functions. Is there something like Exit() or Destroy() or Abort() something similar that would just terminate it?
ExitProcess is the function to use, else you can use exit, note that neither insure the integrity of the shutdown (ie: you many leak handles etc and threaded operations will be terminated, even if they are halfway through an operation, like a db commit)
7,247,654
7,247,703
Problem instantiating struct template
How can instantiate this template struct? template<typename T, template<typename, template <typename> class D= std::allocator >class Z=std::vector > struct amen { Z<T,D<T> > cc; // i know D template class parameter is not visible , how do i do it? }; int main(){ amen<int> moreAmen; } Can an...
You have this wrong. It should be template<typename U, typename D = std::allocator<U> > class Z = std::vector The allocator of std::vector is not a template. Then the declaration of cc becomes Z<T> cc; As you gave a default argument for the allocator, you don't need to pass any argument for it. If you wanted...
7,247,973
7,248,236
$this->load->library('form_helper') equivalent in C++?
I am wondering if you were to write the following Codeigniter PHP code: $this->load->library('form_validation'); In C++ would it be something like this class CI {}; //class CI this; //instance of class made called this this.load.library('form_validation'); This is purely academic and not for practical purposes. As...
There is just so much wrong with this question. C++ is a compiled language vs PHP which is interpreted. In C++ one has to include references to libraries using the #include statement. This effectively implants the source of that file into the file being used. The codeigniter example is loading its own library code sinc...
7,248,058
7,323,385
Does cvQueryFrame have buffer for frames in advance?
If i do: while(1) { //retrieve image from the camera webCamImage=cvQueryFrame(camera) // where 'camera' is cvCreateCameraCapture(0) //do some heavy processing on the image that may take around half a second funcA() } Now when I go to consecutive iterations, it seems that webCamImage lags ! Even if i mov...
cvQueryFrame is just a wrapper that calls 2 other functions: cvGrabFrame, which gets data from the camera very quickly, and cvRetrieveFrame, which uncompresses this data and puts it into an IplImage. If you need frames captured immediately, just grab the frame, and retrieve it for processing later. See http://opencv.jp...
7,248,078
7,248,344
updating the value of a key in a std::map
Assume we have a simple structure such as the following struct T{ int x; int y; }; T t1, t2; Also assume that I have a map<T, int> myMap and that two structures of type T are compared using their x values only. I.e. t1 < t2 iff t1.x < t2.x. I am trying to update some of the y values of the keys over myMap. This sh...
If you are sure that y does not participate in the "logical state" of your class and is merely an implementation detail, then you could declare it mutable: struct T { int x; mutable int y; bool operator<(const T& rhs) const { return x < rhs.x; } }; Now you ought to be able to change y: for (auto it = m.begin(); ...
7,248,417
7,248,924
Restricting method call to another method
There probably is a fairly simple and straight-forward answer for this, but for some reason I can't see it. I need to restrict calling methods from a class only to some methods implemented by derived classes of some interface. Say I have class A{ public: static void foo(); }; class myInterface{ public:...
[Disclaimer: this solution will stop Murphy, not Macchiavelli.] How about: class DatabaseQueryInterface { public: ~virtual DatabseQueryInterface() = 0; virtual Query compileQuery() const = 0; // or whatever virtual ResultSet runQuery(const Query&) const = 0; // etc }; class DatabaseUpdateInterface : public Datab...
7,248,536
7,248,777
Can a static method in a derived class call a protected constructor in C++?
This code works with clang but g++ says: error: ‘A::A()’ is protected class A { protected: A() {} }; class B : public A { static A f() { return A(); } // GCC claims this is an error }; Which compiler is right?
g++ is right. The C++ Standard §11.5/1 says that "<...> the access must be through a pointer to, reference to, or object of the derived class itself <...>". In case of constructors, this means that B is allowed to call the protected constructor of A only in order to construct its own base subobject. Check this related ...
7,248,627
7,248,697
Setting width in C++ output stream
I'm trying to create a neatly formatted table on C++ by setting the width of the different fields. I can use setw(n), doing something like cout << setw(10) << x << setw(10) << y << endl; or change ios_base::width cout.width (10); cout << x; cout.width (10); cout << y << endl; The problem is, neither of the alternativ...
You can create an object that overloads operator<< and contains an iostream object that will automatically call setw internally. For instance: class formatted_output { private: int width; ostream& stream_obj; public: formatted_output(ostream& obj, int w): width(w), stream_obj(obj) {} ...
7,248,760
7,251,664
Recursive to Iterative Transformation
I've gotten stuck on trying to re-write my code from a recursive function into an iterative function. I thought I'd ask if there are any general things to think about/tricks/guidelines etc... in regards to going from recursive code to iterative code. e.g. I can't rly get my head around how to get the following code ite...
As tables and table_count always refer to the same objects, you might make a small performance gain by taking tables and table_count out of the argument list of build_tables by storing them as members of a temporary struct and then doing something like this: struct build_tables_struct { build_tables_struct(std::array...
7,248,774
7,249,015
Meta-programming problem with Enums
Atm i have sth like that: template<int n> struct Pow { enum{val= Pow<n-1>::val<<1}; }; template<> struct Pow<0>{ enum{val =1}; }; I can acess data like Pow<30>::val. It's good but i want do like this int main() { Pow<30>::val; and then use variable to access all of value <0,30> I knew that i can...
Using C++0x variadic templates: template<int... Indices> struct powers { static const int value[sizeof...(Indices)]; typedef powers<Indices..., sizeof...(Indices)> next; }; template<int... Indices> const int powers<Indices...>::value[sizeof...(Indices)] = { Pow<Indices>::val... }; template<int N> struct buil...
7,248,913
7,248,986
C++ template function that receives std::vector as argument
I need to make a template function that receives as parameter a std::container of some type - let's say std::vector and deletes all elements from that container. I need a function equivalent to this: for_each(some_vector.begin(), some_vector.end(), [](some_vector_type* element){delete element;}); The call should be s...
Why wouldn't it be? template <typename C> void delete_all_elements(C& container) { std::for_each( container.begin(), container.end(), [](typename C::value_type ptr) { delete ptr; } ); container.clear(); } You can add e.g. static_assert(std::is_pointer<typename C::value_type>::value, "Elemen...
7,248,917
7,248,985
Why we need to put const at end of function header but static at first?
I have code like this... class Time { public: Time(int, int, int); void set_hours(int); void set_minutes(int); void set_seconds(int); int get_hours() const; int get_minutes() const; int get_seconds() const; static void fun() ; void printu()...
with a const instance method such as int get_hours() const;, the const means that the definition of int get_hours() const; will not modify this. with a static method such as static void fun();, const does not apply because this is not available. you can access a static method from the class or instance because of its v...
7,249,209
7,249,287
running linux c++ code in windows
Possible Duplicate: C++ Portability between Windows and Linux i am new to c++ programming and i dont really know much about it i am running linux (ubuntu) in my desktop and my laptop is running windows but it has charger problems.. anyway, what i want to do is to program softwares in linux and run them in my laptop ...
C++ code can be compiled quite happily on Linux, Windows and a gazillion other platforms. Where you will have problems is with the libraries that you link to. So long as you stick to the standard library of C++ or highly portable libraries like boost then you should have relatively few issues. If you link to a library ...
7,249,378
7,249,442
Disabling C++ exceptions, how can I make any std:: throw() immediately terminate?
This C++ program is a CGI script, I have no desire to deal with exceptions. I'd rather get a marginal performance boost and let the OS (Linux) handle cleanup after the process dies. I am using the Standard C++ Library, and want any function to die like in Perl: Whenever it throws an exception. Without unwinding, or run...
Option #1: Simply never catch exceptions. Exceptions don't have much overhead when they're not thrown or caught; if you're throwing and not prepared to catch, well, you're doing to die anyway, so the performance impact at that point is trivial. Note also that stack unwinding will not be performed if an exception is not...
7,249,671
7,249,713
How do I access the internal contiguous buffer of a std::vector and can I use it with memcpy, etc?
How can I access the contiguous memory buffer used within a std::vector so I can perform direct memory operations on it (e.g. memcpy)? Also, it is safe to perform operations like memcpy on that buffer? I've read that the standard guarantees that a vector uses a contiguous memory buffer internally, but that it is not n...
In practice, virtually all compilers implement vector as an array under the hood. You can get a pointer to this array by doing &somevector[0]. If the contents of the vector are POD ('plain-old-data') types, doing memcpy should be safe - however if they're C++ classes with complex initialization logic, you'd be safer us...
7,249,903
7,249,953
How does "this" cascading work?
I have the following class interface: class Time { public: Time( int = 0, int = 0, int = 0 ); Time &setHour( int ); Time &setMinute( int ); Time &setSecond( int ); private: int hour; int minute; int second; }; The implementation is her...
Each of t's methods return a reference to t. A reference is an alias. So if you did Time t; Time& tAgain = t; tAgain.setMinute( 30 ); tAgain.setMinute also alters t's time. Now extrapolate that simple example to cascading. Each method of t returns a reference to itself Time &Time::setSecond( int s ) { ...
7,249,959
7,250,001
How do you deal with the native size of integers changing between platforms?
I'm afraid I already know the answer to this but I'd like to be sure... I have a fairly large project with a header file that typedefs native types: typedef unsigned long int u32; typedef signed long int s32; // etc... The inevitable has happened and I am now trying to compile on a system where long is 64 bits...
C has <stdint.h>, which in C++0x is <cstdint>. For non-C++0x compilers, you have <boost/cstdint.hpp> if you don't mind reliance on Boost. The <inttypes.h> header also includes macros for printf() format specifiers, which can be adapted for use with the <cstdint> types. If you're using C++, you should be using <iostream...
7,250,018
7,250,178
Why does PHP not have an attribute 'const' like C++ does?
Why does PHP not have the moral equivalent to the C++ const? I think that this is lacking in the PHP language. Is there a way to simulate the same properties as a const object or parameter?
C# doesn't do the const thing either, and it is a very general-purpose language. I'm a big const fan, but understand why scripts in scripting languages tend to not use them: Scripting languages are great for "running naked through the woods" because it is "fun", and very quick to add new functionality, because you are...
7,250,309
7,250,472
choosing ctor arguments at runtime
Is it possible to address the following scenario of choosing the argument at runtime with mpl? struct A { A(int number) { /* use number */ } }; struct B { }; template <typename T, int n> struct A_or_B_Holder { A_or_B_Holder() : _t( /* void or 'n', depends on T */ ) { } private: T _t; }; A_or_B_Holder<B, v...
Your first problem is that void is a type, not an integer. You could make the template accept two types, the second being either boost::mpl::int_ or void. Then you could either specialize the entire struct, or you could put the data member in a base class and specialize that. #include <boost/mpl/int.hpp> struct A { ...
7,250,419
7,250,570
How to query the length of the boost::filesystem::path?
I couldn't find a 'path length' method in the boost::filesystem::path, is there one? If there is no such method (why?) - should I use .native().length() or .string().length() ? I take it .string().length() should be faster, right?
.native() directly returns the internal representation of the path, while string() might perform some conversions. All in all, it won't make much difference though whether you use native().length() or string().length().
7,250,462
7,250,488
How to know when EnumWindows finishes its listing of windows?
How to know when EnumWindows finishes its listing of windows? Because EnumWindows receives a callback function as parameter, and it keeps calling it until no more windows to be listed.
EnumWindows() blocks while enumeration is taking place. When EnumWindows() finishes enumerating through the windows, it returns a BOOL. The following code snippet: #include <windows.h> #include <cstdio> BOOL CALLBACK MyEnumWindowsProc(HWND hwnd, LPARAM lparam) { int& i = *(reinterpret_cast<int*>(lparam)); ++i;...
7,250,715
7,250,768
C++ priority dictionary
I need a container to store pairs, I have two operations: update value by key get the key with maximum value. For the first operation, map is a good structure. For the second operation, seems priority queue is a good one. How would you do this? Is there anyway to have both of the two operations done without having a...
An asymptotically efficient solution to this would be to use a combination of a hash table and a Fibonacci heap. You would use the hash table to be able to access the value associated with any particular key in O(1) time, and would use the Fibonacci heap to be able to quickly look up the key/value pair with the lowest...
7,250,720
7,251,116
ofstream::operator<<(streambuf) is a slow way to copy a file
I need a cross-platform, no external library, way of copying a file. In my first pass I came up with (error handling omitted): char buffer[LEN]; ifstream src(srcFile, ios::in | ios::binary); ofstream dest(destFile, ios::out | ios::binary); while (!src.eof()) { src.read(buffer, LEN); dest.write(buffer, src.gcount(...
I wonder if your fstream is unbuffered by default. GCC 4.5.2 by default uses an internal buffer, but I don't think that's required by the standard. Have you tried using pubsetbuf (see below) to set a buffer for your in/out streams. A quick test on my system, if I set LEN to 0 (and therefore unbuffered), it took 10 se...
7,250,840
7,250,929
STL implementation of MVP design pattern
I'm trying to implement an MVP pattern using STL and I have used *shared_ptr* and *weak_ptr* for "breaking the cycle" when having recurrent references. class i_model; class i_view; class i_view { public: i_view() : myModel(NULL) {} virtual ~i_view() {} void set_model(const ...
shared_from_this may help: http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/enable_shared_from_this.html
7,250,883
7,263,748
sqlite3_wal_checkpoint_v2 always returns SQL_BUSY
Context I'm using sqlite version 3.7.7.1 in a Windows C++ program, I'm creating a DB that has only one connection with SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX. I'm using SQLite because I need very fast ACID transaction. The Database is store on a NTFS solid state drive on Windows XP sp3. This D...
I found the cause to my problem and it was something 2 stupid things on my side : Querying the page size with a "PRAGMA page_size", I was just reading the row and not resetting or finalizing the statement with "sqlite3_reset" or sqlite3_finalize (it was kind of hidden by the C++ wrapper I test with). This was causing t...
7,250,974
7,251,006
Storage type of string literal when passed as argument
I'm curious about string literals. I've read that in the case of something like this, const char * ptr = "Hello World"; that they have static storage duration in the data of the program and are not allocated on the heap or stack. What about when it is used as an argument? for example Function("panda"); when defined...
In your example, "panda" is (normally: implementation defined) stored with static duration in the data of the program. When you call Function("panda"), this is the same as extern char* s = "panda"; Function(s);. This is made more clear in your declaration for the function. Function does not receive a char array, it r...
7,251,015
7,261,047
Is there an STL container that stores an array of elements in contiguous memory where the element size is specified at runtime?
I'm trying to create container that looks close to how my file spec works. It's like a vector but the type of the elements is defined by a hashtable. If I knew the type at compile-time I could just write something like this: struct foo { float a,b,c; int d; byte e,f; ...
Given this code: typedef Toffset uint; //byte offset; typedef Ttype uint; //enum of types typedef std::pair<Toffset,Ttype> member; typedef std::unordered_map<std::string, member> memberdefs; memberdefs itemKey; itemKey["a"] = member(0, 0); itemKey["b"] = member(4, 1); itemKey["c"] = member(8, 2); itemKey["d"] = mem...
7,251,070
7,252,517
gmpxx.h: no such file or directory
I just installed a brand new copy of mingw (32 bit) downloading it from the official project page from Sourceforge. I installed everything in the package, all compilers and so on. Then I downloaded from here gmp for MinGW. I extracted gmp-5.0.1-1-mingw32-src.tar.lzma somewhere into my mingw folder, then ran ./pkgbuild ...
You need to make sure the is among the directories searched for headers. Find the place where the gmpxx.h header resides and add -I /path/to/header/ on your g++ line.
7,251,251
7,251,309
C++ linux : error: ‘move’ is not a member of ‘std’ how to get around it?
So on my VS2010 I can compile code like : boost::shared_ptr<boost::thread> internal_thread; boost::packaged_task<void> internal_task_w(boost::bind(&thread_pool::internal_run, this, internal_thread)); internal_thread = boost::shared_ptr<boost::thread>( new boost::thread(std::move(internal_task_w))); first 2 lines are o...
To get g++ into C++11 (or C++0x) mode, you have to add the command-line parameter -std=c++0x on versions <= 4.6, nowadays you can also use -std=c++11.
7,251,253
7,251,364
c++: no matching function for call, but the candidate has the exact same signature
g++ complains about myclass.cxx:185: error: no matching function for call to 'IMyInterface::doSomething(const SomeClass*, unsigned int)' IMyInterface.h:34: note: candidates are: virtual void IMyInterface::doSomething(const SomeClass*&, unsigned int) when I call m_instanceOfInterface->doSomething((const SomeClass*)0,(u...
The function requires its argument by non-const reference, which cannot bind to a temporary. Observe: void foo(int, T &); foo(1, T()); // error, cannot bind to temporary In your case, T = SomeClass const *. So, you have provide a non-temporary: SomeClass const * pc = 0; m_instanceOfInterface->doSomething(pc, 1U); Not...
7,251,331
7,251,355
How to ensure (like a try-finally) destruction of a HEAP-ALLOCATED object
I'm looking for a way to ensure that an object that is executed on the heap is ALWAYS deallocated when I'm done with it. I know that if it's allocated on the stack, I can use RAII to ensure it will be taken care of - unfortunately, this won't work for me (at least directly) because the object in question is actually cr...
You can still use RAII on pointers returned by functions. You can use smart pointers (which is exactly what the dummy class you are describing is) like this: std::unique_ptr<TheApi::ApiObject> p_myObj(TheApi::createAnApiObj());
7,251,573
7,263,378
gcc relocation error at runtime
Currently I'm running some multi-threaded code which all compiles with no errors or warnings and I get this error when I execute the code: relocation error: /lib/x86_64-linux-gnu/libgcc_s.so.1: 1thread_mutex_locXãƨ+�����Ȩ+ ������ƨ+�&쏭Ũ�Ȩ+e What is a relocation error?
The relocation is process of adopting some offsets in the code to the actual memory layout. Relocations (places which will be edited by relocation process and the description of each relocation) are generated by compiler, e.g. for TLS variables, for dynamic library calls, for PIC/PIE code. Relocation description is sto...
7,251,653
7,251,711
Defining your own explicit conversions
Suppose, if a conversion from one type another type is not available through explicit casts e.g static_cast, Would it be possible to define explicit conversion operators for it? Edit: I'm looking for a way to define explicit conversion operators for the following: class SmallInt { public: // The Default Construct...
For user defined types you can define a type cast operator. The syntax for the operator is operator <return-type>() You should also know that implicit type cast operators are generally frowned upon because they might allow the compiler too much leeway and cause unexpected behavior. Instead you should define to_someTyp...
7,251,897
7,252,014
Qt QMap.insert() failing
I have a levelObjects object that's a QList of QVariants of QMaps: QList< QVariant > levelObjects; Later on, when I try to change the value of something in one of the QMaps, it doesn't seem to do anything: qDebug() << "Before - " << levelObjects[id].toMap().value("x").toFloat() << ", newX = " << posX; qDebug() << leve...
On the line: levelObjects[id].toMap().insert("x", stringNum) levelObjects[id].toMap() is returning a QMap object, and it is in the returned QMap object (not the original QVariant in the levelObjects list) that the insertion is done.
7,252,274
7,252,355
Getting Unique Numbers and Knowing When They're Freed
I have a physics simulation (using Box2D) where bodies with identical integer IDs do not collide, for instance, bodies that belong to the same character. I have a problem though in that I need to be able to get a unique number for each possible entity, so that no two characters accidentally get the same ID. There's a...
You could maintain a "free" list of unused IDs as a singly linked list inside your master World object. When an object is destroyed by World (making its ID unused) you could push that ID onto the head of the free list. When you are creating a new object you could do the following: If the free list is non-empty: pop the...
7,252,455
7,252,524
Use of setjmp and longjmp in C when linking to C++ libraries
I would like to use setjmp and longjmp in a C program that links to a library that is implemented in C++ (but has a C API). The C++ code does do dynamic memory allocation and pointers get passed through the API, but as long as the C side of the code manages those (opaque) objects correctly, there shouldn't be any messi...
The fact that you call C++ functions from your C code does not make setjmp and longjmp more unsafe than they always are. What's important is that if your library allocates resources you must have recovery code in place to ensure that those are released properly after longjmp is called. While this is likely easy for you...
7,252,482
7,252,495
MSVC2005 std::_Iterator_base:: functions slow while debugging
I'm profiling debug build c++ code in MSVC 2005 and certain code takes an extremely long time to execute (30+ seconds) compared to (1-2 seconds) in release. I've set _SECURE_SCL to 0 in the compiler options (/D _SECURE_SCL=0) and verified its set to zero in the source. I've copied the top consumers from the profiler (A...
You should also disable _HAS_ITERATOR_DEBUGGING if you care about debug performance. When iterator debugging is enabled, a lot of bookkeeping is done to help you to detect bugs in your code where you use an invalidated iterator or fail to correctly manage container and iterator lifetimes. That said, a 30:1 performance...
7,252,941
7,252,994
Possible for glutPostRedisplay() to redraw only certain objects?
I have a fractal object that is created with random values to its variables. I'm using C++ and OpenGL. But now, as I intend to use the glutTimerFunc to animate other objects on the scene, I need to call for glutPostRedisplay() to redraw the scene. However, this would affect the fractal object that was totally based on ...
OpenGL does not know what an "object" is. It knows only what you give it. If you are generating vertices with fractals, then you need to either retain sufficient information to regenerate the fractals later, or you need to keep the post-generation data lying around somewhere. I assume you have some random number genera...
7,252,964
7,253,085
How to create a function with argument that would be result of boost::bind?
So I want to create a function like: void proxy_do_stuff(boost::bind return_here) { return_here(); // call stuff pased into boost::bind } And I could call it like : proxy_do_stuff(boost::bind(&myclass::myfunction, this, my_function_argument_value, etc_fun_argument)); How to do such thing?
#include <boost/bind.hpp> template<typename T> void proxy_do_stuff(T return_here) { return_here(); // call stuff pased into boost::bind } struct myclass { void myfunction(int, int) { } void foo() { int my_function_argument_value = 3; int etc_fun_argument= 5; proxy_do_st...
7,253,186
7,253,290
a couple of simple questions about basic pointer use in c++ and the c++ memory model
I've been studying along with the Stanford courses on iTunes U and have hit pointers in C++. I think I understand how pointers work, but I just want to check how to do some simple stuff. Let's say I want to create a dynamic array: double *array; At this point there's a variable called "array" in the stack and noth...
array contains junk data - whatever was in that memory location before array existed is still there. If you try to play with it you're going to shoot yourself in the foot, which is why you need to assign it to a valid memory location, (hence the ensuing call to new[]). Yes, array now contains a pointer (memory address...
7,253,458
7,253,557
Can functional/immutable data structures still be useful for concurrency in a non-garbage collected context?
One of the selling points of immutable data structures is that they are automatically parallelizable. If no mutation is going on, then references to a functional data structure can be passed around between threads without any locking. I got to thinking about how functional data structures would be implemented in c++. ...
There are lock-free reference counting algorithms, see, e.g. Lock-Free Reference Counting, Atomic Reference Counting Pointers. Also note that C++0x (which will probably become C++11 soon) contains atomic integer types especially for purposes like this one.
7,253,568
7,253,610
MFC's message map, no need of &?
I've been looking for the answer to this question but it seems quite difficult to get it, which brings me finally here. It's a syntax that we have to put the & right before pointer to member function. For example here. class Test; typedef void (Test::*fpop)(); class Test { public: void Op1(){} }; int main(){ f...
The only correct way to form a pointer to member in C++ is with & and the class qualifier (in this case CSingleApp::). The Visual C++ compiler has always been more relaxed and has allowed things not normally permitted in the language such as leaving of the qualifier when forming the pointer from inside the class' conte...
7,253,589
7,260,775
How to get the max value from n dimensional array in OpenCV
I am trying to get max value from a 3-d Mat, but minmaxIdx and mixmaxloc both failed to do this. int sz[] = {BIN, BIN, BIN}; Mat accumarray(3, sz, CV_8U, Scalar::all(0)) ; double testMaxval = 0; int minIdx = accumarray.dims ; minMaxIdx(accumarray, NULL, &testMaxval,NULL,minIdx ,NULL) ; cout<<testMaxval<<endl ; This c...
Following code works for me with OpenCV 2.3.1: int sz[] = {3, 3, 3}; Mat accumarray(3, sz, CV_8U, Scalar::all(0)); accumarray.at<uchar>(0, 1, 2) = 20; double testMaxval; int maxIdx[3]; minMaxIdx(accumarray, 0, &testMaxval, 0, maxIdx); cout << testMaxval << endl ; cout << maxIdx[0] << ", " << maxIdx[1] << ", " << maxIdx...
7,253,714
7,254,772
Get Notified about Windows is Going to Sleep/Waking up in C++
I am working on an App which has Multiple Threads waiting for different inputs from DLLs and Serial Ports. I want to add a functionality that before machine going to Sleep, I have to unload certain DLL and On waking up have to Re-load the DLL. For this, I need to get notified on Sleep and Wake up. I found many files a...
Try handling the WM_POWERBROADCAST message Here's sample code that should work. Apparently you do need to create a window otherwise you don't receive the messages. The sample creates a hidden window to achieve this. static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if(messag...
7,253,864
7,254,045
skipws flag set when opening an input file stream in binary mode
I know the extraction operator should not be used on an input stream opened in binary mode, but the member function read should be used instead. std::ifstream ifs("file.bin", std::ios::in | std::ios::binary); char c; ifs >> c; // Should not be used ifs.read(&c, 1); // OK But it can be done anyway. So my question is wh...
"Binary" mode, as controlled by std::ios_base::binary is only for switching off the translation of newlines between the standard C++ \n character and the system specific newline sequence as stored in files. It's completely independent of whether you are parsing a file that contains meaningful separating whitespace or s...
7,253,883
7,259,924
Cannot dynamically link to components in a custom bpl
While drafting the following post I found a solution, but I thought it might be still worthwhile to post here for reference. See solution below. In RAD studio (C++), I have a project group with multiple dlls and exes that rely on a standard set of custom controls. I have isolated these controls in a borland package (b...
From Hendrik: "OK, the solution is rather easy: In project options, go to page "Packages" and under "Build with runtime packages", enter the name of the package (without the bpl extension) that contains the common components. Done."
7,253,976
7,254,057
How do i add an icon to QComboBox in Qt?
I want to add an icon with text into the QComboBox in Qt, how can I implement it?
Update: based on Qt 5.13 (released 2019) there us a dedicated API for this: void QComboBox::addItem(const QIcon &icon, const QString &text) Or if you want to specify an index: void QComboBox::insertItem ( int index, const QString & text) void QComboBox::setItemIcon ( int index, const QIcon & icon ) All credit for thi...
7,254,005
7,256,296
Boost bind inside Boost packaged_task. Why boost asio thinks its not CompletionHandler?
So all my work happens inside of a class named thread_pool. This code will work no matter what run_item takes into itself: template <class task_return_t> void thread_pool::pool_item( boost::shared_ptr< boost::packaged_task<task_return_t> > pt) { internal_tasks.post(boost::bind(&thread_pool::run_item<tas...
It looks like the function thread_pool::run_item<task_return_t> accepts a non-const packaged task reference (or pointer) but boost::bind made a const copy, and is unable to pass the argument. Without seeing the run_item signature, I can't tell exactly, but that's where I would look. Edit: Looking a bit deeper (once I ...
7,254,009
7,254,067
How to convert a string to a templated type in c++
I want to read and parse a text file in C++ in a generic way. The file is always made of key-value pairs, one per line. The key is templated as well as the value. I foresee the key and the values to always be a basic type (int, float, string). My problem is that I don't know how to create a transform the key or value ...
I think your basic approach is wrong. You seem to be trying to use template-meta programming to achieve your goals. This is probably not a good idea. A simpler approach is just to use C++ streams. These stream objects already know how to read all the basic types. And anybody that want to do anything in C++ will add the...