question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,640,718
1,640,838
Debugging C++ from core files with GDB
GDB seems to always just work for C programs, but for C++ I often get these cryptic stacks: (gdb) bt #0 0x08055fa4 in std::runtime_error::what () #1 0x080576c8 in std::runtime_error::what () #2 0x08057dda in std::runtime_error::what () #3 0x080580d2 in std::runtime_error::what () #4 0x08058662 in std::runtime_erro...
It's unlikely that the text for std::runtime_error::what() actually covers a range from 0x0804d011 through 0x08058725 as suggested by the backtrace. That would be more than 45KB of code. It's more likely that the symbol lookup code that is trying to resolve 0x08055fa4, 0x080576c8, etc. is simply locating std::runtime_...
1,640,720
28,518,981
How do I tell if the c function atoi failed or if it was a string of zeros?
When using the function atoi (or strtol or similar functions for that matter), how can you tell if the integer conversion failed or if the C-string that was being converted was a 0? For what I'm doing, 0 is an acceptable value and the C-string being converted may contain any number of 0s. It may also have leading white...
For C++11 and later: The go-to function for string-to-integer conversion is now stoi, which takes a string and returns an int, or throws an exception on error. No need for the verbose istringstream hack mentioned in the accepted answer anymore. (There's also stol/stoll/stof/stod/stold for long/long long/float/double/lo...
1,640,758
1,640,769
Passing std::vector for any type to a function
Given: template<typename T> class A { B b; std::vector<T> vec1; std::vector<T> vec2; } I'd like B to have a member function that fill() that takes a reference to those to vectors and fills vec2 with values of T depending on some information contained in b. One way of doing this is overloading fill() for each p...
Templatize B. template<typename T> class B { void fill(const std::vector<T>& a, std::vector<T>& b) { } }; template<typename T> class A { B<T> b; std::vector<T> vec1; std::vector<T> vec2; } If you don't want to templatize B, then templatize the fill function: class B { template<typename T> void fill(cons...
1,640,847
1,640,863
Are There Yacc Grammar Debuggers?
I've been helping augment a twenty-some year old proprietary language within my company. It is a large, Turing-complete language. Translating it to another grammar regime (such as Antlr) is not an option (I don't get to decide this). For the most part, extending the grammar has gone smoothly. But every once in awhile I...
You might get some help from yacc -d, which produces debugging output -- it basically gives a full listing of the symbol stack states and such. The output is dense and voluminous, so trying to read all of it directly rarely accomplishes much (never has for me anyway). However, when you make a change the gives (for exa...
1,640,848
1,640,896
Generating getters & setters in XCode
I am currently using xcode for some c++ development & I need to generate getters & setters. The only way I know is generating getters & setters in Objective C style something like this - (string)name; - (void)setName:(string)value; I dont want this; I want c++ style generation with implementation & declaration for use ...
It sounds like you're just looking for a way to reduce the hassle of writing getters/setters (i.e. property/synthesize statements) all the time right? There's a free macro you can use in XCode to even generate the @property and @synthesize statements automatically after highlighting a member variable that I find really...
1,640,886
1,640,893
Does (!(i % j)) mean not modulus of i and j = 0?
int main() { int i,j; for (i=1; i<=25; i++) { for (j=2; j<= i/2; j++) if (!(i%j)) break; if (j>i/2) cout << i << "\n"; } return 0; } This program (not written by me) outputs the prime numbers from 1 to 25, including 1 even though 1 isnt prime. I am having trouble with this line: if (!(i%j)) break; Does th...
!(i%j) is the same as (i%j)==0, or "i is divisible by j"
1,640,922
1,646,780
Restricting the size of components at design time
I am trying to inherit from TButton in order to provide some size aware capabilities, where the buttons are able to resize themselves and/or their font size (within certain constraints) to allow for changes in text e.g. | small | or |   this is a really long   | | sentence on a button | could happi...
Override the virtual SetBounds() method. From there, you can adjust the user's requested dimensions as needed before then passing them to the ancestor SetBounds() method. For example: class TMyButton : public TButton { typedef TButton inherited; public: ... virtual void __fastcall SetBounds(int ALeft, in...
1,641,114
1,641,151
How to read a value with operator>> but no default constructor to the value?
template <class T> T Read () { T t; cin >> t; if (cin.fail()) { // ... } return t; } This generic code read value of type T with some additional error handling. It relies on having operator>> that can parse T, and in this way it is extensible to new types. What I didn't realize is that it relies on T ha...
Streaming from an input stream always assumes a fully constructed object to write into. You can't get around having to construct an object, all you can do is allow for different ways to do so. One way to do this could be traits. The standard traits would do what you're doing: template< typename T > struct istream_tra...
1,641,182
1,641,223
How can I catch a ctrl-c event?
How do I catch a Ctrl+C event in C++?
signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this : #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> void my_handler(int s){ printf("Caught signal %d\n",s); exit(1); } int ma...
1,641,286
5,595,356
Using Qt with DirectX?
What exactly are my options? I have programs I need to write in OpenGL and DirectX, and I'd like to use Qt for OpenGL, and not have to re-implement half my program for the DirectX components of my task. I've looked on Google and I have found references to people complaining about Direct3D being a dependency of Qt, and ...
its pretty straightforward than I thought, -> Create a QWidget -> Override paintEngine() method, does nothing, just returns NULL -> Assign HWND to widget->winId() #ifdef USE_QTGUI QApplication a(argc, argv); CD3DWidget wndw; wndw.show(); wndw.resize(1280,960); hWnd = wndw.winId(); ...
1,641,412
1,641,446
iPhone App: Making a webpage accessible only to people using a specific app
I was just wondering if it is possible and if so what the best way to create a web-page that is only accessible from a custom iPhone application? For example, if you tried to access the webpage from the iPhone's built in browser, or any other browser it would display an error page but when accessed from a custom built ...
Any and all request headers can and will be spoofed. Authentication is the only plausible solution.
1,641,501
1,641,526
How does Windows identify non-Unicode applications?
I am building an MFC C++ application with "Use Unicode Character Set" selected in Visual Studio. I have UNICODE defined, my CStrings are 16-bit, I handle filenames with Japanese characters in them, etc. But, when I put Unicode strings containing Japanese characters in a CComboBox (using AddString), they show up as ???...
Windows knows the difference between Unicode and non-Unicode programs by the functions they call. Most Windows API functions will come in two variants, one ending in A for non-Unicode and one ending in W for Unicode. The include files that define these functions will use the compiler settings to pick one or the other ...
1,641,611
1,641,625
How do you do inheritance in a non-OO language?
I read that early C++ "compilers" actually translated the C++ code to C and used a C compiler on the backend, and that made me wonder. I've got enough technical knowledge to wrap my head around most of how that would work, but I can't figure out how to do class inheritance without having language support for it. Speci...
In C anyway you an do it the way cfront used to do it in the early days of C++ when the C++ code was translated into C. But you need to be quite disciplined and do all the grunt work manually. Your 'classes' have to be initialized using a function that performs the constructor's work. this will include initializing a...
1,641,819
1,641,829
Why is complex<double> * int not defined in C++?
The C++ program #include <complex> #include <iostream> int main() { std::complex<double> z(0,2); int n = 3; std::cout << z * n << std::endl; } yields an error: no match for ‘operator*’ in ‘z * n’. Why? I'm compiling with g++ 4.4.1. Perhaps the compiler is just following the C++ standard, in which case my quest...
This works: #include <complex> #include <iostream> int main() { std::complex<double> z(0,2); double n = 3.0; // Note, double std::cout << z * n << std::endl; } Because complex is composed of doubles, it multiplies with doubles. Looking at the declaration: template <typename T> inline complex<T> operator*(...
1,641,928
1,642,285
DllImport method isn't receiving data
BYTE* pImageBuffer = NULL; eResult res = PlayerLib::CreateImageSnapshot( iPlayerRef, eBMP, &pImageBuffer ); if( res > 0 ) { .... // do something with the image WriteFile(FileHandle, pBuffer, eRes, NULL, NULL); ReleaseImageSnapshot( pImageBuffe...
My suggest to you would be to marshal BYTE ** as ref IntPtr. Your declaration would be: [DllImport("PlayerLib")] public static extern int CreateImageSnapshot(int iPlayerRef, eImageFormat imgFormat, ref IntPtr ppImageBuffer); P.S. and sorry for my English, guys ;)
1,642,021
1,642,125
Resources in a static lib file - MFC
MFC is failing to launch my dialog boxes, it seems, because it can't find the resource identifiers. The dialog boxes are in a separate .lib file (so it has a separate .rc file, which, I'm assuming, somehow conflicts with the one in my .exe file). How should I be handling this situation?
In the .rc file for the .exe file, add a line like this: #include "YourLibResourceFile.rc" Then, in the .exe's project settings, add an additional include directory to where YourLibResourceFile.rc is, in Resources/Additional Include Directories.
1,642,028
1,642,035
What is the "-->" operator in C++?
After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4. Here's the code: #include <stdio.h> int main() { int x = 10; while (x --> 0) // x goes to 0 { printf...
--> is not an operator. It is in fact two separate operators, -- and >. The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator. To better understand, the statement could be written as follows: while( (x--) > 0 )
1,642,091
1,642,101
Storing char array in a class and then returning it
I need to store a char array inside a class and then return it. I have to admit that I'm a bit confused about pointers and have tried everything I can think of but can't get it to work. Here's what I have: #include <iostream> using namespace std; class Test { public: void setName(char *name); char getName(); p...
Just return a pointer: const char* Test::getName() const { return m_name; } and add a constructor for the class Test that would null-terminate the encapsulated array: Test::Test() { m_name[0] = 0; } so that you don't ask for trouble if someone instantiates class Test and doesn't call setName() on the instance...
1,642,240
1,642,281
how to implement common functor for several classes in c++
suppose you have two (or more) classes with private member vectors: class A { private: std::vector<X> priv_vec; public: //more stuff } class B { private: std::vector<Y> priv_vec; public: //more stuff } and you have a functor-class which has a state and works on a generic vector (does sor...
Hum, first, beware on states in functors. Most STL implementation of the algorithms may copy your functors around, therefore you generally have to extract the state in an outer structure. Now, for the application of functors, well it is simple: have your classes declare a template member function! class A { public: t...
1,642,696
1,642,704
How to abort getchar in a console application when closing it
I've written a simple command line tool that uses getchar to wait for a termination signal (something like: 'Press enter to stop'). I however also want to handle the SC_CLOSE case (clicking the 'close' button). I did this by using SetConsoleCtrlHandler. But how do I cancel my getchar? I tried doing fputc('\n', stdin);...
Maybe there's some sort of getchar with a timeout that I can call instead? You can read console input asynchronously: #ifdef WIN32 #include <conio.h> #else #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #endif int main(int argc, char* argv[]) { while(1) { #ifdef WIN32 if (kb...
1,642,703
1,643,796
How to get boost wdirectory_iterator to return UTF32 on the Mac
directory_iterator returns UTF8 using both Visual Studio and Xcode as expected. wdirectory_iterator, however, returns UTF16 using Visual Studio, and UTF8 using Xcode, despite returning a wchar_t string. What can I change to get wdirectory_iterator to return UTF32? An answer to a question I asked previously suggests tha...
wdirectory_iterator is a typedef for basic_directory_iterator<wpath>. wpath is a typedef for basic_path<std::wstring, wpath_traits>. Similarily to what is done in std::basic_filebuf, A basic_path uses an "internal" encoding to represent names to the program, and an "external" encoding to interact with the platform's fi...
1,642,763
1,642,776
null pointer equivalence to int
In "The C++ Programming Language", Bjarne writes that the null pointer is not the same as the integer zero, but instead 0 can be used as an pointer initializer for a null pointer. Does this mean that: void * voidPointer = 0; int zero = 0; int castPointer = reinterpret_cast<int>(voidPointer); assert(zero == castPointer)...
Yes, that means that castPointer isn't necessarily zero, and the assert may fail. Because while the null pointer constant is zero, the null pointer of some type is not necessarily an address with all bits zero. reinterpret_cast has no special provisions to yield zero when casting a null pointer to int. You can achieve...
1,642,789
1,645,438
Fgets in C++ repeats last line
I have program like (from link text) FILE* soubor; char buffer[100]; soubor = fopen("file","r"); string outp = ""; while (! feof(soubor)) { fgets(buffer,100,soubor); fputs (buffer , stdout); } fclose(soubor); and file like A B C D E and the output of program is A B C D E E it repeats last line of fil...
Using feof() as the condition for a loop to read from a file nearly always leads to problems. The standard way would look like this: while (fgets(buffer, 100, infile)) fputs(buffer, stdout);
1,642,810
1,642,835
Is there such a C++ optimisation?
E.g. vector<string> a; vector<string> b; a.push_back("first"); b=a; Would it be optimised somehow as vector<string> b; b.push_back("first");
Short answer: Yes. Long answer: Not really an "optimization", as most modern compilers (read as: non-MSVC) will do that. It's called static single assignment (SSA) and GCC supports it since version 4.0 - and it kicks ass, too!
1,642,903
1,642,917
STL containers on the stack and the heap
If std::vector and friends are self resizing, does that mean if I declare a vector like so: std::vector<string> myvec; Then it'll resize using more stack, whereas: std::vector<string> *myvec = new std::vector<string>(); Would resize using more heap?
Vectors allocate on the heap in their internals. The only thing you pay for in the stack for a stack based bector is a couple of bytes, the inner buffer will always be allocated from the heap. So effectively when you do a vec = new vector() you are allocating a small quantity, which may not be really good.
1,642,955
1,643,090
How to identify more than 4 gb ram on 32-bit machine
I know that a 32-bit OS cannot see more than 4 GB of RAM. So if I were to install, say, 6 GB of RAM on a machine running 32-bit OS, is there any way to identify that? I know one way to get the installed RAM is through WMI class: win32_physicalmemory.Capacity But I don't know if it'll show the correct installed ram size...
32bit operating systems CAN see more than 4GB of memory with PAE-enabled CPUs. It's just that the 32bit address space is limited to 4GB. But as the application has only access to its own virtual address space, it can't tell if some memory it allocated lays in 1st or 5th gigabyte of memory. On windows, you can use the G...
1,643,035
1,643,190
Propagating 'typedef' from based to derived class for 'template'
I'm trying to define base class, which contains typedef's only. template<typename T> class A { public: typedef std::vector<T> Vec_t; }; template<typename T> class B : public A<T> { private: Vec_t v; // fails - Vec_t is not recognized }; Why in B I receive an error that Vec_t is not recognized and I need to...
I believe that this question is duplicate, but I cannot find it now. C++ Standard says that you should fully qualify name according to 14.6.2/3: In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not exam...
1,643,197
1,643,261
What is this C++ technique for adding types to a class called?
I've just found some C++ code (at http://msdn.microsoft.com/en-us/library/k8336763(VS.71).aspx), which uses a technique I've never seen before to add types to an existing class: class Testpm { public: void m_func1() { cout << "m_func1\n"; } int m_num; }; // Define derived types pmfn and pmd. // These types are p...
The comment is incorrect: pmfn and pmd are not "derived types" at all (they are not even types!). They are pointers to members.
1,643,690
1,643,873
Destruction of singleton in DLL
I’m trying to create a simple Win32 DLL. As interface between DLL and EXE I use C functions, but inside of DLL i use C++ singleton object. Following is an example of my DLL implementation: // MyDLLInterface.cpp file -------------------- #include "stdafx.h" #include <memory> #include "MyDLLInterface.h" class MySing...
If i don't call MyInterfaceUninitialize() from my EXEs ExitInstance(), i have a memory leak (m_pName pointer). Why does it happening? This is not a leak, this is the way auto_ptrs are supposed to work. They release the instance when they go out of scope (which in your case is when the dll is unloaded). It looks li...
1,643,820
1,643,874
Why no warning with "#if X" when X undefined?
I occasionally write code something like this: // file1.cpp #define DO_THIS 1 #if DO_THIS // stuff #endif During the code development I may switch the definition of DO_THIS between 0 and 1. Recently I had to rearrange my source code and copy some code from one file to another. But I found that I had made a mistak...
gcc can generate a warning for this, but its probably not required by the standard: -Wundef Warn if an undefined identifier is evaluated in an `#if' directive.
1,643,909
1,646,184
Get window handle on which mouse button was clicked
Hey, I'm using Windows Hook, I installed the mouse hook, system-wide and its working perfectly. Now there is a problem, I need to the get window handle on which the mouse was clicked.. How do I do that? Does the Mouse hook event passes us that information?
Since you're using WH_MOUSE_LL, you're making a low-level mouse hook, which actually receives a pointer to a MSLLHOOKSTRUCT that doesn't have an hwnd member. You need to set a normal mouse hook using WH_MOUSE; you'll then get a pointer to the MOUSEHOOKSTRUCT that you're expecting..
1,644,121
1,644,183
Storing data of unknown size in C++
I've been using PHP for about 4 years, however I've come across a problem that requires something with slightly (:P) better performance and so I've chosen C++. The program I'm writing is a Linux daemon that will scan a MySQL database for URLs to load, load them using cURL, search for a specified string, and then update...
in c++ the vector class can store an unknown sized amount of data. #include <string> #include <vector> std::vector <std::string>Data; std::string newData = "a String"; Data.push_back(newData); std::string otherData = "a different String"; Data.push_back(otherData); of course 'string' could be any data type you want...
1,644,172
1,767,464
Building Qt 4.5 with Visual C++ 2010
Did somebody tried to build Qt 4.5 with Visual Studio 2010 (Beta 2)? Any hints on doing that successfuly? Later edit I tried to run configure from a Visual Studio 2010 console. There is no makespecs support for 2010, so configure fails because of that.
It worked for me to build just as if it was vs2008, but using the vs2010 tools: Open vs2010 command prompt. cd into the top-level Qt directory. configure.exe -platform win32-msvc2008 -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-multimedia -no-qt3support -fast nmake
1,644,212
3,870,775
Connecting multiple devices through RAPI2
The Microsoft RAPI2 interface is designed with the ability to talk to multiple devices. But, ActiveSync 4.5.0 allows only allows one device at a time to connect and only allows it over a USB connection. Is there a way to write a client-server piece for the desktop and mobile device that will allow more than one device...
In msdn they wrote this: For Windows CE 5.0 and earlier, this enumeration sequence will only contain a single connected device.
1,644,325
1,649,788
C# call to unmanaged C++ returning string of squares symbols
I have some C# code calling into an unmanaged C++ DLL. The method I am calling is intended to accept a string as a ref. To handle this I pass in a StringBuilder, otherwise there is a StackOverflowException. This is working fine, but on some calls the string that comes back from the unmanaged code is a jumbled string ...
After I tried the first 2 answers and learned that they weren't helping, I knew that something else must be suspect. I found a small bug somewhere else in my app where I was actually missing an initialization param on the unmanaged code. This was causing my strangely encoded string. Thanks for the help, Corey
1,644,490
1,647,690
emacs completions or IntelliSense the same as on Visual Studio
emacs 22.2.1 on Linux I am doing some C/C++ programming using emacs. I am wondering does emacs support completions (IntelliSense in Visual Studio). For example when filling structures I would like to see the list of members when I type the dot operator or arrow operator. The same would go for function signatures that g...
I am using cedet with emacs. I tried using the cedet version in Debian but it has some bugs so I uninstalled that and downloaded the cvs version from http://sourceforge.net/projects/cedet/develop I compiled it in my ~/tmp/emacs-stuff/ directory and then added the following lines to my ~/.emacs.d/custom.el file: ;;ne...
1,644,598
1,647,213
Firing a COM Event From Another Thread
I have created an in-process COM object (DLL) using ATL. Note that this is an object and not a control (so has no window or user-interface.) My problem is that I am trying to fire an event from a second thread and I am getting a 'Catastrophic failure' (0x8000FFFF). If I fire the event from my main thread, then I don...
COM basics In STA your object lives on a single thread (The Thread). This thread is the one it's created on, it's methods are executed on and it's events are fire on. The STA makes sure that no two methods of your object are executed simultaneously (because they have to be executed on The Thread so this is a nice conse...
1,644,619
1,644,742
CPython is bytecode interpreter?
I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture? Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different from CPython (except they are implement...
CPython is the implementation of Python in C. It's the first implementation, and still the main one that people mean when they talk about Python. It compiles .py files to .pyc files. .pyc files contain bytecodes. The CPython implementation also interprets those bytecodes. CPython is not written in C++, it is C. The...
1,645,309
1,645,446
Help me evaluate this casting
I found this in the PowerVR mesh drawing code and I don't really know how to read it. &((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]] What is going on here? Is this a reference to void cast as an unsigned short pointer and then offset by (3*mesh(etc...) + batchNum)? It's breaking my brain. It's ...
Let's go from the inside out. (unsigned short*)0 This is casting 0 to an unsigned short pointer. This will be used for computing a memory offset, computed in terms of the size of an unsigned short. 3 * mesh.sBoneBatches.pnBatchOffset[batchNum] This is, presumably, the offset in memory of some batch of triangles. A tr...
1,645,324
1,645,344
Is it a good practice to always create a .cpp for each .h in a C++ project?
Some classes, like exceptions or templates, only need the header file (.h), often there is no .cpp related to them. I have seen some projects were (for some classes) there aren't any .cpp files associated to the headers files, perhaps because the implementation is so short that it is done directly in the .h, or maybe ...
I wouldn't add unnecessary .cpp files. Each .cpp file you add must be compiled, which just slows down the build process. In general, using your class will only require the header file anyways - I see no advantage to an "empty" .cpp file for consistency in the project.
1,645,326
1,645,365
non-blocking thread-safe queue in C++?
Is there a thread-safe, non-blocking queue class in the C++? Probably a basic question but I haven't been doing C++ for a long time... EDIT: removed STL requirement.
Assuming your CPU has a double-pointer-wide compare-and-swap (compxchg8b on 486 or higher, compxchg16b on most amd64 machines [not present on some early models by Intel])... There is an algorithm here. Update: It's not hard to translate this to C++ if you aren't afraid of doing a bit of work. :P This algorithm assume...
1,645,474
1,645,499
C++ Boost: is it included by default in most Linux distros?
Is the C++ Boost library usually included by default on most Linux distros?
Many distributions include boost in their official repositories, but do not provide it by default on a standard install (in other words, it's not installed by default, but is relatively easy to install). On the other hand, presuming you're asking this because you're wondering if you can use boost in a project that you...
1,645,492
1,645,583
std::map, references, pointers and memory allocation
I am having a lil hard time with map and the valuetype allocation. consider this simple class: class Column { private: char *m_Name; public: // Overrides const char *Name(){ return this->m_Name; } // Ctors Column(const char *NewName){ this->m_Name = new char[strlen(NewName) + 1]...
The underlying reason why your string m_Name doesn't print the second time is because of the way the STL builds a map. It makes various copies of the value during its insertion. Because of this, m_Name gets destroyed in one of the copies of the original column. Another piece of advice is to use pointers to objects when...
1,645,913
1,645,924
Inserting objects into hash table (C++)
This is my first time making a hash table. I'm trying to associate strings (the keys) with pointers to objects (the data) of class Strain. // Simulation.h #include <ext/hash_map> using namespace __gnu_cxx; struct eqstr { bool operator()(const char * s1, const char * s2) const { return strcmp(s1, s2) == 0; } };...
Try liveStrainTable[ MRCA.c_str() ]= firstStrainPtr;. It expects const char * as type of key value, but MRCA has type string. Another way is to change liveStrainTable to: hash_map< string, Strain *, hash<string>, eqstr > liveStrainTable;
1,645,978
1,646,011
C/C++ function/method decoration
DISCLAIMER: I haven't done C++ for some time... Is it common nowadays to decorate C/C++ function/method declarations in order to improve readability? Crude Example: void some_function(IN int param1, OUT char **param2); with the macros IN and OUT defined with an empty body (i.e. lightweight documentation if you will in ...
I wouldn't appreciate such decoration. Much better to use const and references and constant references, like in void some_function(AClass const &param1, AnotherClass &param2) Usually int are passed by value and not by reference, so I used AClass and AnotherClass for the example. It seems to me that adding empy IN and ...
1,646,163
1,646,248
Does an ATL COM Object Have a Message Pump?
If you create a new ATL project and add a simple COM object to it (note: an object and not a control) that uses the Apartment threading model, will there be a message pump running under the hood? I want to create a hidden window that is a member of my COM object class but I'm not sure if any messages will actually be ...
No, an ATL COM object does not implement a message pump by default. Your code must explicitly use on via a normal Windowing library or explicit message pump implementation.
1,646,266
1,646,288
Difference between hash_map and unordered_map?
I recently discovered that the implementation of the hash map in C++ will be called unordered_map. When I looked up why they weren't just using hash_map, I discovered that apparently there are compatibility issues with the implementation of hash_map that unordered_map resolves (more about it here). That wiki page doesn...
Since there was no hash table defined in the C++ standard library, different implementors of the standard libraries would provide a non-standard hash table often named hash_map. Because these implementations were not written following a standard they all had subtle differences in functionality and performance guarantee...
1,646,312
1,647,812
What caused the mysterious duplicate entry in my stack?
I'm investigating a deadlock bug. I took a core with gcore, and found that one of my functions seems to have called itself - even though it does not make a recursive function call. Here's a fragment of the stack from gdb: Thread 18 (Thread 4035926944 (LWP 23449)): #0 0xffffe410 in __kernel_vsyscall () #1 0x005133de i...
The reason you get "bad" stack is that __lll_mutex_lock_wait has incorrect unwind descriptor (it is written in hand-coded assembly). I believe this was fixed somewhat recently (in 2008), but can't find the exact patch. Once the GDB stack unwinder goes "off balance", it creates bogus frames (#2 through #8), but eventual...
1,646,672
1,646,714
Boost installation -Simplified Build From Source
As mentioned in the docs what do i need to install to run the commands : bootstrap .\bjam The BoostPro Computing folks maintain the Boost installer for Windows, but if I first run the installer and download a minimal build and then run the installer again, the installer doesn't detect that I've already installed Boos...
Set up Your BOOST_ROOT environment variable first: winXP: set BOOST_ROOT=D:\your\boost\sources then in the BOOST_ROOT directory run: boostrap.bat this will create your bjam.exe and it's environment. Next step is to invoke: bjam toolset=msvc stage This will compile Your boost library and place all libs into the folde...
1,646,994
1,648,013
boost lib build configuration variations
I am new to boost - can you please tell me what are the difference b/w the following variations of the boost lib and which one do I need to link to in which case? libboost_unit_test_framework-vc80-1_35.lib libboost_unit_test_framework-vc80-gd-1_35.lib libboost_unit_test_framework-vc80-mt-1_35.lib libboost_unit_test_...
Here is the link to the docs for full info on what the many suffixes means: windows: http://www.boost.org/doc/libs/1_40_0/more/getting_started/windows.html#library-naming linux: http://www.boost.org/doc/libs/1_40_0/more/getting_started/unix-variants.html#library-naming Although it seems it's the same anyway so either l...
1,647,261
1,647,269
Way to link 2 variables in a class in C++
Say I wanted to have one variable in a class always be in some relation to another without changing the "linked" variable explicitly. For example: int foo is always 10 less than int bar. Making it so that if I changed bar, foo would be changed as well. Is there a way to do this? (Integer overflow isn't really possible ...
No, you can't do that. Your best option for doing this is to use accessor and mutator member functions: int getFoo() { return foo_; } void setFoo(int newFoo) { foo_ = newFoo; } int getBar() { return foo_ + 10; } void setBar(int newBar) { foo_ = newBar - 10; }
1,647,298
1,647,316
Why don't STL containers have virtual destructors?
Does anyone know why the STL containers don't have virtual destructors? As far as I can tell, the only benefits are: it reduces the size of an instance by one pointer (to the virtual method table) and it makes destruction and construction a tiny bit faster. The downside is that it's unsafe to subclass the containers ...
I guess it follows the C++ philosophy of not paying for features that you don't use. Depending on the platform, a pointer for the virtual table could be a hefty price to pay if you don't care about having a virtual destructor.
1,647,327
1,647,394
C++ : struggle with generic const pointer
I've run into some annoying issues with const-correctness in some templated code, that ultimately boils down to the following observation: for some reason, given an STL-ish Container type T, const typename T::pointer does not actually seem to yeild a constant pointer type, even if T::pointer is equivalent to T::value_t...
It doesn't work because your const does not apply to what you think it applies to. For example, if you have typedef int* IntPtr; then const IntPtr p; does not stand for const int* p; but rather stands for int* const p; Typedef-name is not a macro. Once the "pointerness" of the type is wrapped into a typedef-name, t...
1,647,373
1,647,437
Difference between pass-by-reference & and *?
What is the difference between passing-by-reference and using the C pointer notation? void some_function(some_type& param) and void some_function(some_type *param) Thanks
When you pass a pointer to a variable in a subroutine call, the address of that variable is passed to the subroutine. To access the variable in the subroutine, the pointer has to be dereferenced. When you pass a reference to a variable, the compiler takes care of obtaining the address of the variable when the variable ...
1,647,469
1,647,699
Nokia QT 4 for Visual Studio 2005 and Visual Studio 2008
I downloaded the latest open source version of QT4-and its installed in c:\qt\2009.04. I've also downloaded the QT4 Visual Studio add-in 1.1.0. I want to set it up for both Visual Studio 2005 and Visual Studio 2008 . Most of the docs online are for older versions. What steps do I follow?
Current docs are at link text. However, most for most of the basics, any QT4.x documentation will lead you in the right direction. Do use their demo programs. They are really, really good at showing how to do things. I've built a few applications using them as a starting point. The integration with VS is via Visual...
1,647,557
1,647,574
ifstream: how to tell if specified file doesn't exist
I want to open a file for reading. However, in the context of this program, it's OK if the file doesn't exist, I just move on. I want to be able to identify when the error is "file not found" and when the error is otherwise. Otherwise means I need to quit and error. I don't see an obvious way to do this with fstream. ...
Since the result of opening a file is OS-specific, I don't think standard C++ has any way to differentiate the various types of errors. The file either opens or it doesn't. You can try opening the file for reading, and if it doesn't open (ifstream::is_open() returns false), you know it either doesn't exist or some othe...
1,647,621
1,647,655
Deleting a Shared Pointer
I have a pointer to a QScriptEngine that I'm passing through the overloaded class constructor of class Evaluator and assigns it to QScriptEngine *engine_ (class Property subclasses Evaluator, and calls this constructor of Evaluator, passing it an already allocated QScriptEngine). The constructor with no arguments creat...
You can solve this by giving one of the classes (class A) lifetime control of that pointer, along with a 'getter' method. The other class (class B) would always call A's getter whenever it needed the pointer. That way, A remains in control of the pointer at all times. Downside is the getter function (it will probably i...
1,647,631
1,647,679
C state-machine design
I am crafting a small project in mixed C and C++. I am building one small-ish state-machine at the heart of one of my worker thread. I was wondering if you gurus on SO would share your state-machine design techniques. NOTE: I am primarily after tried & tested implementation techniques. UPDATED: Based on all the great ...
State machines that I've designed before (C, not C++) have all come down to a struct array and a loop. The structure basically consists of a state and event (for look-up) and a function that returns the new state, something like: typedef struct { int st; int ev; int (*fn)(void); } tTransition; Then you def...
1,647,649
1,647,671
Do shallow copies share pointers? (C++)
I know that if I do something like this: class Obj { public: int* nine; }; Obj Obj1; //Awesome name int eight = 8; Obj1.nine = &eight; Obj Obj2 = Obj1; //Another Awesome name then Obj1's and Obj2's nines will point to the same 8, but will they share the same pointer? I.e.: int Necronine = 9; Obj1.nine = &Necronin...
will Obj2's nine point to Necronine, or will it remain pointing at 8? It will remain pointing at 8. When this line is executed: Obj Obj2 = Obj1; // every object has his own pointer the value(copy) of obj1.nine is copied into obj2.nine and thats it.
1,647,723
1,647,733
strings.h and wrapping this macro with a macro check of whether
I infer from Google search results that strings.h (from here) is for UNIX systems. I would like to wrap the following line with a macro check of whether the host's operating system is Linux/UNIX. It would be much appreciated to hear suggestions about it. Thanks in advance. #include <strings.h>
One option would be: #ifndef _WIN32 #include <strings.h> #endif Per MSDN, _WIN32 is "defined for applications for Win32 and Win64. Always defined." A compiler or standard library for an operating system other than Windows is, of course, free to define _WIN32, but that would be... most unusual.
1,647,895
1,647,921
What does static_assert do, and what would you use it for?
Could you give an example where static_assert(...) ('C++11') would solve the problem in hand elegantly? I am familiar with run-time assert(...). When should I prefer static_assert(...) over regular assert(...)? Also, in boost there is something called BOOST_STATIC_ASSERT, is it the same as static_assert(...)?
Static assert is used to make assertions at compile time. When the static assertion fails, the program simply doesn't compile. This is useful in different situations, like, for example, if you implement some functionality by code that critically depends on unsigned int object having exactly 32 bits. You can put a stati...
1,648,127
1,648,169
C++ boost::thread and automatically locking containers
Is there a way to automatically lock an STL container on access, without having to lock and release around it?
The currrent C++ standard does not say anything about thread safety for STL containers. Officially it is possible for an STL implementation to be thread safe, but it's very unusual. If your STL implementation is not thread safe, then you will need to "lock and release around it" or find some other way to coordinate a...
1,648,229
1,648,318
QTimer vs individual threads
My program's really consuming CPU time far more than I'd like (2 displays shoots it up to 80-90%). I'm using Qtimers, and some of them are as short as 2ms. At any given time, I can have 12+ timers going per display -- 2ms, 2ms, 2ms, 250ms, the rest ranging between 200ms and 500ms. Would it be better if I used threads f...
The main time issue is going to come in on the high priority timers. First off make sure you really need these every 2ms, secondly to overcome some of the overhead in the QTimer class you could group your 3 2ms timeouts into one, and everytime it goes off just execute the 3 sections of code sequentially. I don't think ...
1,648,618
1,648,632
Techniques for obscuring sensitive strings in C++
I need to store sensitive information (a symmetric encryption key that I want to keep private) in my C++ application. The simple approach is to do this: std::string myKey = "mysupersupersecretpasswordthatyouwillneverguess"; However, running the application through the strings process (or any other that extracts string...
Basically, anyone with access to your program and a debugger can and will find the key in the application if they want to. But, if you just want to make sure the key doesn't show up when running strings on your binary, you could for instance make sure that the key is not within the printable range. Obscuring key with X...
1,648,689
1,648,781
How to code Jon Skeet's Singleton in C++?
On Jon's site he has thisvery elegantly designed singleton in C# that looks like this: public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static cons...
This technique was introduced by University of Maryland Computer Science researcher Bill Pugh and has been in use in Java circles for a long time. I think what I see here is a C# variant of Bill's original Java implementation. It does not make sense in a C++ context as the current C++ standard is agnostic on parallelis...
1,649,139
1,649,213
Searching a C++ Vector<custom_class> for the first/last occurence of a value
I'm trying to work out the best method to search a vector of type "Tracklet" (a class I have built myself) to find the first and last occurrence of a given value for one of its variables. For example, I have the following classes (simplified for this example): class Tracklet { TimePoint *start; TimePoint *end; ...
If the vector is sorted and contains the value, std::lower_bound will give you an iterator to the first element with a given value and std::upper_bound will give you an iterator to one element past the last one containing the value. Compare the value with the returned element to see if it existed in the vector. Both th...
1,649,344
1,649,389
Create a new EXE from within C
Am working in VC++ 2008 (express) and I would like to write something in C that creates an "empty" exe that I can later call LoadLibrary on and use BeginUpdateResource, UpdateResource, EndUpdateResource to modify the contents. Just writing a 0-byte file doesn't allow me to open it with LoadLibrary because it isn't a re...
You can compile an empty .exe file with, for example, int main() { return 0; } and use it as a template. (Or an empty .dll, whatever)
1,649,398
1,649,423
How do I ensure buffer memory is aligned?
I am using a hardware interface to send data that requires me to set up a DMA buffer, which needs to be aligned on 64 bits boundaries. The DMA engine expects buffers to be aligned on at least 32 bits boundaries (4 bytes). For optimal performance the buffer should be aligned on 64 bits boundaries (8 bytes). The transfer...
Yes, your buffer IS aligned on 64-bits. It's ALSO aligned on a 4 KByte boundary (hence the 0x1000). If you don't want the 4 KB alignement then pass 0x8 instead of 0x1000 ... Edit: I would also note that usually when writing DMA chains you are writing them through uncached memory or through some kind of non-cache bas...
1,649,529
1,649,979
Sorting by blocks of elements with std::sort()
I have an array of edges, which is defined as a C-style array of doubles, where every 4 doubles define an edge, like this: double *p = ...; printf("edge1: %lf %lf %lf %lf\n", p[0], p[1], p[2], p[3]); printf("edge2: %lf %lf %lf %lf\n", p[4], p[5], p[6], p[7]); So I want to use std::sort() to sort it by edge length. If ...
How about having a reordering vector? You initialize vector with 1..N/L, pass std::sort a comparator that compares elements i1*L..i1*L+L to i2*L..i2*L+L, and when your vector is properly sorted, reorder the C array according to new order. In response to comment: yes things get complicated, but it may just be good compl...
1,649,859
2,565,615
In native C++, how does one use a SqlCe .sdf database?
Is there a simple way, without .NET? I've found some libraries but none for SqlCe 3.5. There is http://sqlcehelper.codeplex.com/ but it's far from done, since a major feature like using a password is not yet implemented. I've looked at the source and it uses OLEdb to handle the database. The official Microsoft Northwin...
Several months ago, I compared certain database implementations for our desktop application. Using SqlCE with native C++ code is awful. If I remember right, some of native examples contains "goto" type jumps, hard to bind data and so on. If you have a choice then use SQLite.
1,650,035
1,650,074
how to convert CString to Bytes
i am actually tryin to convert a csharp code to c... below is the C# code.. CString data = "world is beautiful"; Byte[] quote = ASCIIEncoding.UTF8.GetBytes(data); in the above code... it converts the string into bytes..similarily is ther a way that i can convert it using C.. Can any body tell what wud be the quiva...
Well CString is a C++ class so doing it in C is a little unlikely. But if you wish to get it as a standard multi-byte encoded string then you can do the following CString data = "world is beautiful"; CStringA mbStr = data; char* bytes = mbStr.GetString();
1,650,094
1,650,371
How to keep only the last duplicate when iterating through rows
Following code iterates through many data-rows, calcs some score per row and then sorts the rows according to that score: unsigned count = 0; score_pair* scores = new score_pair[num_rows]; while ((row = data.next_row())) { float score = calc_score(data.next_feature()) scores[count].score = score; scores[cou...
The first thing I'd try would be a map or unordered_map: I'd be surprised if performance is a factor of 60 slower than what you did without any unique-ification. If the performance there isn't acceptable, another option is something like this: // get the computed data into a vector std::vector<score_pair>::size_type co...
1,650,637
1,651,980
Why do I get wrong text size for the toolbar?
In a Win32 GUI application I need to determine the width of area occupied by a string on a toolbar button so that I adjust the button width accordingly. The toolbar is plain old ToolbarWindow32 windows class. I use the following code: HDC dc = GetDC( toolbarWindowHandle ); SIZE size; GetTextExtentPoint32( dc, string...
The font used by the toolbar won't be selected into the DC so you'll need to work out what font it is using, create a copy, select it into the DC, get the size and then select the font out (else you could end up with a resource leak). You will currently be getting the size of the system font I expect, or whatever the ...
1,650,763
1,657,267
Call unmanaged Code from C# - returning a struct with arrays
[EDIT] I changed the source as suggested by Stephen Martin (highlighted in bold). And added the C++ source code as well. I'd like to call an unmanaged function in a self-written C++ dll. This library reads the machine's shared memory for status information of a third party software. Since there are a couple of values, ...
When returning information in a struct the standard method is to pass a pointer to a struct as a parameter of the method. The method fills in the struct members and then returns a status code (or boolean) of some kind. So you probably want to change your C++ method to take a SYSTEM_OUTPUT* and return 0 for success or s...
1,650,904
1,650,929
OpenCV K-Means (kmeans2)
I'm using Opencv's K-means implementation to cluster a large set of 8-dimensional vectors. They cluster fine, but I can't find any way to see the prototypes created by the clustering process. Is this even possible? OpenCV only seems to give access to the cluster indexes (or labels). If not I guess it'll be time to make...
I can't say I used OpenCV's implementation of Kmeans, but if you have access to the labels given to each instance, you can simply get the centroids by calculating the average vector of instances belong to each of the clusters.
1,650,942
1,650,959
Large dynamic array in c++
Short problem: #include <iostream> using namespace std; int main() { double **T; long int L_size; long int R_size = 100000; long int i,j; cout << "enter L_size:"; cin >> L_size; cin.clear(); cin.ignore(100,'\n'); cout << L_size*R_size << endl; cout << sizeof(double)*L_size*R_s...
Yes. The operating system will allow you to allocate up to 2GB of RAM per process. When you start two copies, it will let this grow using virtual memory, which will be very, very slow (since it's using the hard drive), but still function.
1,650,963
4,429,618
uSTL or STLPort for Android?
I'm working with the Android NDK, and since it does not currently support the STL, I was wondering if there are any brilliant people out there who have had success with this, or know which is better suited for the Android platform: uSTL or STLPort. EDIT: Looks like another option may be CrystaX .NET. From their websit...
STLport supported since Android2.3 now!!!
1,650,964
1,650,998
compile errors w/wininet & winhttp in MFC application
Strangely I had this working before but I reinstalled my system, upgraded to w7 and now I can't seem to get this code to compile. The problem is that I'm using winhttp.h in most of my application, but I have a simple FTP client object that I wrote using wininet.h functionality. I can't seem to get the application to co...
Ah got it, finally by moving the winhttp include into the cpp files and putting wininet into the ftp client header.
1,650,981
1,650,988
How do you output the \ symbol using cout?
How do you output \ symbol using cout?
Use two backslashes \\
1,650,987
1,651,846
What's the best way to optimise the build of a project which uses Boost?
I was a bit staggered today by the sheer number of auto generated includes that Boost produces when doing a compile if we turn on verbose includes. We're averaging 3000 header files included per compilation unit and sometimes getting up to 5000. Virtually all of it is caused by Boost's preprocessor-meta programming f...
One thing that can really help is the use of precompiled headers, so that many or most of the Boost headers get compiled once for the whole build, not once for every translation unit. Both Microsoft Visual C++ and GCC support precompiled headers (as do other compilers).
1,651,244
1,651,285
Do I really need Visual Studio
Do I really need Visual studio to build c/C++ application on Windows. Is there any way to have makefiles and get the application built.
If you want to stick to the Microsoft toolchain but don't want the IDE, you can use cl and link to build from the command line in conjuction with either the MSBUILD system or NMAKE. If you don't have the compiler it is available free with VC++ Express.
1,651,531
1,652,425
Loading an image from memory, GDI+
Here's a quick and easy question: using GDI+ from C++, how would I load an image from pixel data in memory?
Probably not as easy as you were hoping, but you can make a BMP file in-memory with your pixel data: If necessary, translate your pixel data into BITMAP-friendly format. If you already have, say, 24-bit RGB pixel data, it is likely that no translation is needed. Create (in memory) a BITMAPFILEHEADER structure, followed...
1,651,563
1,652,444
Inserting (string, object * ) into hash table (C++)
This question is an offgrowth of my previous question on creating a hash table to store string keys and pointers as data. I'm getting a seg fault post-construction when I try to add entries to my hash table. I'm still very confused about what syntax is appropriate. I currently have (thanks to previous posters): // Simu...
As a diagnosis approach, you actually have 2 instructions executed on the line: Lookup in strainTable, which returns a reference Dereferencing the iterator Assignation of a value to the reference Here you might want to take a Divide and Conquer approach: strainTable[ mutantSeq ] = *mItr; // <-- Seg fault happens he...
1,651,616
61,785,481
Qt: does "new without delete" cause memory leaks with controls?
I was looking at Qt example here: and inside the constructor, they have: Window::Window() { editor = new QTextEdit(); // Memory leak? QPushButton *sendButton = new QPushButton(tr("&Send message")); // Memory leak? connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage())); QHBoxLayout *...
As of C++14 you can use the std::make_unique() convenience function template for creating an std::unique_ptr<> that has exclusive ownership of the widget. Then, at the moment of passing the widget to addLayout(), you make the smart pointer give up ownership by calling release(): auto buttonLayout = std::make_unique<QHB...
1,651,682
1,651,726
How to "watch" a C++ dynamic array using gdb?
Consider the following example: int size = 10, *kk = new int[size]; for (int i = 0; i < size; i++) { kk[i] = i; } delete [] kk; How can I add a watch for the whole array? I can add a watch one by one (kk[0],kk[1]...), but since I know the array's length is there a way to do it automatically? I mean something lik...
Try display *kk@<size> From the doc for the print command: @ is a binary operator for treating consecutive data objects anywhere in memory as an array. FOO@NUM gives an array whose first element is FOO, whose second element is stored in the space following where FOO is stored, etc. FOO must be an expression w...
1,651,737
1,651,771
LoadStringW - winuser.h. What does it do?
I have been unable to find any decent documentation on this function. The code base I am working with uses a function from winuser.h called LoadStringW which takes as arguments: (HINSTANCE hInstance, UINT uID, LPWSTR lpBuffer, int cchBufferMax). What is this function? What is it for? When might it return 0?
LoadStringW is the Unicode version of LoadString. The documentation states "If the function succeeds, the return value is the number of TCHARs copied into the buffer, not including the terminating NULL character, or zero if the string resource does not exist. To get extended error information, call GetLastError."
1,651,936
1,651,979
Changing std::endl to put out CR+LF instead of LF
I'm writing a program on a Linux platform that is generating text files that will be viewed on, inevitably, a Windows platform. Right now, passing std::endl into a ostream generates the CR character only for newlines. Naturally, these text files look wrong in MS Notepad. Is there a way to change std::endl such that i...
Opening a file in text mode should cause std::endl to be converted to the appropriate line ending for your platform. Your problem is that newline is appropriate for your platform, but the files you create aren't intended for your platform. I'm not sure how you plan on overloading or changing endl, and changing its beh...
1,652,126
1,652,198
const char * as a function parameter in C++
NOTE: I know there are many questions that talked about that but I'm still a beginner and I couldn't understand the examples. I got a function prototype that goes like this: int someFunction(const char * sm); Here, as you know, const char* means that this function can accept const or non-const pointer-to-char. I tried...
I'll try to put in simpler terms what others are saying: The function someFunction takes a read-only string (for simplicity's sake, though char * could be used in umpteen other cases). Whether you pass in a readonly string to someFunction or not, the parameter is treated as read-only by the code executing in the conte...
1,652,183
1,652,520
How should I save and load user configuration files for a game in C++?
I need a way to save and load user configurations for a game (controls, graphics, etc.) to a file. I want to do this in a cross-platform manner, and if I have to use libraries, I want them to have a simple enough syntax. How do I save and load config files, and what format should I use? XML and INI seem popular but all...
Google Protocol Buffers There is a long standing confusion I think, between serialization and messaging. Serialization Is generally short-lived and involves passing around objects. As stated in the article, COM and CORBA are well-known examples of its uses. Messaging Is about communication between different entities. ...
1,652,255
1,652,266
accessing struct variable inside getter setter in a c++ class
Okay, I have something like this in C++: class MyClass{ private: int someVariable; int someOtherVariable; struct structName{ int someStructVariable; int someOtherStructVariable; };//end of struct public: //getters & setters for the defined variables. int getSomeStructVariable() { // this do...
structName is part of the type name, not the variable name. You need to give it a name, something like: struct structName { int someStructVariable; int someOtherStructVariable; } myStructure; And then in your accessor use: return myStructure.someStructVariable; That should get you the result you want. Other alt...
1,652,396
1,652,404
What is the difference between (type)value and type(value)?
What is the difference between (type)value and type(value) in C++?
There is no difference; per the standard (§5.2.3): A simple-type-specifier (7.1.5) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined ...
1,652,901
1,653,012
Basic questions: Pointers to objects in unordered_maps (C++)
I'm new to C++ programming and would greatly appreciate replies that don't assume much prior knowledge. Thanks to suggestions here, I've created an unordered map: typedef std::tr1::unordered_map<std::string, Strain*> hmap; The data in this map are pointers to instances of class Strain. As soon as these instances are c...
A pointer to any object allocated with new will remain valid until you call delete on the object. You can copy the pointer as much as you like, and it will be valid as long as the underlying object has not been deleted. Secondly, yes, you are correct that you can access object attributes from the stored pointers via c...
1,653,047
1,653,057
Avoid linking to libstdc++
I'm working on an embedded project that currently uses C in Linux and uClibc. We're interested in moving it to C++, but I don't want the overhead associated with linking in libstdc++. My impression is that this is possible provided we don't use anything from STL, such as iostream or vector. How does one direct g++ to ...
When you compile, use g++ -c to compile only. Then for linking, use ld instead of g++. This invokes the linker directly, which requires you to name all your libraries on the command line (including libc and libcrt), however. Alternatively, if you're using g++ as a "better c", you may be able to use gcc for your final...
1,653,203
1,653,225
Where to put containers of user defined types?
Consider one has some user defined types, and containers of those types that are often manipulated because there are often multiple instances of those types on screen at a time. Currently I have a header with an associated source file and a namespace to hold these containers, but should I create a separate class to hol...
I once typedef'd them whenever a specific class has the container as part of that class's interface. Then anyone who needed to use that class easily figured out that a "FooVec" is a std::vector of Foo without a lot of fus. However, this is an imperfect solution, consider the following code: namespace bar { typedef s...
1,653,465
1,653,485
Unable to open fstream when specifying an absolute path
I know this is rather laughable, but I can't seem to get simple C++ ofstream code to work. Can you please tell me what could possibly be wrong with the following code: #include <fstream> ... ofstream File("C:\temp.txt"); if(File) File << "lolwtf"; Opening the ofstream fails whenever I specif...
Your path is invalid: "C:\temp.txt" The \ is escaping the "t" as a horizontal tab character, so the path value ends up as: "C: emp.txt" What you want is: "C:\\temp.txt" or "C:/temp.txt"
1,653,517
1,653,531
Why is C and C++ IDE tool support behind what's available for managed platforms?
If you have used any decent java or .net IDE you can see the abundance of features that they provide that either do not exist in c/c++ IDEs or exist in a much more limited form. I am thinking about features like: Code Completion Syntax Errors (and compilation errors with no need to compile) Refactoring Debugging (the ...
C++ is an extremely difficult language to parse. For the parsers that do successfully process it (compilers), they are way too slow and not flexible enough to support IDE-style code support. Unlike in a compiler, in an IDE, the parser has to be very fast and be able to process syntactically incorrect code. Until now, n...
1,653,585
1,653,646
What's a decent events library for non-GUI applications under *nix? (C++)
First, I'm using Qt at the moment. However, I want the program eventually able to run without a GUI environment, leaving the graphical aspects for configuration mainly. The program makes hefty use of Qt timers and signals/slots, partially for QtScript. So if I want to make it non-GUI operable, hopefully parts of Qt can...
Have you looked at the Boost.Signals library? (I haven't used it myself.)
1,653,605
1,653,611
Is including C++ source files an approved method?
I have a large C++ file (SS.cpp) which I decided to split in smaller files so that I can navigate it without the need of aspirins. So I created SS_main.cpp SS_screen.cpp SS_disk.cpp SS_web.cpp SS_functions.cpp and cut-pasted all the functions from the initial SS.cpp file to them. And finally I included them in the or...
Don't include cpp files in other files. You don't have to define every class function in one file, you can spread them across multiple files. Just add them individually to the project and have it compile all of them separately.
1,653,681
1,653,737
Serialization/Deserialization of a struct to a char* in C
I have a struct struct Packet { int senderId; int sequenceNumber; char data[MaxDataSize]; char* Serialize() { char *message = new char[MaxMailSize]; message[0] = senderId; message[1] = sequenceNumber; for (unsigned i=0;i<MaxDataSize;i++) message[i+2] = data[i...
since this is to be sent over a network, i strongly advise you to convert those data into network byte order before transmitting, and back into host byte order when receiving. this is because the byte ordering is not the same everywhere, and once your bytes are not in the right order, it may become very difficult to re...
1,653,874
1,654,791
Implementing Globalization / Multilingual feature in win32 API application
I have developend a window application(Win32 API) in visual C++. I have to add multilingual feature in this application. Can any one Pls guide me how to get forward with this task.
the basics for a multilingual application on Windows is the use of "resources". a resource is a chunk appended at the end of your executable, which only contains data, and is formatted in a very specific way in order for Windows to be able to interpret those data. in your resources, you can find dialog boxes, string ta...