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
947,394
947,425
What is the point of make_heap?
Can someone please tell me the point of the STL heap function templates like std::make_heap? Why would anyone ever use them? Is there a practical use?
If you want to make a priority queue out from a list, well, you can use make_heap: Internally, a heap is a tree where each node links to values not greater than its own value. In heaps generated by make_heap, the specific position of an element in the tree rather than being determined by memory-consuming l...
947,489
947,541
Does a standard implementation of a Circular List exist for C++?
I want to use a circular list. Short of implementing my own (like this person did) what are my options? Specifically what I want to do is iterate over a list of objects. When my iterator reaches the end of the list, it should automatically return to the beginning. (Yes, I realize this could be dangerous.) See Vladim...
There's no standard circular list. However, there is a circular buffer in Boost, which might be helpful. If you don't need anything fancy, you might consider just using a vector and accessing the elements with an index. You can just mod your index with the size of the vector to achieve much the same thing as a circular...
947,621
947,636
How do I convert a long to a string in C++?
How do I convert a long to a string in C++?
You could use stringstream. #include <sstream> // ... std::string number; std::stringstream strstream; strstream << 1L; strstream >> number; There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though. The C way to do it would ...
947,742
947,755
debug command line application
I'm wondering if it's possible to debug a command line application (where main received arguments argc, and **argv) in visual studio 2008?
You can easily set the command arguments to the executable from within Visual Studio, in the Debugging screen under Configuration Properties (at least that's where it is in 2005).
947,802
947,939
Lua / c++ problem handling named array entries
I'm trying to write some c++ classes for interfacing with LUA and I am confused about the following: In the following example: Wherigo.ZCommand returns a "Command" objects, also zcharacterFisherman.Commands is an array of Command objects: With the following LUA code, I understand it and it works by properly (luaL_getn ...
luaL_getn is for getting the highest numeric element of an array in Lua. An array is a table with only integer indices. When you define a table in Lua (the first example) without explicitly setting indices, you will get an array with elements 1, 2, and 3. Naturally, luaL_getn returns a 3 here. luaL_getn is NOT defined ...
947,864
947,887
debug assertion error
I've been scratching my head for quite some time now, this code worked fine when I first used cmd to go inside the project\debug folder then run the program there. Then I added the if(in) and else part then it started giving me "debug assertion failed" errors mbstowcs.c Expression s != NULL It just doesn't make any sen...
First impressions: if( argv[i][0] = '>' ) should be: if( argv[i][0] == '>' ) You are assigning instead of comparing. I think you also might have intended the compl_out.append to be inside the while loop? As it is it won't append anying to that buffer: while(getline( in, buff )) { cout << "buf" << buff << endl; ...
947,943
947,970
Template specialisation where templated type is also a template
I've created a small utility function for string conversion so that I don't have to go around creating ostringstream objects all over the place template<typename T> inline string ToString(const T& x) { std::ostringstream o; if (!(o << x)) throw BadConversion(string("ToString(") + typeid(x).name() + ")")...
Don't specialize the template, but overload it. The compiler will figure out what function template to take by ordering them according to their specialization of their function parameter types (this is called partial ordering). template<typename T1, typename T2> inline string ToString(const std::pair<T1, T2>& x) { ...
948,947
949,262
What are the differences between parameter definitions as (type& name), and (type* name)?
A very basic question, but still, it would be good to hear from C++ gurus out there. There are two rather similar ways to declare by-reference parameters in C++. 1) Using "asterisk": void DoOne(std::wstring* iData); 2) Using "ampersand": void DoTwo(std::wstring& iData); What are implications of each method? Are there...
#1 uses a pointer parameter ('passing a pointer to'), #2 uses a reference parameter ('passing by reference'). They are very similar, but note that the calling code looks different in the two cases: std::wstring s; DoOne(&s); // pass a pointer to s DoTwo(s); // pass s by reference Some people prefer #1, using a conven...
949,045
949,055
What is the importance of returning reference in operator overloading
Can anybody explain why do you need to return a reference while overloading operators e.g. friend std::ostream& operator<< (std::ostream& out, const std::string& str)
It is to make "chaining" of the operator work, in examples like this: std::cout << "hello," << " world"; If the first (leftmost) use of the operator<<() hadn't returned a reference, there would not be an object to call for the second use of the operator.
949,064
949,093
Cheating in online games: Is it possible to prevent one Win32 process from inspecting/manipulating another's memory?
I play the online game World of Warcraft, which is plagued by automated bots that inspect the game's allocated memory in order to read game/player/world state information, which is used to mechanically play the game. They also sometimes write directly to the game's memory itself but the more sophisticated ones don't, a...
Can't be done. The application is at the mercy of the OS when it comes to memory access. Whoever controls the OS controls access to memory. A user has full access to the whole machine, so they can always starts processes with privileges set to allow them to read from other processes' memory space. This is assuming a 'r...
949,222
949,670
Adding some custom data to the Qt tree model
I am a noob in using model/view paradigm in Qt and have the following problem: I have a tree-like structure, that must be visualized via Qt. I found out, that QAbstractTableModel is perfect for my needs, so I write the following: class columnViewModel : public QAbstractTableModel { // some stuff... }; Everything no...
Do the following: Define a new role (similar to Qt::UserRole), let's say ObserverRole. Use QAbstractItemModel::setData to set the observer as data with observer role. The code sketch: this->model()->setData( ObserverRole, QVariant::fromValue( foo)); You might need to put in the cpp implementation file a declaration f...
949,403
949,456
The specified module could not be found - 64 bit dll
I had the 32 bit dll which is written using Native C, when I tried compiling with VC++(VS2008) for converting the dll to x64 by changing the platform it compiled. But when I tried to access the dll from my C# application which is also 'x64' platform it fails to load the dll. I used Dllimport for linking the dll with my...
try the tool "dependency walker" (ldd-like tool for win, www.dependencywalker.com) to find out what links against what. might be helpful.
949,422
949,525
How much memory was actually allocated from heap for an object?
I have a program that uses way too much memory for allocating numerous small objects on heap. So I would like to investigate into ways to optimize it. The program is compiled with Visual C++ 7. Is there a way to determine how much memory is actually allocated for a given object? I mean when I call new the heap allocate...
There is no exact answer, because some heap managers may use different amount of memory for sequential allocations of the same size. Also, there is (usually) no direct way to measure number of bytes the particular allocation took. You can approximate this value by allocating a certain number of items of the same size ...
949,430
949,895
Does custom action dll-s for msi installer have to be created with Visual Studio only?
I have created setup project with Visual Studio. I also need some custom actions - created DLL with Visual c++ and it works just fine but i don't want to include visual c++ runtime files to my project. So is it possible to build this dll with some other c++ compiler? I have tried to make make it with Dev-c++ but when c...
Probably the easiest solution is to link your DLLs against the static runtime lib.
949,770
954,501
Is the size of an object needed for creating object on heap?
When compiler need to know the size of a C (class) object: For example, when allocating a C on the stack or as a directly-held member of another type From C++ Coding Standards: 101 Rules, Guidelines, and Best Practices Does that mean for a heap allocated object, size is not necessary? Class C;//just forward dec...
To answer your specific question: Does that mean for heap allocated object size is not necessary? Class C;//just forward declaration C * objc = new C(); C++ will not let you do that. Even if it could let you perform a 'new' on an incomplete type by magically resolving the size at a later time (I could envision th...
949,890
951,151
How can I perform pre-main initialization in C/C++ with avr-gcc?
In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following: class Init { public: Init() { initialize(); } }; Init init; Ideally I'd like to be able to simply write: initialize(); but this doesn't compile... Is there a less verbose way to achieve th...
You can use GCC's constructor attribute to ensure that it gets called before main(): void Init(void) __attribute__((constructor)); void Init(void) { /* code */ } // This will always run before main()
949,937
951,164
WIN32 memory issue (differences between debug/release)
I'm currently working on a legacy app (win32, Visual C++ 2005) that allocates memory using LocalAlloc (in a supplied library I can't change). The app keeps very large state in fixed memory (created at the start with multiple calls to LocalAlloc( LPTR, size)). I notice that in release mode I run out of memory at about 1...
You probably have the Debug configuration linking with /LARGEADDRESSAWARE and the Release configuration linking with /LARGEADDRESSAWARE:NO (or missing altogether). Check Linker->System->Enable Large Addresses in the project's configuration properties.
949,966
950,015
Creating dynamically loaded Linux libraries using Eclipse
I am writing a program in C++ using Eclipse. I want to compile it as a library for Linux, somthing like a DLL in Windows. How I can do this? Do you know any tutorials on how libraries are created? I just want to understand that is the analog of a DLL for Linux and how to create it. I will be thankful for a small exampl...
In Linux, DLL's equivalents are (kind of anyway) shared objects (.so). You need to do something like this: $ g++ -c -fPIC libfile1.cpp $ g++ -c -fPIC libfile2.cpp $ g++ -shared -o libyourlib.so libfile1.o libfile2.o Take a look at some open source C++ library projects for more information. GTKMM is one of them. Of cou...
950,072
950,106
How reliable is file sharing on Windows when using it for a database?
We have an application that produces a database on disk. The database is made of thousand of files. The application can have from 500 to 3000 file's handle opened at the same time. These handle are kept opened and data is continuously written to. Up until now, it worked really well on local hard drive, but when trying...
Based on experience with "shared file" databases (dBase, Paradox and the like) this doesn't scale well. It can also be very sensitive to network errors and bad hardware.
950,130
951,018
Use specific version of vcredist?
Is it possible in Visual Studio 2008 SP1 to target a C++ COM project to vcredist 2008 instead of vcredist 2008 SP1? Our customers have the vcredist 2008 installed and we don't want to force them to install vcredist 2008 SP1. (thousands of computers!)
You can try to remove the embed manifest (look under the project settings Manifest Tool) and provide your own manifest for the application that targets the pre sp1 CRuntime versions. You can also deploy the C-Runtime yourself, in the redist folder under x86/x64 you will find the folder of the C-Runtime (Microsoft.VC90...
950,334
950,386
What is the good cross platform C++ IDE?
It needs to have good code completion support, debugger, and a nice way to browse code (click to go to documentation). Since I got spoiled by Java IDEs (Eclipse), it would be cool if it supported refactoring, reference search and some form of on the fly compilation, but maybe I'm asking too much. So far I tried Eclipse...
I have been using Code Lite for some time now. It provides support for auto completion. It has a code explorer and outline, though I find myself using "find resource" to open files. It has a plugin for UnitTest++ and some primitive refactoring capabilities. link text
950,936
950,948
C++ math functions problem (under Linux)
I'm having problem regarding max and sqrt If I include math.h it coudn't find sqrt. So I view the cmath header file and inside it includes math.h, but when I try to open math.h it says that file is not found. SO ithink my math.h is missing in Linux.
Sorry I found the answer. I just need to write it this way: std::max std::sqrt But Why does it work without "std::" under Windows OS?
951,119
952,644
strcpy... want to replace with strcpy_mine which will strncpy and null terminate
The clue is in the title but basically I've inherited some code which has 800+ instances of strcpy. I want to write a new function and then to replace strcpy with strcpy_mine. So I'm trying to work out what parameter list strcpy_mine will have. I tried: void strcpy_mine( char* pTarget, const char* const pCopyMe ) { c...
Depending on how the call-sites look like, often majority of cases can be handled by a simple template: #include <string.h> template <int bufferSize> void strcpy_mine( char (&pTarget)[bufferSize], const char* const pCopyMe ) { strncpy( pTarget, pCopyMe, bufferSize-1 ); //add extra terminator in case of overrun ...
951,234
951,245
Forward declaration of nested types/classes in C++
I recently got stuck in a situation like this: class A { public: typedef struct/class {…} B; … C::D *someField; } class C { public: typedef struct/class {…} D; … A::B *someField; } Usually you can declare a class name: class A; But you can't forward declare a nested type, the following causes compila...
You can't do it, it's a hole in the C++ language. You'll have to un-nest at least one of the nested classes.
951,513
952,350
Where can I find API documentation for Windows Mobile phone application skin?
I have to customize the look of Windows Mobile (5/6) dialer application. From bits and pieces of information and the actual custom skin implementations in the wild I know that it is actually possible to change a great deal. I am looking for ways to change the look and feel of the following screens: Actual dialer (butt...
There is currently no API for the default phone dailer and you can't replace it. The only people that can are the OEM's that make the devices. I beleave you can add a context menu extender but I can't find the sample but that's about it. As the other post article link goes into, there are enough API's in WM that you c...
952,789
953,494
Using Visual Studio 6 C++ compiler from within Emacs
I'm just getting started with c++ development and I would like to use emacs to write the code and then compile and run it from within emacs using the visual studio 6 compiler. I have already googled around a bit but just can't seem to find an explanation of how this is done. Any pointers? Thanks for your help, joerg
I have done this as a matter of course over the past few years. There are two ways to do this: In the older versions of VS (including VS 6.0), there is a button to export the nmake file for the project. I do this on occasion and then use nmake to compile. I have (setq compile-command "nmake debug ") in my .xemace/init...
952,888
952,928
map.erase( map.end() )?
Consider: #include <map> int main() { std::map< int, int > m; m[ 0 ] = 0; m[ 1 ] = 1; m.erase( 0 ); // ok m.erase( 2 ); // no-op m.erase( m.find( 2 ) ); // boom! } (OK, so the title talks abouting erasing an end() iterator, but find will return end() for a non-existent key.) Why is erasing...
For erase(key), the standard says that all elements with value key are removed. There may of course be no such values. For erase(it) (where it is a std::map::iterator), the standard says that the element pointed to by it is removed - unfortunately, if it is end() it does not point to a valid element and you are off in...
952,907
952,963
practices on when to implement accessors on private member variables rather than making them public
I know the differences between public member variables and accessors on private member variables, and saw a few posts already on stack overflow about this. My question has more to do with practices though. Other than not breaking class invariants, what would usually be criterias in terms of practicality to make the mem...
Using an accessor will enforce the client to treat the members as functions, not as raw memory. For instance it will not allow taking the address of said member. So even if the member is as POD as a simple int I still use a get-set pair of function for it. This pays of in the long run as refactoring can change the impl...
953,163
953,204
Disable gcc warning for incompatible options
I'm curious if there is an option to disable gcc warnings about a parameter not being valid for the language being compiled. Ex: cc1: warning: command line option "-Wno-deprecated" is valid for C++/Java/ObjC++ but not for C Our build system passes the warnings we have decided on globally across a build. We have both ...
It seems to me that if there were such an option, there would have to be a further option to turn off warnings about that option, and so on infinitely. So I suspect there isn't. Having the same options for builds of completely different languages seems a bit odd anyway - I would have different options defined as makef...
953,166
954,445
What is the purpose of typedefing a class in C++?
I've seen code like the following frequently in some C++ code I'm looking at: typedef class SomeClass SomeClass; I'm stumped as to what this actually achieves. It seems like this wouldn't change anything. What do typedefs like this do? And if this does something useful, is it worth the extra effort?
See this previous answer to a related question. It's a long quote from a Dan Saks article that explains this issue as clearly as anything I've come across: Difference between 'struct' and 'typedef struct' in C++? The technique can prevent actual problems (though admittedly rare problems). It's a cheap bit of insurance...
953,454
953,506
Sending notifications from C++ DLL to .NET application
I'm writing a C++ DLL that needs to notify client applications. In C++ (MFC), I can register a client window handle inside the DLL, then call PostMessage when I need to notify the client about something. What can I do when the client is a C# application?
You can override the WndProc method in the C# window to handle this specific message protected override void WndProc(ref Message m) { if (m.Msg = YOUR_MESSAGE) { // handle the notification } else { base.WndProc(ref m); } }
953,710
953,731
inline function linker error
I am trying to use inline member functions of a particular class. For example the function declaration and implementation without inlining is as such: in the header file: int GetTplLSize(); in the .cpp file: int NeedleUSsim::GetTplLSize() { return sampleDim[1]; } For some reason if I put the "inline" keyword in e...
You need to put function definition into the header then. The simplest way to hint the compiler to inline is to include method body in the class declaration like: class NeedleUSsim { // ... int GetTplLSize() const { return sampleDim[1]; } // ... }; or, if you insist on separate declaration and definition: clas...
954,015
954,045
Using shared C++/STL code with Objective-C++
I have a lot of shared C++ code that I'd like to use in my iPhone app. I added the .cpp and .h files to my Xcode project and used the classes in my Objective-C++ code. The project compiles fine with 0 errors or warnings. However, when I run it in the simulator I get the following error when I attempt to access an STL...
Make sure the string isn't empty before passing it to the initWithCString function. Also the function you're using has been deprecated, use this one instead.
954,261
954,278
Can one decode real media file to other media formats using any free C++ library?
Please provide some pointers on how to convert real media formats to other popular media formats using some C++ sdk(I guess Helix provides one but don't know how to use it). I am a total newbie in the above area, any help would be highly appreciated.
libavcodec (a library behind ffmpeg and other heavily-used programs) supports some common Real video formats. See this page; the tutorial itself is obsolete, but there are linked updates such as An ffmpeg and SDL Tutorial Helix may be an option, but keep in mind the actual Real Video codecs are only available as binar...
954,266
954,308
Recommendations for an open-source project to help an experienced developer practice C++
I'm looking for recommendations for open-source projects written in C++ that will help me "get my chops back". A little background: I've been working heavily in Java for the last three years, doing a lot of back-end development and system design, but with a fair amount of work in the presentation layer stuff, too. Th...
If you like visual stuff, openFrameworks is a C++ Framework for doing Processing-type applications. http://www.openframeworks.cc/ I'm not sure how viable it still is, but it looked pretty cool. It's hard to suggest something like this, you really don't have any itches you want to scratch??
954,321
956,944
Is it possible to share an enum declaration between C# and unmanaged C++?
Is there a way to share an enum definition between native (unmanaged) C++ and (managed) C#? I have the following enum used in completely unmanaged code: enum MyEnum { myVal1, myVal2 }; Our application sometimes uses a managed component. That C# component gets the enum item values as ints via a managed C++ interop dll...
You can use a single .cs file and share it between both projects. #include in C++ on a .cs file should be no problem. This would be an example .cs file: #if !__LINE__ namespace MyNamespace { public #endif // shared enum for both C, C++ and C# enum MyEnum { myVal1, myVal2 }; #if !__LINE__ } #endif If you wan...
954,548
954,565
How to pass a function pointer that points to constructor?
I'm working on implementing a reflection mechanism in C++. All objects within my code are a subclass of Object(my own generic type) that contain a static member datum of type Class. class Class{ public: Class(const std::string &n, Object *(*c)()); protected: std::string name; // Name for subclass Object *(...
You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not be taken.") Your best bet is to have a factory function/method that creates the Object and pass the address of the factory: class Object; class Class{ public: Class(con...
954,653
954,672
I want to learn COM. How should I proceed?
I am a fresh graduate with a bachelor in Computer Science. As most school today, they are no longer teaching students C or advance C++ (only an Introductory course in C++... With lessons up to Pointers). The standard programming language prescribed in the curriculum is C# (.NET stack). Just recently, I got hired as a j...
The book of Don Box about COM is the definitive reference. Amazon link. Beware is a tough read, but it covers everything in deep. And remember, as Don said... COM IS LOVE. I do not believe you can find a lot of web site, COM was a up to date technology a lot of time ago, but if you can forgot about it trust me... it's ...
954,731
954,778
Can smart pointers selectively hide or re-direct function calls to the objects they are wrapping?
I'm working on a project where certain objects are referenced counted -- it's a very similar setup to COM. Anyway, our project does have smart pointers that alleviate the need to explicitly call Add() and Release() for these objects. The problem is that sometimes, developers are still calling Release() with the smart...
You can't do it - once you've overloaded the operator -> you're stuck - the overloaded operator will behave the same way reardless of what is rightwards of it. You could declare the Add() and Release() methods private and make the smart pointer a friend of the reference-counting class.
954,945
3,067,953
Large number of simulteneous connections in thrift
I'm trying to write a simple server with Thrift. At the beginning it looked promising, but I've stumbled into a problem with a number of clients connected at the same time. I'm using TThreadPoolServer, which allows 4 client to connect and then blocks other clients until I kill one from the connected. What can I do to a...
Taking another approach, if you are using C++ to build your server, you can use TNonblockingServer instead of TThreadPoolServer, which will allow you to accept many connections at once, regardless of how many threads are active, etc... That being said, you won't necessarily be able to actually do work faster (handlers ...
955,129
955,204
Cant focus WxWidgets frame in Mac OSX compiled with SCons
I have this WxWidgets test source code that compiles, and when run, it shows a simple frame: /* * hworld.cpp * Hello world sample by Robert Roebling */ #include "wx-2.8/wx/wx.h" class MyApp: public wxApp { virtual bool OnInit(); }; class MyFrame: public wxFrame { public: MyFrame(const wxString& title, c...
I assume you start the raw executable that is created? This does not work on Mac OS X, see My app can't be brought to the front! You will have to create an application bundle for your app to work properly on Mac OS X. I don't know anything about SCons, but maybe the wiki does help?
955,162
955,179
missing ; before identifier while compiling VC6 code in VC9
The following code compiles fine in VC6 but when I compile the same project in VS2008 it gives the following error error C2146: syntax error : missing ';' before identifier 'm_pItr' template <class pKey, class Data, class pCompare, class hKey = int, class hCompare = less<hKey>, class sKey = int, cl...
You may need to insert 'typename', to tell the compiler PRIMARY_MAP::iterator is, in all cases, a type. e.g. class GCache { private: typedef map<pKey, Data, pCompare> PRIMARY_MAP; PRIMARY_MAP pMap; typename PRIMARY_MAP::iterator m_pItr; //Code truncated }
955,568
955,572
Interfacing MFC and Command Line
I'd like to add a command line interface to my MFC application so that I could provide command line parameters. These parameters would configure how the application started. However, I can't figure out how to interface these two. How could I go about doing this, if it's even possible?
MFC has a CCommandLineInfo class for doing just that - see the CCommandLineInfo documentation.
955,862
955,889
specialised hash table c++
I need to count a lot of different items. I'm processing a list of pairs such as: A34223,34 B23423,-23 23423212,16 What I was planning to do was hash the first value (the key) into a 32bit integer which will then be a key to a sparse structure where the 'value' will be added (all start at zero) number and be negative....
As you are using C++, the first thing you should do is to create a trivial implimentation using std::map. Is it fast enough (it probably will be)? If so, stick with it, otherwise investigate if your C++ implementation provides a hash table. If it does, use it to create a trivial implementation, test, time it. Is it fas...
956,284
956,318
Using C++ Library in Linux (eclipse)
I wrote a library and want to test it. I wrote the following program, but I get an error message from eclipse. #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*desk)(char*); char *error; handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY)...
In C++ you need the following: typedef double (*func)(char*); func desk = reinterpret_cast<func>( dlsym(handle, "Apply"));
956,310
956,647
eliminating the inter-compiler incompatibility issue with C++ dynamic libraries
..., a follow up to this. From the answers I've been given to my referenced question I've learned that: different compilers use different name decoration, which makes it impossible to use a C++ dynamic library built with compiler A in a project built with compiler B, the library can be built as static saving me includ...
I think your approach is right. I'd put it this way: For a dll to be usable by different compilers, it must contain only C functions (they can be compiled using a C++ compiler using extern C) As usual with dlls, a static import library can be used so that functions in the dll can be called directly, rather than needin...
956,504
956,548
Would std::basic_string<TCHAR> be preferable to std::wstring on Windows?
As I understand it, Windows #defines TCHAR as the correct character type for your application based on the build - so it is wchar_t in UNICODE builds and char otherwise. Because of this I wondered if std::basic_string<TCHAR> would be preferable to std::wstring, since the first would theoretically match the character ...
I believe the time when it was advisable to release non-unicode versions of your application (to support Win95, or to save a KB or two) is long past: nowadays the underlying Windows system you'll support are going to be unicode-based (so using char-based system interfaces will actually complicate the code by interposin...
956,546
956,566
CreateFile Win32 API Call with OPEN_ALWAYS failed in an Odd Way
We had a line of code if( !CreateFile( m_hFile, szFile, GENERIC_READ|GENERIC_WRITE, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL ) ) { DWORD dwErr = GetLastError(); CString czInfo; czInfo.Format ("CMemoryMapFile::OpenAppend SetFilePointer call failed - GetLastError returned %d", dwErr); LOG(cz...
Maybe the directory you wanted to create the file in did not exist? Are you sure you fixed it by using 2 CreateFile calls? Or did you just not reproduce it?
956,611
956,864
unique_ptr - major improvement?
In the actual C++ standard, creating collections satisfying following rules is hard if not impossible: exception safety, cheap internal operations (in actual STL containers: the operations are copies), automatic memory management. To satisfy (1), a collection can't store raw pointers. To satisfy (2), a collection mus...
I agree entirely. There's at last a natural way of handling heap allocated objects. In answer to: I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations, there was a proposal to allow this, but it hasn't made it into the C++11 Standard.
956,640
956,698
Linux c++ error: undefined reference to 'dlopen'
I work in Linux with C++ (Eclipse), and want to use a library. Eclipse shows me an error: undefined reference to 'dlopen' Do you know a solution? Here is my code: #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*desk)(char*); char *error...
You have to link against libdl, add -ldl to your linker options
956,658
956,695
Can you use C++ templates to specify a collection type and the specialization of that type?
Example, I want to specialize a class to have a member variable that is an stl container, say a vector or a list, so I need something like: template <class CollectionType, class ItemType> class Test { public: CollectionType<ItemType> m_collection; }; So I can do: Test t = Test<vector, int>(); t.m_collection<vecto...
Why not do it like this? template <class CollectionType> class Test { public: CollectionType m_collection; }; Test t = Test<vector<int> >(); t.m_collection = vector<int>(); If you need the itemtype you can use CollectionType::value_type. EDIT: in response to your question about creating a member function returni...
956,764
956,791
Collection specialized for shared_ptr
Does there exist a collection, that is aware of shared_ptr internals, and avoids regular copying of stored shared_ptr elements in favor of just copying their internal weak pointer? This implicitly means, that no constructor/destructor calls will be done and that there will be no manipulation of shared_ptrs' reference ...
that is aware of shared_ptr internals, That should answer your question right there. To be aware of the internals, such a collection would almost certainly have to be part of boost's smart pointer libraries. Unfortunately, there is no such thing. This is indeed a downside to smart pointers. I would recommend using da...
956,779
956,800
C++ iterator problems
I have the following member data vector<State<T>*> activeChildren; I want to clean-up these pointers in my destructor StateContainer<T>::~StateContainer() { vector<State<T>*>::iterator it = activeChildren.begin(); while(it!=activeChildren.end()) { State<T>* ptr = *it; it = activeChildre...
Looks like typename time again - I think you need: typename vector<State<T>*>::iterator it = ... A heuristic for g++ users - when you see this message in template code: expected `;' before ‘it’ it is a pretty good bet that the thing in front of the 'it' is not being seen by the compiler as a type and so needs a 'type...
956,811
1,061,375
VS2008 C++ app fails to start in Debug mode: This application has failed to start because MSVCR90.dll was not found
I've got a minimal app I just created, using VS 2008 SP1 on Vista x64. Its a Console app, created with the wizard, no MFC or anything, I'm building it in 64bit. When I run the debug exe, on my development box, by pressing F5 in Visual Studio 2008, I get this error: TestApp.exe - Unable To Locate Component This applic...
Thanks again for all the help with this. It turns out I'd just made a mistake and not noticed that a library I was using was statically linked against a different version of the MSVC runtime. That was causing on end of problems.
957,057
957,132
What is the MZ signature in a PE file for?
I'm working on a program that will parse a PE object for various pieces of information. Reading the specifications though, I cannot find out why the MZ bytes are there, as I cannot find this on the list of machine types that these 2 bytes are supposed to represent. Can anyone clarify?
The MZ signature is a signature used by the MS-DOS relocatable 16-bit EXE format. The reason a PE binary contains an MZ header is for backwards compatibility. If the executable is run on a DOS-based system it will run the MZ version (which is nearly always just stub that says you need to run the program on a Win32 syst...
957,087
957,111
When is it preferable to store data members as references instead of pointers?
Let's say I have an object Employee_Storage that contains a database connection data member. Should this data member be stored as a pointer or as a reference? If I store it as a reference, I don't have to do any NULL checking. (Just how important is NULL checking anyway?) If I store it as a pointer, it's ...
It's only preferable to store references as data members if they're being assigned at construction, and there is truly no reason to ever change them. Since references cannot be reassigned, they are very limited. In general, I typically store as pointers (or some form of templated smart pointer). This is much more fle...
957,310
958,208
suggestions on a project in C++ / distributed systems / networks
I'd like to work on a 2-3 month long project (full time) that involves coding in C++ and is related to networks (protocol stacks). I was considering writing my own network stack but that doesn't seem as interesting. It would be great to find an idea to implement a tcp/ip-like stack for distributed system/GPUs that is b...
If you are specifically interested in doing network programming with an emphasis on distribution and GPU/graphics stuff, you may want to check out the open source (GPL) CIGI project (sourceforge project site: CIGI is an open simulation protocol for communication between a host device and IG (image generator). The C...
957,838
957,947
Enforce static method overloading in child class in C++
I have something like this: class Base { public: static int Lolz() { return 0; } }; class Child : public Base { public: int nothing; }; template <typename T> int Produce() { return T::Lolz(); } and Produce<Base>(); Produce<Child>(); both return 0, which is of course correct, but unwanted...
There are two ways to avoid it. Actually, it depends on what you want to say. (1) Making Produce() as an interface of Base class. template <typename T> int Produce() { return T::Lolz(); } class Base { friend int Produce<Base>(); protected: static int Lolz() { return 0; } }; class Child : pub...
958,003
958,092
How to manage special cases and heuristics
I often have code based on a specific well defined algorithm. This gets well commented and seems proper. For most data sets, the algorithm works great. But then the edge cases, the special cases, the heuristics get added to solve particular problems with particular sets of data. As number of special cases grow, the co...
If you have a knowledge base or a wiki for the project, you could add the graph in it, linking to it in the method as per Matthew's Fowler quote and also in the source control commit message for the edge case change. //See description at KB#2312 private object SolveXAndYEdgeCase(object param) { //modify param to so...
958,374
958,501
Correct formatting of numbers with errors (C++)
I have three sets of numbers, a measurement (which is in the range 0-1 inclusive) two errors (positive and negative. These numbers should be displayed consistently to the number of significant figures, rounded up, which corresponds to the first non-zero entry in either of the number. This requirement is skipped on the...
My C++ is rusty, but wouldn't the following do it: std::string FormatNum(double measurement, double poserror, double negerror) { int precision = 1; // Precision to use if all numbers are zero if (poserror > 0) precision = ceil(-1 * log10(poserror)); if (negerror < 0) precision = min(precision, ceil(-1 *...
958,456
958,633
C/C++ Reflection and JNI - A method for invoking native code which hasn't been written yet
I am implementing a piece of Java software that will hopefully allow for C libraries as plugins. In order to call these future functions, I need to somehow create a native function in Java from which I can call the code that doesn't exist yet. The method signature will be static but the method and class names may chang...
The standard way (or common since there is no real standard) Is to create a DLL (shared lib). That DLL has a "C" function with a a fixed name that returns a pointer to a factory object. You can then use the factory to build objects. Example: DLL-> Wdigets1.dll C function -> extern "C" Fac& getWidgetFactory(); DL...
958,464
958,519
Are there any tools for parsing a Visual c++ generated resource script?
Are there any tools for parsing a Visual c++ generated resource script? Is this resource script's format documented any where? I am looking for something in MFC or .net that could parse some data out of the files for reporting.
I do not know of any tools for parsing this, but the format is described in detail at this site. The resource script files are an ASCII text format, so it should be fairly easy to parse out the information you need.
958,625
958,651
In C++, when can two variables of the same name be visible in the same scope?
This code illustrates something that I think should be treated as bad practice, and elicit warnings from a compiler about redefining or masking a variable: #include <iostream> int *a; int* f() { int *a = new int; return a; } int main() { std::cout << a << std::endl << f() << std::endl; return 0; } Its outpu...
It's allowed so that you can safely ignore global identifier overriding. Essentially, you only have to be concerned with global names you actually use. Suppose, in your example, f() had been defined first. Then some other developer added the global declaration. By adding a name, f() which used to work, still works...
958,695
958,699
C++ Compiler for Windows without IDE?
I'm looking for just a compiler for C++ (such as g++) for Windows, that I could run in my cmd. I'm using notepad++ as my text editor and I want to set up a macro in there that can compile my programs for me. I do not wish to install Cygwin though. Any suggestions?
MinGW. It's GCC/G++ for Windows. It's much lighter than Cygwin. The main difference from Cygwin GCC is that it doesn't try to emulate UNIX APIs, you have to use the Windows APIs (and of course the standard C/C++ libraries). It also doesn't provide a shell and utilities like Cygwin, just the compiler. There is also a re...
958,865
958,871
Simple Question: Passing object with state, C++
I'm not an C++ expert and still do not have a great intuitive grasp of how things works. I think this is a simple question. I am having trouble passing objects with state to other objects. I'd prefer to avoid passing pointers or references, since once the initialized objects are setup, I call them millions of times i...
What you may want to do is use the member initialisation syntax: class TakesObject { public: TakesObject(ObjectWithState obj): obj_(obj) { } private: ObjectWithState obj_; }; In your posted code, the TakesObject constructor will first try to construct a new ObjectWithState with its default constructor, then call...
959,067
959,105
trapping http/https requests in windows
Is it possible to trap http/https requests for filtering in windows?
If you need to sniff the packets, you could use Ethereal or Wireshark Update: Try WinPcap then it gives you a lot of features along with the popular *nix Library libpcap API
959,183
959,214
Appending ints to char* and then clearing
I'm working on a project using an Arduino and as such, I'm reading from a serial port (which sends ints). I need to then write this serial communication to an LCD, which takes a char*. I need to read several characters from the serial port (two integers) into a string. After both have been received, I then need to clea...
A char is a single character, whereas a char* can be a pointer to a character or a pointer to the first character in a C string, which is an array of chars terminated by a null character. You can't use a char to represent an integer longer than 1 digit, so I'm going to assume you did in fact mean char*. If you have cha...
959,193
959,201
How to declare factory-like method in base class?
I'm looking for solution of C++ class design problem. What I'm trying to achieve is having static method method in base class, which would return instances of objects of descendant types. The point is, some of them should be singletons. I'm writing it in VCL so there is possibility of using __properties, but I'd prefer...
Just to check we have our terminologies in synch - in my book, a factory class is a class instances of which can create instances of some other class or classes. The choice of which type of instance to create is based on the inputs the factory receives, or at least on something it can inspect. Heres's a very simple fac...
959,261
959,282
My C Program provides a callback function for a hook. How can I keep it alive, un-kludgily?
Currently, I'm spawning a message box with a OS-library function (Windows.h), which magically keeps my program alive and responding to calls to the callback function. What alternative approach could be used to silently let the program run forever? Trapping 'Ctrl-c' or SIGINT and subsequently calling RemoveHook() for a ...
You probably want to pump messages. A typical message loop looks like something like this: BOOl ret; MSG msg; while ((ret=::GetMessage(&msg, hWnd, 0, 0))!=0) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } You don't seem to have an actual window to pump on, and you don't say what SetHook is actually doing -...
959,589
959,594
Is there any Win32 API to trigger the hibernate or suspend mode in Windows?
Is there any Win32 API to put the machine into hibernate or suspend mode? I read MSDN and found that WM_POWERBROADCAST message gets broadcasted when power-management events occur. I thought of simulating the same with PostMessage(WM_POWERBROADCAST). Is this the correct way of doing or any Win32 API exists to achieve t...
Check out SetSuspendState. Note that you need SE_SHUTDOWN_NAME privilege, as mentioned on the referenced msdn page.
959,621
959,631
C++ idiom to avoid memory leaks?
In the following code, there is a memory leak if Info::addPart1() is called multiple times by accident: typedef struct { }part1; typedef struct { }part2; class Info { private: part1* _ptr1; part2* _ptr2; public: Info() { _ptr1 = _ptr2 = NULL; } ~Info() { delete _p...
Use a smart pointer such as boost:shared_ptr , boost:scoped_ptr is recommended to manage the raw pointer. auto_ptr is tricky to work with, you need pay attention to that.
959,837
959,873
How can I know the type of a file using Boost.Filesystem?
I'm using Boost but I cannot find complete (or good) documentation about the filesystem library in the installation directory nor the web. The "-ls" example I found has been quite a helper but it's not enough. Thanks in advance :)
How about: http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm The functions for figuring out the file type (directory, normal file etc.) is found on this subpage: http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/reference.html#file_status If you are looking for the file extension check out: temp...
959,947
960,084
Asynchronous Windows Console input whilst outputting
I'm having issues trying to read input whilst outputting at the same time. I need a server console for my game which can receive input whilst outputting and not mess up the buffer. For example, I'm typing "Hello world" and in the process, player deaths, kills, etc. are being outputted into the console, which would resu...
Instead of writing output directly to the console, why not spawn a GUI window? Then, just have one area where output is directed, and a separate input area at the bottom where you can type commands. Kinda like how an irc client would look. If it has to be console only, I would suggest using something like ncurses (or P...
959,951
959,972
Returning reference to static local variable in C++
This question is just for my better understanding of static variables in C++. I thought I could return a reference to a local variable in C++ if it was declared static since the variable should live-on after the function returns. Why doesn't this work? #include <stdio.h> char* illegal() { char * word = "hello" ; r...
The two functions are not itself illegal. First, you in both case return a copy of a pointer, which points to an object having static storage duration: The string literal will live, during the whole program duration. But your main function is all about undefined behavior. You are not allowed to write into a string lit...
960,036
960,038
How to change a value in memory space of another process
If you could help me with this dilemma I have. Now, I know C \ C++, I know asm, I know about dll injection, I know about virtual memory addressing, but I just can't figure out how software like CheatEngine, and others, manage to change a variable's value in another process. For those who don't know, 3rd party cheat eng...
I'm fairly certain those programs are pretending to be debuggers. On Windows, I would start with DebugActiveProcess() and go from there. Oh, and the very useful looking ReadProcessMemory() function (and WriteProcessMemory()).
960,089
963,913
Html renderer with limited resources (good memory management)
I'm creating a linux program in C++ for a portable device in order to render html files. The problem is that the device is limited in RAM, thus making it impossible to open big files (with actual software). One solution is to dynamically load/unload parts of the file, but I'm not sure how to implement that. The ability...
To be able to browse a tree document (like HTML) without fully loading, you'll have to make a few assumptions - like the document being an actual tree. So, don't bother checking close tags. Close tags are designed for human consumption anyway, computers would be happy with <> too. The first step is to assume that the f...
960,122
961,130
Xerces-C problems; segfault on call to object destructor
I've been playing around with the Xerces-C XML library. I have this simple example I'm playing with. I can't seem to get it to run without leaking memory and without segfaulting. It's one or the other. The segfault always occurs when I delete the parser object under "Clean up". I've tried using both the 2.8 & 2.7 ve...
" xmlDoc->release(); " is the culprit. You dont own that Node unless you say " xmlParser->adoptDocument() " http://xerces.apache.org/xerces-c/apiDocs-2/classAbstractDOMParser.html#fe052561c37d70b62ac57ab6706d75aa
960,218
960,221
i need a good website to learn c++
i want to learn C++; and i already have a compiler. i already know a few programming languages including: BASIC (yes, the dos version) visualBasic (using VisualBasic Express 2006 or 8 i'm not quite sure) Java PHP HTML (if we count that) so it doesn't need to be for absolute beginners; although if you find one post it...
www.cplusplus.com is a great website with tons of documentation for experts and beginners. Tutorials for beginners: http://www.cplusplus.com/doc/tutorial/ An additional website I heartily reccomend once you have a little more expertise is the C++ FAQ Lite.
960,432
960,445
UML - How to manage big class diagrams?
For my project report, i need to show the class diagram of the software i've built which counts around 20 classes! The problem, is that when i render the class diagram in jpeg file(either using StarUML or ArgoUMl or whatever..) we can't see the details correctly (very big picture because of the large number of classes)...
With 20 classes I would expect at least 3 subsystems, (modules, layers), possibly more Make package diagram showing the relation between those, one class diagram for each subsystem. Add class diagrams for special things you want to show. Print each on A4. If you can't split the diagram easily into modules, I'd consider...
960,459
960,703
realloc crashing in previously stable function
Apparently this function in SDL_Mixer keeps dying, and I'm not sure why. Does anyone have any ideas? According to visual studio, the crash is caused by Windows triggering a breakpoint somewhere in the realloc() line. The code in question is from the SVN version of SDL_Mixer specifically, if that makes a difference. sta...
For one thing, it's not valid to allocate an array of num_decoders pointers, and then write to index num_decoders in that array. Presumably the first time this function was called, it allocated 0 bytes and wrote a pointer to the result. This could have corrupted the memory allocator's structures, resulting in a crash/b...
960,541
960,570
Detecting reason for failure to open an ofstream when fail() is true
Seems like this should be simple, but I don't find it in a net search. I have an ofstream which is open(), and fail() is now true. I'd like to know the reason for the failure to open, like with errno I would do sys_errlist[errno].
Unfortunately, there is no standard way of finding out exactly why open() failed. Note that sys_errlist is not standard C++ (or Standard C, I believe).
960,648
961,183
Calculating larger values of the ackermann function
I have some code: int CalculateAckermann(int x, int y) { if(!x) { return y++; } if(!y) { return CalculateAckermann(x--,1); } else { return CalculateAckermann(x--, CalculateAckermann(x, y--)); } } Designed to calculate the ackermann function. Above a fairly lo...
As a note if you wish to just used the closed form, then the algorithms for m<4 are straightforward. If you wish to extend to tetration, then I suggest you write a fastpower algorithm probably using the binary method and then with that method you can write a tetration function. Which would look something like: int Tetr...
961,237
961,396
When to use assembly language to debug a c/c++ program?
When to use the assembly to debug a c/c++ program? Does it help to learn some assembly to debug programs?
It can be very helpful in cases where you can not (yet) reliably reproduce a bug, such as due to heap/stack corruption. You might get one or two core dumps, quite possibly from a customer. Even assuming your debugger is reliable, looking at assembly can tell you exactly which instruction is crashing (and thus which pie...
961,297
961,311
Does defensive programming violate the DRY principle?
Disclaimer: I am a layperson currently learning to program. Never been part of a project, nor written anything longer than ~500 lines. My question is: does defensive programming violate the Don't Repeat Yourself principle? Assuming my definition of defensive programming is correct (having the calling function validate ...
It all comes down to the contract the interface provides. There are two different scenarios for this: inputs and outputs. Inputs--and by that I basically mean parameters to functions--should be checked by the implementation as a general rule. Outputs--being return results--should be basically trusted by the caller, at ...
961,565
987,185
Xerces: How to merge duplicate nodes?
My question is this: If I have the following XML: <root> <alpha one="start"> <in>1</in> </alpha> </root> and then I'll add the following path: <root><alpha one="start"><out>2</out></alpha></root> which results in <root> <alpha one="start"> <in>1</in> </alpha> </root> <root> <alpha one="start"> <...
If you use xalan its possible to use an xpath to find the element and directly insert into the correc one. The following code may be slow but returns all "root" elments with the attribute "one" set to "start". selectNodes("//root[@one="start"]") It is probably better to use the full path selectNodes("/abc/def/.../root...
961,943
961,947
c++ overloading operators, assignment, deep-copy and addition
I'm doing some exploration of operator-overloading at the moment whilst re-reading some of my old University text-books and I think I'm mis-understanding something, so hopefully this will be some nice easy reputation for some answerers. If this is a duplicate please point me in the right direction. I've created a simpl...
You need to pass your parameters as const reference. For example: counter& counter::operator=( const counter &rhs ) And similarly for operator+(). This is necessary in order to be able to bind temporary values to the function parameter(s). Temporary values are created when you return by value, so when you say: varOne ...
961,970
961,998
Flash SMS in Windows Mobile
How can i write code for send Flash SMS (Sms Class 0) in Windows Mobile? please guide me with .NET or C++ code also .Net is better.
Use the PROVIDER_SPECIFIC_MESSAGE_CLASS enumeration's PS_MESSAGE_CLASS0 value provided in a call to SmsSendMessage (the pbProviderSpecificData parameter). This code is a bit lower level than Compact Framework's APIs, thus gives you some more control over the message you want to send. You have to marshall it from native...
962,086
962,094
One question about element inserting in STL list
CODE: struct Stringdata { // Length of data in buffer. size_t len; // Allocated size of buffer. size_t alc; // Buffer. char data[1]; }; typedef std::list<Stringdata*> Stringdata_list; Stringdata_list strings_; Stringdata *psd = this->strings_.front(); //... if (len > psd->alc - psd->len) alc = sizeof(St...
Your code appears to do neither. The code in the else branch does not modify the strings_ structure at all. The code is only modifying the element return from the front of the list. This should have no affect on the actual list structure.
962,132
962,148
Calling virtual functions inside constructors
Suppose I have two C++ classes: class A { public: A() { fn(); } virtual void fn() { _n = 1; } int getn() { return _n; } protected: int _n; }; class B : public A { public: B() : A() {} virtual void fn() { _n = 2; } }; If I write the following code: int main() { B b; int n = b.getn(); } One might ex...
Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further. The C++ FAQ Lite covers this in section 23.7 in pretty good d...
962,175
975,835
Compiling with Ogre + MFC in _DEBUG mode
There is a problem compiling Ogre with MFC in debug mode, you get an error because of the MFC macro: #ifdef _DEBUG #define new DEBUG_NEW Which basically clobbers Ogre's debug new - #define OGRE_NEW new (__FILE__, __LINE__, __FUNCTION__) I'm trying to get MFC+Ogre to run merrily together in DEBUG mode, and I got it ...
I think this might be a problem in the specific machine I was using. I tried this out on another machine, and it seemed to work in debug mode with the #ifdefs #undefs as shown above.
962,573
962,595
How to manipulate this interface?
I have seen lots of kinds of interface to multithreading and locks. These make me feel frustrating, Some of them include 2 different classes like the sample below, while others have only one class and the acquire() can implement the wait function. My questions are: Why we design locks like this in object oriented prog...
The above is a lock and a condition variable. These are two unique concepts: A lock is just a single atomic lock on or off. A condition variable (is much harder to use correctly) and requires a lock to implement correctly but maintains a state (basically a count). For information about "Condition Variables" see: http:/...
962,590
962,606
Constructor cannot access private members of its own class
I get the following error in Visual Studio 2008: error C2248: 'Town::Town' : cannot access private member declared in class 'Town'. It looks like the constructor is unable to access the members of its own class. Any idea what's going on? Here's the code: I have this: template<class T> class Tree{...} And this class...
By default class access level is private. If you do not add a public: before the Town constructor it will be private. class Town{ public: // <- add this Town(int number):number(number){}; ... private: int number; };
962,599
962,650
Binary operator overloading on a templated class
I was recently trying to gauge my operator overloading/template abilities and as a small test, created the Container class below. While this code compiles fine and works correctly under MSVC 2008 (displays 11), both MinGW/GCC and Comeau choke on the operator+ overload. As I trust them more than MSVC, I'm trying to figu...
I found the solution thanks to this forum posting. Essentially, you need to have a function prototype before you can use 'friend' on it within the class, however you also need the class to be declared in order to properly define the function prototype. Therefore, the solution is to have two prototype definitons (of the...
962,879
962,895
Visual C++ Linking LNK2019 Error with a Precompiled Header
I had a very weird problem with precompile header. The linker generates LNK2019: unresolved external symbol error when I implement method in .cpp file. However, the program could be compiled if I implement method in .h file. I happened to find out a solution but I have no idea about the root cause of this error. My pr...
Project 2 does not include the definition of the A constructor - one way to give it visibility of this is to include the definition in the header file (which you did). Another way would be to include the A.cpp file in project 2. A third way would be to export the A class, or the A constructor using a .def file or using...
962,901
962,916
End of Line on Windows cmd
I have a while(cin >> string) loop in which I want the user to input a string. However, I do not know how to end the input. I know on *nix machines for bash shell, I can use ctrl-D. But this does not seem to work on cmd.exe for Windows... Any tips? [Edit] This is on C++
The Windows equivalent of Ctrl+D is Ctrl+Z Enter.
962,925
962,927
C++ Class Common String Constants
In C++ I would like to define some strings that will be used within a class but the values will be common over all instances. In C I would have used #defines. Here is an attempt at it: #include <string> class AskBase { public: AskBase(){} private: static std::string const c_REQ_ROOT = "^Z"; static std::stri...
You will have to define them separately in a single translation unit (source file), like so: //header class SomeClass { static const std::string someString; }; //source const std::string SomeClass::someString = "value"; I believe the new C++1x standard will fix this, though I'm not entirely sure.
962,941
962,943
Holding cmd.exe open on Vista
I'm writing C++ console programs. After compilation, when I run the program from my file browser, cmd.exe automatically closes such that I can't see my programs output. The only way to work around this I've found is to run the program from inside cmd.exe Is there anyway to keep cmd.exe open after a program finishes run...
Have your application ask for a keypress before exiting - that's the easiest fix!
962,995
963,048
mapping of a contained struct with boost
Considering these two structs: struct point { int x,y; }; struct pinfo { struct point p; unsigned long flags; }; And a function, that changes a point: void p_map(struct point &p); Is it possible to use boost (e.g. boost::bind or boost::lambda) to create a function equivalent with: void pi_map(struct pinf...
You can do it with boost::lambda, member variables can be bound with bind the same way member functions are: #include <boost/function.hpp> #include <boost/lambda/bind.hpp> using namespace boost::lambda; boost::function<void (pinfo&)> pi_map = bind(&p_map, bind(&pinfo::p, _1));
963,158
964,040
Helping getting started using Boost.Test
I am trying to start unit testing. I am looking at a few C++ frameworks and want to try Boost.Test. The documentation seems very thorough, and it's a bit overwhelming, especially someone new to unit testing. So here's a situation that I want: Let's say I have 2 classes, Foo and Bar. I want to write a suite of tests for...
BOOST.Test is very flexible and you can probably do what you want. However since you say you are new to unit testing, you should probably follow the standard unit testing structure. This is to have a separate test project for each project you are unit testing. Then include the sources and libraries you need to build ...
963,259
963,371
Transitioning from Java to C and then C++?
Currently I am working with Java and its object oriented-design aspects (I also work with PHP/MySQL a lot). I don't implement it on the web; I just use it for designing programs for general purposes. However, now I need to learn C right now, and I have an interest in C++. I got The C Programming Language, which some pe...
Don't worry one bit. I started programming with Java, then moved on to C++. And then I learned x86 assembly and now I'm into C and then I came back to use some features of C++ like objects. I even did a Java project not long ago. The order is not important, as long as you put work in learning these languages, you will ...