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,118,386
7,118,533
How can I edit the default window title and frame in a Qt application?
I want to create a personalized UI with my Qt application. For this reason I want to edit the default window frame that you can see at any type of window application. The application that contains the default window title and frame: http://0000.2.img98.net/out.php/i12977_with-default-title-and-frame.jpg The application...
You need to create a new class derived from QWidget, and pass Qt::FramelessWindowHint argument to QWidget constructor, like this: class MyWidget : public QWidget { public: MyWidget(QWidget* parent) : QWidget(parent, Qt::FramelessWindowHint) {...} After it you need to reimplement QWidget::paintEvent (QPaintEvent * even...
7,118,460
7,118,998
Boost::mutex - is it possible to lock it inside one class function and unlock on another?
So we have class with functions a and b. Thread one calls a and no other thread can call a or b untill one would call b. Meaning thread one would be capable to call a and than a and ... and than a, and while one had not called b other threads that want to call a or b stand waiting. is it possible to do such thing with ...
The mutex is not a problem; it's the lock. The simplest solution is just to call mutex::lock() and mutex::unlock() manually, and forget about the mutex::scoped_lock; after all, you don't want the lock to respect scope. The problem with this is the usual one; you probably want to free the lock in case of an exception....
7,118,750
7,160,476
Failed to locate method JNI_GetCreatedJavaVMs in the libjvm.dylib (Mac OS)
I am trying to embed java virtual machine in my program but I libjvm.dylib lacks JNI_GetCreatedJavaVMs. The program works fine both on Windows and on Linux platforms. However, when running on Mac OS I'm getting: Failed to locate method JNI_GetCreatedJavaVMs in the shared library libjvm.dylib exception. I use libjvm.dy...
The JNI_GetCreatedJavaVMs as well as other JVM functions are located in JavaVM file, which can be found in /System/Library/Frameworks/JavaVM.framework/ directory.
7,119,227
7,119,287
Undefined reference question
I'm getting this error in C++ and I really don't know how to get to the bottom of it: g++ proxy.cpp -lboost_thread -lboost_filesystem -lboost_system /tmp/ccUHa2s3.o: In function `main': proxy.cpp:(.text+0x1d8): undefined reference to `server::server(std::deque<boost::shared_ptr<boost::asio::io_service>, std::alloc...
It means it cannot find the implementation of the server constructor. Have you written one which you do not show above? EDIT: Ok, so you've written one, but you're not passing it to the compiler. You need to have proxy-server.cpp in your g++ line. EDIT 2: It is not enough to just compile the file containing main and in...
7,119,412
7,119,486
C++ general question
Miner::Miner(int id):BaseGameEntity(id), m_Location(shack), m_iGoldCarried(0), m_iMoneyInBank(0), m_iThirst(0), m_iFatigue(0), m_pCurrentState(GoHomeAndSleepTilRested::Instance()) What exactly ...
It is the constructor of Miner class, using initialization list. Refer to the following link for details of initialization list: http://www.cprogramming.com/tutorial/initialization-lists-c++.html
7,119,427
7,123,418
Does a namespace-scope constructor definition require a class-qualified identifier?
Here's something we all learned on Day 1 of C++, which we take for granted but doesn't clearly follow from the wording of the Standard. Given a class S, we can define its constructor struct S { S(); }; S::S() { … } But the Standard seems to allow this just as well: struct S { S(); }; S() { … } Qualifying the name of ...
When faced with the tokens S() { } at namespace scope, the compiler can't magically decide it's a ctor. Which grammar rule would produce such a sequence of tokens? Let's ignore everything but function-definitions; they can't produce the ( ){ } part. That means that S() must be a declarator , and the decl-specifier-seq...
7,119,588
7,119,896
MS vs Non-MS C++ compiler compatibility
Thinking of using MinGW as an alternative to VC++ on Windows, but am worried about compatibility issues. I am thinking in terms of behaviour, performance on Windows (any chance a MinGW compiled EXE might act up). Also, in terms of calling the Windows API, third-party DLLs, generatic and using compatible static librarie...
First, MinGW is not a compiler, but an environment, it is bundled with gcc. If you think of using gcc to compile code and have it call the Windows API, it's okay as it's C; but for C++ DLLs generated by MSVC, you might have a harsh wake-up call. The main issue is that in C++, each compiler has its own name mangling (or...
7,119,957
7,120,035
Problem with a deferencable iterator only with visual studio 2010
I have this bit of code to remove certain element in my std::vector: splitVector.erase(splitVector.begin()); if ( (splitVector.end())->length() == 0 ) splitVector.erase(splitVector.end()); This code works fine on MacOs but on windows it just give me this error : Expression: vector iterator not deferencable I don...
You need to realise that vector::end is not the last item in the vector. It's one past the last item. If you try to dereference it then your program is bugged. Windows is helpfully telling you this, MacOS unhelpfully didn't. Suggest you read up on how to use containers and iterators in the standard library. If you don'...
7,119,986
7,120,191
How do you get the current count from CSemaphore?
I am trying to debug a multi-threaded program that uses CSemaphore to limit the size of a buffer. How do you get the current value of the semaphore counter from this class? It doesn't seem to be directly accessed from any of its members, and I can't seem to find any functions that will give me it either.
You're not supposed to care - this is a semaphore, not thread-shared counter. That said, you might abuse the ReleaseSemaphore API's lpPreviousCount output parameter BOOL WINAPI ReleaseSemaphore( __in HANDLE hSemaphore, __in LONG lReleaseCount, __out_opt LPLONG lpPreviousCount ); The idea: CSemaphore...
7,120,317
7,120,398
Read data in executable on run
G'Day! I have an executable (Unix or Windows - it should be cross-compiling). If one opens this executable by any editor and write some stuff to the end - the application would still run perfect. On execution, the application with all its data loads to the RAM. So, the user-written part of file is also loaded into memo...
Are you re-inventing exe packers (see http://en.wikipedia.org/wiki/Executable_compression) embedded resources? A portable approach was described here Is there any standard way of embedding resources into Linux executable image? I also think you're might be optimizing the wrong things. Reading directly from file (...
7,120,688
7,120,975
Defining _CRT_SECURE_NO_WARNINGS lead to crash in vector destructor
I am working with a legacy code ported from Visual C++ 6.0 to VC++ 9.0 (2008). I disabled the secure CRT warnings using _CRT_SECURE_NO_WARNINGS pre-processor definition. But that has lead to crashes in the std::vector destructor. Any issues in using _CRT_SECURE_NO_WARNINGS?
How is it crashing? This sounds more like you've got memory in one location overwriting memory in your vector, then freeing it before your vector is freed. I'd look to any place with pointers. Since you're now on a standards compliant compiler replace them with boost shared pointers or boost arrays. Anything to rem...
7,120,710
7,120,740
Why did Microsoft abandon long double data type?
A while ago I wrote a program which used some factorial functions. I used the long double data type to support "relative" big numbers. Now, I changed from codeblocks to Visualstudio 2010, I was wondering why my program didn't work any more till I realized after some research that MS has abandonded the long double data...
I'm not sure why you think that long double was "abandoned", as it is part of the C++ Standard and therefore a compliant implementation must, well, implement it. What they did "abandon" is long double overloads of mathematical functions, and they did this because: In Win32 programming, however, the long double data ty...
7,120,724
7,120,859
How do I delete an object that was dereferenced?
I have the following code MyObject * func1() { MyObject * obj = new MyObject(); // lots of stuff here return obj; } MyObject func2() { MyObject * obj = func1(); // even more stuff here return *obj; } void main() { MyObject obj = func2() } As I got it from here this code is leaking. Will t...
A more elegant solution (and more "correct") would be to use a smart pointer: MyObject func2() { return *std::auto_ptr<MyObject>(func1()); } (With a more modern compiler, use std::unique_ptr. Or if you're using Boost, you can also use boost::scoped_ptr.) I say more "correct", because if the copy constructor of My...
7,121,002
7,121,046
C++ Matrix Class with Operator Overloading
I was implementing a small dense matrix class and instead of plan get/set operators I wanted to use operator overloading to make the API more usable and coherent. What I want to achieve is pretty simple: template<typename T> class Matrix { public: /* ... Leaving out CTOR and Memory Management for Simplicity */ ...
I dispute that "it's not possible" to do the correct thing: struct Matrix { int & operator()(size_t i, size_t j) { return data[i * Cols + j]; } const int & operator()(size_t i, size_t j) const { return data[i * Cols + j]; } /* ... */ private: const size_t Rows, Cols; int data[Rows * Cols]; // not real code...
7,121,196
7,121,282
error: address of overloaded function with no contextual type information
Code: class que { public: que operator++(int) {} // 1 que &operator++() {} que &operator+=(int n) { que& (que::*go)(); go = 0; if(n > 0) go = &que::operator++ ; // 2 //go = (n > 0) ? (&que::operator++) : 0 ; // 3 } }; int main() { que iter; iter += 3; return 0...
error: address of overloaded function with no contextual type information There are two functions with the operator++ name (that's the 'overloaded function' bit of the message), you need to specify which one you want (that's the 'contextual type information' one): n > 0 ? (que& (que::*)())&que::operator++ : 0 You ha...
7,121,198
7,121,223
SQLite database is getting locked
I have a piece of code in C++ that creates many threads & each of these threads access a common SQLite database & SELECTs & INSERTs data. All the INSERTs are with in transactions. Many times I get "Database is locked" error. How can I fix this?
You can use SQLite in a multithreaded way, but for each thread you must open a new connection (sqlite3_open()) and operate on that connection. There is more info in the official documentation
7,121,297
7,121,893
Extending my Java API to C++ through JNI: How to wrap a method returning a String?
I am using JNI to extend my API in Java, in order to make it accessible through C++ (I am creating wrapper classes). I am experienced in Java but new to C++. Now, I am creating a wrapper in C++ for a Java function getString() which returns a String. I am using GetStringUTFChars to get the C string from the Java String...
Mahesh is right std::string getString() { jmethodID methodID = env->GetMethodID(aClass, "methodName", "()Ljava/lang/String;"); if (methodID == NULL) { cout << "--methodID = NULL"; exit(0); } jstring jstringResult = (jstring) env->CallObjectMethod(aClassInstance, metho...
7,121,696
7,122,036
is it wrong to malloc a global variable inside a function?
I have two 'simple' questions in C++. 1- I want to make a variable shared by some methods in a class, so what i am doing is declaring the variable in the header file and make it global to the class. Hence, all methods will have access to it. Is this the right way of doing it ? 2- Following my first point, if i declare ...
Let's clear things up a bit. Assuming this is in header members.h: extern double a; // this is a "global" variable declaration. It needs a definition. class B { double c; // this is a data member. There will be one in each object of class B static double * d; // this is a static data member. There wil...
7,121,772
7,122,186
With what shall we replace the DCOM communication with?
We currently have a number of C++/MFC applications that communicate with each other via DCOM. Now we will update the applications and also want to replace DCOM with something more modern, something that is easier to work with. But we do not know what. What do you think Edit The data exchanged is not something that may ...
there are many C++ messaging libraries, from the old ACE to new ones like Google's Protocol Buffers or Facebook's (now Apache's) Thrift or Cisco's Etch. Currently I'm hearing good things about ZeroMq which might give you more than you are used to.
7,122,009
7,122,052
Get drive letter from filename in Windows
Is there a Windows API function to extract the drive letter from a Windows path such as U:\path\to\file.txt \\?\U:\path\to\file.txt while correctly sorting out relative\path\to\file.txt:alternate-stream etc?
PathGetDriveNumber returns 0 through 25 (corresponding to 'A' through 'Z') if the path has a drive letter, or -1 otherwise.
7,122,102
7,122,152
Sockets - IPPPROTO_TCP Vs. 0
What's the difference under the covers between using: socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); and socket(AF_INET, SOCK_STREAM, 0); I had a reason to use a stream socket within an application and was told to use the 2nd one (which I'm guessing is because TCP would be overkill since its in-box and reliable by defaul...
There is no difference. Both will return a TCP socket, because TCP is the default STREAM protocol of INET family.
7,122,571
7,122,678
How do I read the data from an IStream instance into a char pointer?
I'm trying to copy some binary data from my IStream instance (since Gdiplus::Image only saves to IStream-deriving objects, or a file path) to a char pointer from which I can read simply by knowing the allocated binary size and have access to the pointer. My class is as follows: Upload::Upload(Gdiplus::Bitmap* bitmap, C...
First of all, IStream::Read() is not required to read exactly the specified number of bytes - it is required to read no more than that number. Actual number is stored inside the veriable pointed to by the third parameter. Second, you don't check the HRESULT returned by Read(). A much better strategy would be to call Re...
7,122,756
7,123,598
Modeless dialogs and accelerators
I want to perform some action when the user presses CTRL+S inside a modeless dialog. Accelerators would be perfect for this, except that I don't have control over the thread's message loop (think plugin), so I can't call TranslateAccelerator. A nested message loop is not an option because the main application does a lo...
This is a fairly infamous interop problem, it rears its ugly head also when using Winforms to implement UI in a native program. Microsoft's recommendation is a rough-and-tumble one: start your own thread to display the window so you can pump your own message loop. You'll need SetParent() to avoid Z-order problems. S...
7,122,895
7,123,243
What is the best way to write a part of buffer with quoting?
For exaplme, I have some buffer : const char* buf with next content (mysql packet): 72 00 00 00 select * from `db` where (`name` = "Bill's car") and i need to write to ostream only query with quoting. So, result should be next: select * from `db` where (`name` = \"Bill\'s car\") I know, that << quote << will make quo...
Something like this ought to do: std::copy(buffer + index_of_start_of_sql, buffer + index_of_end_of_sql, std::ostream_iterator<char>(std::cout, "")); This copies the contents of the buffer character by character to the output stream (in this case std::cout). You don't need to worry about handling quotes then. The only...
7,122,907
7,123,422
Qt release build requires debug DLLs
I have a rather weird problem deploying my application ... I compile the application in Release mode, but when I try to run it it requires QtCored4.dll (notice the letter d). Why doesn't it require the non-debug dll, QtCore4.dll instead?
I was including a debug 3rd party library build, rather than a release one ... Including the latter one fixed the errors.
7,123,536
7,131,041
Programmatically read internet explorer cookies
I'm trying to create a piece of software (C++ with Qt) that would search some data into cookies of my website. I found the WinAPI function named InternetGetCookie(szURL, NULL, lpszData, &dwSize) but when I want to show the result I have something like this: __utma=166311972.1573129762.1302471948.1313050619.1313050781.2...
I found. When IE is in protected mode you can't see all the cookies with "InternetGetCookie" To solve this problem there is an other function: HRESULT IEGetProtectedModeCookie( __in LPCWSTR lpszURL, __in LPCWSTR lpszCookieName, __inout LPWSTR pszCookieData, __inout DWORD *pcchCookieData, __in ...
7,123,613
7,125,917
Boost Serialization : Does the default constructor have to be public?
Just a tid bit of information that doesn't seem documented anywhere. Does anyone know? Because I would like to make it private, hoping that the constructor would be called from boost::serialization::access which is declared as a friend.
Test example. Given that this works I'd assume it is a feature and would be upset if there was a future release that didn't allow the access granting mechanism to grant access to private default constructors. #include <boost/serialization/access.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/shared_...
7,123,755
7,196,397
VC++ 2010: Weird Critical Section error
My program is randomly crashing in a small scenario I can reproduce, but it happens in mlock.c (which is a VC++ runtime file) from ntdll.dll, and I can't see the stack trace. I do know that it happens in one of my thread functions, though. This is the mlock.c code where the program crashes: void __cdecl _unlock ( ...
I decided to adhere to the KISS principle and rock and roll all nite simplify things. I figured I'd replace the CSharedMemoryClass with a std::tr1::shared_ptr<BYTE> and a CCriticalSection which protects it from concurrent access. Both are members of CImage now, and concerns are better separated now, IMHO. That solved t...
7,123,785
7,123,918
Is there a suitable data structure for solving this question?
I have four group of data: //group 1 2 2 6 2 2 7 2 3 5 2 3 6 2 3 7 3 2 5 3 2 6 3 2 7 3 3 4 3 3 5 3 3 6 3 3 7 ... ... 7 2 2 7 2 3 7 2 5 7 2 7 7 3 2 7 5 2 7 6 2 //group 2 2 2 2 2 2 3 2 2 4 2 2 5 2 3 2 2 3 3 3 3 2 3 3 3 3 4 2 ... ... 5 2 2 //group 3 2 4 2 5 3 3 3 4 3 5 3 6 ... ... 7 2 //group 4 6 7 8 And what I wa...
Something like to hold the data std::set<std::vector<int> > data; Now you can create one of these for each group if there is no guarantee that the number of items in each group is the same, or if you know what each group is a specific number of items, then put them all in the same set. Then use std::find_if with a cus...
7,123,862
7,126,736
Inject sleep() into a function of an external process
I know how to inject a DLL into a running process and also how to utilize functions used internally by the process e.g. void__stdcall remoteMethod(unsigned short id) { typedef void (__stdcall *pFunctionAddress)(unsigned short); pFunctionAddress pMyFunction = (pFunctionAddress)(0xCAFEBABE); pMyFunction(id); } Now i wan...
I think you are trying to be too cute here. Just call SuspendThread/ResumeThread alternately on a timer. I know it's ugly, but you aren't going to enter your solution in any beauty pageant I suspect.
7,123,925
7,124,453
ICU Byte Order Mark (BOM)
I am using ICU's ustdio functions to write a UnicodeString object to a file in a range of encodings, however it doesn't appear to prepend the BOM. My Code: void write_file(const char* filename, UnicodeString &str) { UFILE* f = u_fopen(filename, "w", NULL, "UTF-16 LE"); u_file_write(str.getTerminatedBuffer(), s...
Just guessing, the "UTF-16 LE" and "UTF-16 BE" were intended to be used when the byte order was well specified and the BOM would not be necessary in the context where the file would be used. You should be able to write your own BOM character '\ufeff' to the file.
7,123,986
7,127,207
Is it possible to trap the Windows Start Menu popup via Windows key(possibly without a hook)?
I've been working on an input event system. I mapped all the keys on my own keyboard, the scancodes and so on, including both windows keys. When I press them, the program successfully receives the distinct keydown events for them without any trouble. When I release the keys, however, the Start Menu pops up, obscuring t...
The Raw Input API should solve your problem. http://msdn.microsoft.com/en-us/library/ms645543.aspx
7,124,008
7,124,207
Multiple inclusion of header files leads to longer compile time?
Does including the same header files multiple times increase the compilation time? For example, suppose every file in my project uses <iostream> <string> <vector> and <algorithm>. And if I include a lot of files in my source code, then does that increase the compile time? I always thought that the guard headers served...
Most of these answers are wrong... For modern compilers, there is zero overhead for including the same file multiple times, assuming the header uses the usual "include guard" idiom. The GCC preprocessor, for example, has special code to recognize the include guard idiom. It will not even open the header file (never m...
7,124,042
7,124,189
How to force std::cin not to do any implicit conversion?
I was wondering if we can force std::cin so it doesn't performs any implicit conversion between data types, for e.g: unsigned int number; cout<<"Please input a number :"; if(std::cin>>number)cout<<std::endl<<"Good number"; else cout<<"Bad number"; So if you punch -23 or 26.3 , it will simply perform implicit conversio...
cin is going to store the value into the data type you provide. unsigned int will not take signed numbers so it will overflow to the largest unsigned int or to 0. In your example, you are providing a double constant, which is not an unsigned int. Change your unsigned int to a double if you want it to work the way you i...
7,124,294
7,124,416
Debugging Managed .NET Code Called From Unmanaged C++
I've read through the solutions available on SO, but nothing so far has corrected my issue. My start-up project is an unmanaged C++ project (We'll call it TestWrapper). The goal is to have the TestWrapper call a managed C++ project that then calls my C# project. This is working fine and I have no issues running it. How...
The debugger must decide on startup if it's debugging native, managed or native + managed code. Hence you must change the debugger settings on the start project and not the DLLs where you're having problems. Try the following Right Click on the project and select "Properties" Navigate to Configuration Properties ->...
7,124,307
7,126,261
How do I start up an MFC application from scratch?
In other words from a blank win32 project (no wizard). This is where I am at: Preprocessor Definitions: WIN32 Linker->System->Subsystem = Console int _tmain() { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { ...
You're probably failing because you're creating the CWinApp after you're calling AfxWinInit. In a regular MFC app, the CWinApp is a global variable, which is constructed before main. This way, when MFC is initialized, it has a valid global CWinApp in place. Try: MyWinApp* app = new MyWinApp(); // ^moved up^ // initi...
7,124,573
7,124,719
How do I build boost universal libraries for x86 and x64 architecture?
Like in the title : How do I build boost universal libraries for x86 and x64 architecture ? Thanks
Add architecture=combined to build both Intel and PowerPC. Add address-model=32_64 to build both x86 and x64 in one package. See Apple Darwin gcc bjam toolset=darwin --with-... address-model=32_64 architecture=combined
7,124,614
7,124,691
C++ template programming - Deferred function calls
I am looking for an elegant solution to the following problem. I have a task struct that I use for deferred function calls. template <typename T> struct Task1 { T Arg1; Delegate<T> TaskDelegate; }; The problem I'm having is this: Task1<const Foo&> MyTask; This will result in the parameter being held as a cons...
You could take a look at the implementation of function<> either in boost or the upcoming standard. As a matter of fact, you can just use function<>. I think that the solution there was (before C++0x) to always store a copy of the arguments, if the user wants reference semantics they can use a reference wrapper. As to...
7,124,899
7,125,040
Initializer list for dynamic arrays?
It is possible to give an initializer list to the definition of a static array. Example: int main() { int int_static[2] = {1,2}; } Is a similar initializer list possible for a dynamic array? int main() { int* int_ptr = new int[2]; } This is closer to what I am trying to do: struct foo { foo(){} foo(void * ptr...
No, you cannot do that. I think C++ doesn't allow this because allowing such thing doesn't add any nice-to-have feature to the language. In other words, what would be the point of dynamic array if you use a static initializer to initialize it? The point of dynamic array is to create an array of size N which is known a...
7,125,666
7,125,934
What is boost::program_options::notify() for?
This question is about the C++ Boost program_options library. All the tutorials are very clear that I should call notify() on my completed variable map, but I'm not sure what this is actually doing for me. Commenting it out didn't seem to have any effect, and the documentation didn't go into much detail: http://www.boo...
notify() is a member function of value_semantic. It is a hook that is provided so that, once the final value of an option is determined, any action that should be taken with that option can be done automatically and be encapsulated in its own function. This prevents code from having one long function that acts on eac...
7,125,720
7,125,787
How does a copy of the data in one data structure to another work in C++?
I have a class that looks like: class A { public: A(); void MethodThatWillNotBeInOtherStructure(); inline int getData() { return data; } inline void setData(int data_) { data = data_; } private: int data; } and a structure like: struct B { public: inline int g...
Copying two unrelated structures in to each other through void * would work properly only if the two structures have the same memory layout. Otherwise the copying fails. Note that the objects of structure A and B in your above code will have the same memory layout, since there member variables are identical. Copying ...
7,126,028
7,126,535
What's the proper way to pass a pointer to a function for deletion?
I have a matrix declared like int **matrix, and I know that the proper way to pass it to a function to allocate memory should be like this: void AllocMat(int ***mat, int size); But now I need to delete these memory in another function and am not sure about what to pass: void DeallocMat(int **mat, int size); or void D...
The question is tagged C++, and yet the answers only use the C subset... Well, first of all, I would recommend against the whole thing. Create a class that encapsulates your matrix and allocate it in a single block, offer operator()(int,int) to gain access to the elements... But back to the problem. In C++ you should u...
7,126,201
7,127,502
Optimized way to find M largest elements in an NxN array using C++
I need a blazing fast way to find the 2D positions and values of the M largest elements in an NxN array. right now I'm doing this: struct SourcePoint { Point point; float value; } SourcePoint* maxValues = new SourcePoint[ M ]; maxCoefficients = new SourcePoint*[ for (int j = 0; j < rows; j++) { for (int i...
A few ideas you can try. In some quick tests with N=100 and M=15 I was able to get it around 25% faster in VC++ 2010 but test it yourself to see whether any of them help in your case. Some of these changes may have no or even a negative effect depending on the actual usage/data and compiler optimizations. Don't alloca...
7,126,333
7,126,358
CrossPlatform Multiprocessing and Multithreading Library for C++
Anybody have an idea of best CrossPlatform Multiprocessing and Multithreading Library for C++. The one i can find by google is OPEN MP. is that the only one and standard library for multiprocessing in C++?
OpenThreads is a good option. Boost.Thread is an cross platform, multithreading library and it will be an part of upcoming C++11 standard. Boost.Process exists, but is not yet part of the official boost library. Also, QThread/QProcess from Qt is another good option. It is available on platforms: Linux, Mac OS X, Win...
7,126,449
7,126,499
Pointer-Array Interaction w/ null terminator
I was just experimenting with the use of pointers when dealing with arrays and I've become a bit confused with how C++ is handling the arrays. Here are the relevant bits of code I wrote: //declare a string (as a pointer) char* szString = "Randy"; cout << "Display string using a pointer: "; char* pszStri...
cout has an operator<< overload for char* to print the entire string (that is, print each character until it encounters a 0). By contrast, the char overload for cout's operator<< prints just that one character. That's essentially the difference here. If you need more explanation, read on. When you dereference the point...
7,126,458
7,127,988
How to iterate through map of map of map of map of map of map of vector
I am trying to gather all the data from a map of map of map of map of map of map of map of vector without having to have 7 loops in C++. Here is how the data looks: Map 1=>Map 1.1=>Map 1.1.1=>Map 1.1.2=>Map 1.1.3=>Map 1.1.4=>Vector 1.1.5=>Elem 1 =...
I like @inflagranti's idea - so, without claim to utility, here's a for-each template that iterates over everything. It uses the is_container trait from the pretty printer, which I don't replicate here. Update: Now fully worked out to deal with both with naked value types and with pair value types. Update 2: Simplified...
7,127,059
7,127,707
How to save a chart as an image in QT
I have created a chart in QT. Is there a way that I can save this as an Image? Thanks,
When you say chart, I assume it is some kind of vector graphics or similar. I usually export them as PDF using QPrinter and then use them in my documents (LaTeX, Keynote, ...). Here is a code snippet which might help. Untested, since I ported it in my head from Python back to C++: QPrinter *printer = new QPrinter(); ...
7,127,242
7,127,312
Fastest IPC method on Windows 7
What is the fastest possible Interprocess Communication (IPC) method on Windows 7? We would like to share only a memory blocks (two-way). Is it ReadProcessMemory or something else? We would like to use plain C but, for example, what does Boost library use for IPC?
ReadProcessMemory shouldn't even be listed as an IPC method; yes, it can be used as such, but it exists mainly for debugging purposes (if you check its reference, it's under the category "Debugging functions"), and it's surely slower than "real" shared memory because it copies the memory of a process into the specified...
7,127,284
7,838,661
Unresolved symbol: sql::mysql::get_driver_instance(void)
I have a program that uses MySQL connector to talk to a MySQL database. The application runs fine using Visual Studio 2008. I'm trying to get the application to build with Visual Studio 2010 and that's where the problems began. The MySQL Connector 1.05 is not supported with VS 2010, and they don't have a binary ver...
Some function names have changed. My best solution is to differentiate between them by using preprocessor conditionals.
7,127,476
7,127,506
Using C Headers in C++
I have searched the googles for this and have found that you use extern "C" { #include "header.h" } To include a C library inside of a C++ library... however, when I do this. The C++ program seems to pick up all my #defines and struct definitions but none of the function declarations leaving me with undefined referenc...
That's a link-time error. In other words, your C++ compiler picked your header all right; you just forgot to link with your library. Right now, you tell your compiler that such functions and structures exist, but not where it can find them. For a shared library (.so), you'll have to pass -l[lib name] to G++; you might ...
7,127,759
7,152,335
Branch on ?: operator?
For a typical modern compiler on modern hardware, will the ? : operator result in a branch that affects the instruction pipeline? In other words which is faster, calling both cases to avoid a possible branch: bool testVar = someValue(); // Used later. purge(white); purge(black); or picking the one actually needed to b...
The CMOV (Conditional MOVe) instruction has been part of the x86 instruction set since the Pentium Pro. It is rarely automatically generated by GCC because of compiler options commonly used and restrictions placed by the C language. A SETCC/CMOV sequence can be inserted by inline assembly in your C program. This should...
7,127,889
7,127,975
C1001: An internal error has occurred in the compiler
This should be self explanatory. I'm trying to implement a distribution sort, and the MSVC compiler is crashing. It seems to be a specific case to do with my SFINAE to detect a member function, this doesn't appear to happen if I don't pass indexert to a function, nor if I replace has_get_index. It also doesn't happe...
This probably isn't what you intended: template <typename C> static yes& test( typename C::func ) ; With typename you tell the compiler that C::func will be a type. In reality it will be a function, and putting a function name there in the parameter declaration doesn't make any sense. Did you maybe intend to use type...
7,127,931
7,128,104
what determines what bytes are output from std::endl
I have a large code base that uses std::cout to generate its output, and it uses std::endl all over the place to generate its newlines. This program seems to generate only linefeeds for the endl, which isn't a huge problem in itself, but for whatever reason, wasn't what I had expected. So as a reality check, I built a ...
To add to Tomalak Geret'kal's answer: the fact that endl expands to the platform-specific endline is a popular misconception. Inside a C/C++ application the only "official" newline (at least, as far as streams and stream-related functions are concerned) is '\n'. The translation from '\n' to the platform-specific newlin...
7,127,947
7,128,207
Screen Calibration in WinCE
I know I can set the calibration with the function TouchCalibrate. I don't want to use the windows function I want to set the calibration via the registry. This works fine except I don't know what message to send to the OS to let it know the data has been update. Does anyone know what message I need to send?
I don't have the CE private source installed on this machine to verify, but I believe you need to broadcast a WM_SETTINGSCHANGE message.
7,127,959
7,127,997
Avoiding pointers in std::list
I try to avoid having pointers, and instead of doing std::list<std::pair<int,int>* > myList; void addElement(int a, int b) { myList.push_back(new std::pair<int,int>(a,b)); } I figured i could do something like std::list<std::pair<int,int> > myList; void addElement(int a, int b) { std::pair<int,int> p(a,b); ...
"Can i expect the compiler to optimize away the unnecessary object p?" Maybe, maybe not. Try this though: myList.push_back(std::make_pair(a,b)); You usually have better chances of optimization when you work with r-values where applicable. But even if it's not optimized away, that is no reason to resort to using poi...
7,128,304
7,128,492
C++ Using unions or inheritance to parse data
I have a scenario where I receive binary data in a buffer (from a com port, or a socket, or some other producer, etc.). The data received is interpreted in different ways, typically keying off the message header in the first byte or first few bytes. I am looking for the best class structure to handle and parse data l...
Your second method is completely broken, as you're getting a sequence of bytes in recvfrom and then interpreting this as a non-POD type, which is undefined and likely to crash, as Message probably needs a vtable and whatnot set up for it which is unlikely to be correct unless the data being received was sent by the exa...
7,128,983
7,133,581
Forcing QDialog to stay open
How should I best go about forcing a QDialog to stay open when the dialog's accept() slot is called? I was thinking of reimplementing that function to get the dialog's exec to return without hiding the dialog, but was wondering if there were any better ways to accomplish this.
Rather than use a QDialog, I would accomplish the effect with a QDockWidget. Remove the feature that allows the dock to be moved (QDockWidget::DockWidgetMovable) Set the dock widget to floating (setFloating(true)) Connect items on the dock widget to the appropriate signals and slots on the main window References Doc...
7,129,027
7,129,063
How to insert 'const Obj' into std::list<T*>?
I wrote a function void addAnything(T const &obj) { ... m_list.push_front(obj); // - line returns C2664 - list is initialized by std::list<T*> m_list ... } and my Problem is to convert from 'const T' in 'T *const'. And I need to insert it into this list... =/ Any method for inserting elements ...
Are you aware of std::list<T*> definition? Manually you should delete object when is removed from the list. I not than replace std::list<T*> with std::list<T>.
7,129,037
7,129,134
How do I change a C++ output stream to refer to cout?
I have a class that I want to give an output stream as a member to, to wit: class GameBase { protected: ofstream m_OutputWriter; ... } There is a method in this class that takes a string argument and opens m_OutputWriter to point to that file, so data may be output to that file by using the standard << operator; H...
In addition to having an std::ofstream as a member, I would use a function that returns an std::ostream&. For example: class GameBase { std::ofstream m_OutputWriter; protected: std::ostream& getOutputWriter() { if (m_OutputWriter) return m_OutputWriter; else return st...
7,129,206
7,131,937
Grouping one QRadioButton into several QButtonGroups
I have, for example, four QRadioButtons rb1, rb2, rb3, rb4. I set rb1 and rb3 checked: rb1->setChecked(true); rb3->setChecked(true); Also, I have four QButtonGroups : bg12, bg34, bg13 and bg24, and make first two non-exclusive(they are by default): bg13->setExclusive(false); bg24->setExclusive(false); The first case:...
The QAbstractButton holds one QButtonGroup as member, so a button can only belong to one group. But for the non-exclusive group, you can use QSignalMappers instead.
7,129,269
7,129,287
About C++ types, and vectors
Let's say I have a few classes Class Alpha (Base Class) Class Beta (Subclass Alpha) Class Delta (Subclass Alpha) Would it be possible to create a vector<Alpha> and store object instances of types Alpha, Beta, and Delta all within that vector, and have the vector function as normal? If not, supposing I wanted to have so...
One approach to this is to have a vector full of pointers, and have the functions that are common to each of them be virtual in the base class: class Alpha { public: virtual void dosomething() { /* do something as an alpha */ } }; class Beta : public Alpha { public: void dosomething() { /* do something as a be...
7,129,342
7,129,353
Do function pointers remain valid across processes?
I have written an extension module that uses C++ function pointers to store sequences of function calls. I want to 'run' these call sequences in separate processes using python's multiprocessing module (there's no shared state, so no synchronization issues). I need to know if function pointers (not data pointers) remai...
Sure--the address space is copied when you fork, so the pointers are still valid afterward for both parent and child processes.
7,129,384
7,129,412
template function and vector accessing
Design problem- one function calls all three I continuation from another question after that thread, here is what I try: template<class T> void func(T* p) { p-> } I am stuck after that arrow as I don't know how to access each element of the which vector I passed in? The func receives argument as a switch case, I ha...
template<class T> void func(T*p) { (*p)[0]; // the first element of the passed-in vector (or array) }
7,129,434
7,129,450
overloading << for my class
I'm trying to write the global function: std::ostream& operator<<(std::ostream& out, const Str& str) { for(int i = 0; i < (int)str.mSize; ++i) out << str.mBuffer[i]; return out; } For a custom string class. It compiles fine but when I go to link: 1>Str.obj : error LNK2005: "class std::basic_ostream<char,struct st...
If you define a function in a header file and include it twice, you'll get a multiple definition error, which you have. To remedy this, declare the function in the header with a prototype and define it in a .cpp file. Alternately, if you're trying to make a header only library, you could do class Str { // your clas...
7,129,488
7,129,504
bitset::operator[] == false/true or bitset::test?
Is using bitset::operator[] equivalent to using bitset::test or is there some underlying optimization? That is, are these two loops equivalent? Using bitset::operator[]: static const int UP = 0; static const int DOWN = 1; for(int i = 1; i < KEY_MAX; ++i) { if(_handler && (_prevKey[i] == UP && _curKey[i] == DOWN)) ...
From the C++03 standard, §23.3.5.2/39-41: bool test(size_t pos) const; Requires: pos is valid Throws: out_of_range if pos does not correspond to a valid bit position. Returns: true if the bit at position pos in *this has the value one. §23.3.5.2/46-48: bool operator[](size_t pos) const; Requires: pos is valid. Thr...
7,129,703
7,131,245
C-like callback handling: which algorithm preforms faster?
I have an array of call backs like this void (*callbacks[n])(void* sender) and I'm wondering which one of these codes will preform faster : //Method A void nullcallback(void* sender){}; void callbacka(void* sender) { printf("Hello "); } void callbackb(void* sender) { printf("world\n"); } int main() { vo...
This totally depends on your actual situation. If possible I would prefer methode A, because it is simply easier to read and produce cleaner code, in particular if your function has a return value: ret = callbacks[UPDATE_EVENT](sender); // is nicer then if (callbacks[UPDATE_EVENT]) ret = callbacks[UPDATE_EVENT](sen...
7,129,717
7,129,730
What does "C-style array" mean and how does it differ from std::array (C++ style)?
I came across this question, while reading about std::array and std::vector.
A C-Style array is just a "naked" array - that is, an array that's not wrapped in a class, like this: char[] array = {'a', 'b', 'c', '\0'}; Or a pointer if you use it as an array: Thing* t = new Thing[size]; t[someindex].dosomething(); And a "C++ style array" (the unofficial but popular term) is just what you mention...
7,129,798
7,129,877
function pointer and virtual function
I guess my question should be silly but it is true that I have never seen a function pointer that is declared as virtual. Is there a reason for this? Edit: I should have said: Is it possible that the function it points to is specified as virtual?
Well, yes (and no). Ordinary function pointers cannot point to non-static member functions. They can only point to standalone functions, which is why for ordinary function pointers the matter of function virtuality does not even come into the picture. In order to point to member functions in C++ you need a pointer of ...
7,129,808
7,129,971
Files needed to include when using liblzf
i want to use liblzf in my application that is written in c++ The description on the site says that It only uses 2 .c and 2 .h files but the tar.gz file contains 3 .h and 3 .c files. Can anyone tell me what should I only include in my application?
lzf_c.c for compression, lzf_d.c for decompression. You don't need lzf.c which seems to be a testing harness. I suspect you have some tweaking to do to get it working with C++.
7,129,815
7,129,839
Overloading Iterator: C++ Semantics Question
Please note this code was not written by me. Otherwise I would not be asking this question. Full credit goes to Jerry Coffin. Anyways the code generates a sequence of numbers by overloading std::iterator< >. I will first post the code, then I will give my interpretation of what I am seeing. If an expert C++ member coul...
You aren't really overloading an iterator; you're writing your own iterator, which involves overloading a few operators. That std::vector constructor effectively looks like this: template <typename ForwardIterator> vector(ForwardIterator first, ForwardIterator last) { for (ForwardIterator it = first; it != last; ++...
7,129,825
7,129,918
How do you include LuaPlus into your project?
I downloaded the visual2008 file from here(http://luaplus.org/projects/luaplus/files), but I don't know how to add it to my project. It's not like the other libraries where I just had to add the include directory to my Visual Studio folder and the bin to my system32 or project folder. There are no header files either. ...
I remember downloading LuaPlus for the first time and thinking the same thing--"Where are the headers?" What you'll want to do is just clone the repository located on GitHub and use that to build LuaPlus yourself. The author helpfully included batch files to create different project files (incl. VS2010). You can the...
7,130,061
7,130,124
QComboboxes in a QTableWidget
I would like one of the cells in a table to be a QComboBox. However, I don't want them displayed as such all the time, only when a user selects that cells. Are there any more convenient ways of accomplishing this than detecting when a cell's been clicked, removing the item in the cell and replacing it with a widget, an...
The way to do that is to use item delegates. You install your delegates using one of the setItemDelegate methods of the view/widget. The delegate is responsible for display and editing of the cell, and you don't have to do the click/key handling yourself. The documentation for this is in the model/view programming guid...
7,130,552
7,130,671
Eclipse CDT can't build - not sure what's wrong (console included)
I'm now going to give c++ a try to see what this language have to offer. I'm having some trouble setting it all up though. I have downloaded Eclipse CDT and followed this guide : http://www.dcs.vein.hu/bertok/oktatas/cpp_by_eclipse/eclipse_for_cpp_on_windows.html#Install_gdb I am using Windows 7 64bit. I have never ins...
The problem is simple enough, Eclipse can't find your compiler. On the lengthy PATH that is quoted I don't see 'c:\MinGW\bin' so I'm guessing you had problems with step 4 under section install MinGW. Having said all that I don't think Eclipse is a very good environment for developing C++ and I don't think MinGW is a pa...
7,130,726
7,130,740
How to write a hello world kernel?
I am writing a kernel, so that i am starting with a hello world program in kernel. I have written a hello world kernel in c++ and it compiles successfully. But when i boot it, it does not show anything on screen. What's wrong with this code? link.ld OUTPUT_FORMAT("binary") ENTRY(start) SECTIONS{ . = 0x00100000; .text ...
Have you tried qemu? When making a tiny os at uni, it proved to be the best program for this type of stuff.
7,130,878
7,132,556
At what point does dereferencing the null pointer become undefined behavior?
If I don't actually access the dereferenced "object", is dereferencing the null pointer still undefined? int* p = 0; int& r = *p; // undefined? int* q = &*p; // undefined? A slightly more practical example: can I dereference the null pointer to distinguish between overloads? void foo(Bar&); void foo(Baz&); foo(*...
Yes it is undefined behavior, because the spec says that an "lvalue designates an object or function" (at clause 3.10) and it says for the *-operator "the result [of dereferencing] is an lvalue referring to the object or function to which the expression points" (at clause 5.3.1). That means there is no description for ...
7,130,892
7,131,398
How to use C++ class instance in C#
I have a DLL that contains a class that inherits from another abstract C++ class defined as following: class PersonInterface { public: virtual int __stdcall GetName() = 0; }; The DLL exports a function that can be used in C# as following (following method is part of static class PersonManager): [DllImport( "person...
Compile your C++ DLL using /clr compiler option. Write up a managed class using public ref class syntax, and have pointer to your native class in this class. Expose all methods from this managed class and forward all calls to your native class. Import this DLL as assembly in your c# project and use this class as you w...
7,130,925
7,131,326
question concerning cin.clear()
I am just working through the book Accelerated C++. (My problem is located on page 57, if you guys have the book with you) The problem is the following: We do have a function which reads student grades: ... while (in >> x) { // in and x are defined as an istream& and as a double hw.push_back(x); // hw is vect...
The call to clear clears the error state set by a failed read. It doesn't do anything with the characters that might be present in the input stream. If the error state is a result of failing to read a double, it is likely that the next character will also fail as an integer. If you try char ch; cin >> ch; I'm sure th...
7,130,957
7,131,565
Crash detection, logging, and C++
I have an application that I wrote in QT C++, it runs fine under Ubuntu for me, both in a Virtual Box, and on the "target machine", a little Zotac MAG box. I have run it for hours, pumped input through it (mind numbing work), and I can't get the bastard to crash, but users keep telling me that it crashes maybe 4 times ...
I believe Google's Breakpad is what you're looking for.
7,131,026
39,520,176
Is it safe to call the functions from <cctype> with char arguments?
The C programming language says that the functions from <ctype.h> follow a common requirement: ISO C99, 7.4p1: In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined. T...
For what it's worth, the Solaris Studio compilers (using stlport4) are one such compiler suite that produce an unexpected result here. Compiling and running this: #include <stdio.h> #include <cctype> int main() { char ch = '\xa1'; // '¡' in latin-1 locales + UTF-8 printf("is whitespace: %i\n", std::isspace(ch)...
7,131,282
7,131,306
develop image to text converstion application for mobile os
I was thinking to develop an image to text conversion application for android. Im looking if there is any existing api written in java or c/c++. Can anyone suggest me about it. Thanks in advance
This site might be helpful for you google OCR sample code
7,131,314
7,131,358
Smart pointer blows stack due to recursive delete
Simple data structures, for instance linked lists, where the 'next' pointer is a smart pointer. When the head node gets deleted, the smart pointer for 'next' kicks in and does a recursive delete. For a long list, this quickly blows the stack. I have had to go back to replace these smart pointers with simple, raw poin...
Assuming I've understood you right and both head and next are smart pointers you can avoid this by doing: head = head->next; Or equivalent. Your 'old' head will get deleted and the old second place item will get promoted to the head. All in one consistent change, with no deep recursion. The only pre-condition to this ...
7,131,372
7,131,456
Count Number of Triples in an array that are collinear
I was asked this Interview Question (C++,algos)and had no idea how to solve it. Given an array say Arr[N] containing Cartesian coordinates of N distinct points count the number of triples (Arr[P], Arr[Q], Arr[R]) such that P < Q < R < N and the points Arr[P], Arr[Q], Arr[R] are collinear (i.e lie on the same straight ...
The following is probably not optimized, but its complexity is the one your interviewer requested. First create a list of (a,b,c) values for each couple of points (N² complexity) --> (a,b,c) stands for the cartesian equation of a straight line a*x+b*y+c=0 Given two points and their coordinates (xa, ya) and (xb, yb), co...
7,131,442
7,131,555
static initializer list for wrapper class
Is it possible to "pass" somehow a static initializer list at construction time to a container wrapper class that than in turn initializes its member? struct bar { bar(void * ptr): ptr(ptr) {} void * ptr; }; template<class T, int N> struct foo { foo( args ) :store(args) {} // here the arg list should be passed...
Method 1: va_args If you agree to make bar POD this can be done with va_args: #include <stdarg.h> struct bar { void * ptr; }; template<class T, int N> struct foo { foo(...) { // here the arg list should be passed va_list ap; va_start(ap, N); for (int i = 0; i < N; ++i) { store[i] = va_arg(ap, ...
7,131,475
7,132,309
Detours Hook in external process for "empty" function does not work
Im hooking functions in an external process via their function offset. That works well for the functions im hooking so far - however i have found a "debugLog(char...)" function that still exist in the binary but doesnt do any printing - it looks like this debugMessage proc near ; xor e...
The function is likely too small to hook. Detours has to overwrite a potion of the hooked function to redirect calls elsewhere, but there probably isn't enough room in that logging stub for Detours to write a JMP instruction targeted at your replacement.
7,131,741
7,131,836
Initializing multiple (unique) entries of a vector
With an array you can do this: int a[] = { 1,2,3,4,5,6 } How do you do this with a vector?
You could write this, though its not an initialization, but looks very appealing: std::vector<int> v; v << 1,2,3,4,5,6,7,8,9,10; //all pushed into the vector! And to support this syntax, you need two utility operators defined as: template<typename T> std::vector<T>& operator << (std::vector<T>& v, const T & item) { ...
7,131,764
7,131,815
Visual C++ generates DIV instead of IDIV (x86, integer arithmetic)
I'm working with Visual C++ 2008 here (9.x) and I was preparing a fixed point value when I ran into the compiler generating a DIV instead of an IDIV. I collapsed the code into a tiny piece to exactly reproduce: short a = -255; short divisor16 = 640; // unsigned, 16-bit unsigned int divisor32 = 640; // unsigned, 32-bit ...
The code that is generated for the / operator depends on the operands. First, the expression (a << 8) has type int, since the integer promotions are performed on each of the operands (ISO C99, 6.5.7p3), and then the operation is int << int, which results in an int. Now there are four expressions: int / short: the righ...
7,131,827
7,132,383
Preload data from a file using a separate thread
I have a small application that process a large quantity of (relatively small) files. It runs sequentially: it loads data from a file, perform operations on it, and move to the next file. I noticed that during run time, the CPU usage is not 100%, and I guess this is due to the time taken by the I/O operations on the ha...
A toy program on how to use some C++0x threading and synchronization facilities. No idea on what the performance of this (I recommend Matt's answer), my focus is on clarity and correctness for the sake of making an example. The files are read separately, as you requested. They're not converted to a sequence of int howe...
7,131,858
7,131,881
std::transform() and toupper(), no matching function
I tried the code from this question C++ std::transform() and toupper() ..why does this fail? #include <iostream> #include <algorithm> int main() { std::string s="hello"; std::string out; std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper); std::cout << "hello in upper case: " << out << st...
Just use ::toupper instead of std::toupper. That is, toupper defined in the global namespace, instead of the one defined in std namespace. std::transform(s.begin(), s.end(), std::back_inserter(out), ::toupper); Its working : http://ideone.com/XURh7 Reason why your code is not working : there is another overloaded fun...
7,131,983
7,132,603
In which cases there is no constructor at all, even a default constructor?
In this book I am currently reading I ran across this: A class doesn't need a constructor. A default constructor is not needed if the object doesn't need initialization. Am I correct in inferring from the above that the compiler does not generate a default constructor for the class/structure in some cases? If yes, w...
A class doesn't need a constructor. A default constructor is not needed if the object doesn't need initialization. I think the author is talking about this situation: some_type some_function () { POD_type this_is_intentionally_uninitialized; ... } Under some circumstances a constructor won't be called, period....
7,132,214
7,132,231
Are Debug Routines MSVC++ specific?
Are the Debug Routines found here: http://msdn.microsoft.com/de-de/library/1666sb98(v=VS.100).aspx specific to MSVC++ or are they C++ Standard? What do other compilers provide?
They are not specified by the C++ standard. They are MSVC specific. For GCC debug related options see this.
7,132,248
7,132,273
Union vs. static_cast(void*)
I'm writing code and until now I was using structures like this: struct s{ enum Types { zero = 0, one, two }; unsigned int type; void* data; } I needed some generic structure to store data from different classes and I wanted to use it in std::vector, so that's reason why I can't use templates. What's better opt...
Consider boost::any or boost::variant if you want to store objects of heterogeneous types. And before deciding which one to use, have a look at the comparison: Boost.Variant vs. Boost.Any Hopefully, it will help you to make the correct decision. Choose one, and any of the container from the standard library to store ...
7,132,540
7,132,560
How can you tell which version of the ISO C++ standard your compiler supports?
Possible Duplicate: How to determine the version of the C++ standard used by the compiler? Is there a way for your program to determine this at compile time? Are there preprocessor macros you can use? I know that g++ has this nice matrix of c++0x/c++11 feature support. Does this exist for other popular compilers? Ar...
Look at the value of __cplusplus In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L. http://predef.sf.net has some values for detecting specific standards. The Boost.Config recommendation on the question you linked to is good advice too, and offers a more f...
7,132,544
7,132,545
C/C++ struct question
Suppose you have a .cpp file (that is, compiled using a C++ compiler like MSVC). In that file, you define a struct in the following way: struct Pixel { float x, y; }; In the same file, you have a line of code that will call a C function, that requires a C struct equal to Pixel. If you write: Pixel my_pixel // set m...
If the header file is correct, it will work, assuming the C compiler and the C++ compiler use compatible calling conventions. Make sure the header file has an appropriate extern "C" block that contains the function definition.
7,132,678
7,132,701
toolchain or IDE? (debugger question)
In short: What's the most efficient debugger/debugging environment for C++? I only started development on Linux recently because I now have to do some work on a GPU server. I've played around with vim and find it quite nice with loads of plugins. I think for editing vim is way better than Visual Studio, but there's one...
The problem with remote debugging is, that the debugger must run on the executing machine. But there is a way under linux to do it remotely with an IDE. You could use NetBeans IDE and use this Plugin: http://plugins.netbeans.org/plugin/37426/gdbserver The Documentation for the gdbserver could be found here: http://www...
7,132,727
7,133,001
writing an object to a file in cpp
I am trying to write the contents of an object into a file. This is my code void Write_data_intoFile(Customer c1) { ofstream fout("cust_details.txt", ios::out | ios::app); fout.write(reinterpret_cast<char*> (&c1),sizeof c1); fout.close(); } This is how i call the function c[ Customer_count ].Write_data_intoFile(c[ Cu...
OK, first you need to write a function for text I/O of Customer. Traditionally that function is called operator<<. So you need something like this ostream& operator<<(ostream& out, const Customer& c) { return out << c.name << ' ' << c.id << '\n'; } Maybe (it's hard to be sure) you need to declare this function as a ...
7,132,795
7,132,878
Syntax errors in C++ include file
I'm writing a game in c++ in microsoft visual studio 2010, yesterday I wrote a pong game and everything was fine but now the compiler telling me that there is a lot of errors for example: 1>w:\c++\planet escape\planet escape\room.h(25): error C2061: syntax error : identifier 'WorldMap' And here is the Room.h file: #pr...
You have circular includes. Suppose you are compiling a file that has a #include "WorldMap.h" as the first applicable #include statement. The file WorldMap.h has that #include "Room.h" that is going to cause a lot of trouble. The problems start in earnest in Room.h at the #include "WorldMap.h" statement. That #include ...
7,132,912
7,132,996
Corrupted offset in call instruction
The last few days have been spent debugging a very strange problem. An application built for i386 running on Windows crashed, with the top of the callstack completely corrupted and the instruction pointer in a nonsense location. After some effort, I rebuilt the callstack and was able to determine how the IP ended up i...
That's a single bit flip: 0x0254 = 0b0000001001010100 0x8254 = 0b1000001001010100 Perhaps corrupt memory, corrupt disk, gamma ray from the sun...? If this specific case is reproducible and their on-disk binary matches yours, I'd investigate further. If it's not specifically reproducible, I'd encourage the client to r...
7,132,957
7,133,322
C++, scientific notation, format number
Is it possible to format string in scientific notation in the following ways: set fixed places in exponent: 1 set fixed decimal places in mantissa: 0 double number = 123456.789 So the number should be formated 1e+5 I am not able to set 0 decimal points for mantissa: cout.precision(0); cout << scientific << num...
I'm not sure what C++ compiler you're using that's giving you 3 digits for the exponent—the C and C++ standards require a minimum of 2 digits for that, and that's what g++ does. There's no way to get only one digit using the standard C or C++ I/O functions, so you'll have to roll your own solution. Since doing a floa...
7,132,977
7,133,122
Using arrays as a template parameters in my rudimentary vector class
Coming from a PHP background, I'm trying to learn C++, since I find it an interesting language. As a practice I want to create a simple Vector class using templates, which is not to hard. However, I run into one problem. I have created the following template class: template <typename T> class Vector { public: Vecto...
Quite simply, don't ever use the in-built primitive arrays. For anything. They suck, tremendously. Always use a class wrapper such as boost::array, if you don't have TR1 or C++0x both of which also provide an array class. A Vector<boost::array<int, 2>> will trivially compile. Why not use primitive arrays? They have hid...
7,133,336
7,133,547
Hot recompilation for C++
I was recently amazed to see Java code being automatically recompiled and injected into a running program. Since modern C++ compilers (eg. LLVM-based) start investigating JIT compilation, I am wondering if there is any work made on this topic. Update: By "hot recompilation", I mean editing the code, recompiling a speci...
It's possible that by "hot recompilation" you mean something like "Edit and continue" in Visual C++. Maybe that link constitutes an answer to your question. But it would be easier if you would define the term you're asking about, "hot recompilation", more clearly (as I'm writing this it's not well defined). added: "Edi...