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,724,332
1,724,505
How do I install GDI+ version 1.1 on Windows XP?
Has anyone done this successfully? As I understand, GDI+ 1.1 only ships with Vista. I'm trying to get my hands on the different Effects classes. I'm using C++ VS2008 (VC9)
GDI+ 1.1 is not redistributable according to EULA of Windows Vista.
1,724,842
1,724,884
Dynamic output filenames (C++)
I'm trying to create output files subscripted by a dynamic index ( d = {0,...,NUM_DEMES-1}). Currently, I'm only getting output files for the first value (d=0). #include <sstream> #include <string> void Simulation::updateSimulation( double t ) { ... ofstream abundanceStream; ofstream abHeaderStream; if ( ste...
You are always using the same objects. You can either close the streams after "use" or use different objects for each file.
1,725,147
1,725,182
Templates, nested classes, and "expected constructor, destructor, or conversion before '&' token"
While working with some templates and writing myself a basic container class with iterators, I found myself needing to move the body of member functions from a template class into a separate file to conform to style guidelines. However, I've run into an interesting compile error: runtimearray.cpp:17: error: expected ...
I think that you are missing the typename keyword. e.g. template<typename T> RuntimeArray<T>::Iterator& RuntimeArray<T>::Iterator::operator++() should be template<typename T> typename RuntimeArray<T>::Iterator& RuntimeArray<T>::Iterator::operator++() 'Nested' types which are dependent on a template parameter need the...
1,725,237
1,726,046
Outputting unicode characters in windows terminal
Over the past week I've been working on a roguelike game in C++ along with a friend. Mostly too learn the language. I'm using: pdcurses Windows 7 Visual studio C++ To output wchar_t's wherever I want to in the console. I have succeeded in otuputting some unicode characters such as \u263B (☻), but others such as \u263...
The problem is that I need to force the terminal to switch to a more unicode-rich font face. Is there a cross-platform way to do this? is there even a windows specific way to do this? I had a look for this, but couldn't find a Windows API call to do it (which may just mean I didn't find it, of course). I would not ex...
1,725,498
1,725,954
Is anybody working on a high level standard library for C++
STL/Boost cover all the low level stuff. But what about the higher level concepts? Windows: We have multiple windowing libs KDE(Qt) Gnome Motif(C but written in OO style) MS Windows etc But is anybody working on a unified standard for windowing? Something that wrapped all the above would be acceptable. (even if it on...
The Poco C++ project aims to deliver all that you ask, except for Windowing: The POCO C++ Libraries aim to be for network-centric, cross-platform C++ software development what Apple's Cocoa is for Mac development, or Ruby on Rails is for Web development — a powerful, yet easy to use platform to build your ...
1,725,714
1,725,770
Why ofstream would fail to open the file in C++? Reasons?
I am trying to open an output file which I am sure has a unique name but it fails once in a while. I could not find any information for what reasons the ofstream constructor would fail. EDIT: It starts failing at some point of time and after that it continuously fails until I stop the running program which write this f...
Too many file handles open? Out of space? Access denied? Intermittent network drive problem? File already exists? File locked? It's awfully hard to say without more details. Edit: Based on the extra details you gave, it sounds like you might be leaking file handles (opening files and failing to close them and so...
1,726,104
1,726,190
visual studio intellisense error
template <typename T> class Test { friend Test<T> & operator * (T lhs, const Test<T> & rhs) { Test<T> r(rhs); // return r *= lhs; } } 4 IntelliSense: identifier "T" is undefined Why is T defined on line 3 but not line 4? I mean I guess it's not a real error just an intellise...
Intellisense shows T as undefined because it is a generic template type. Depending on how you instantiate the class, T will be a different type. For example if you have Test<int> A, T is of type int, but if you call Test<string> A, T is of type string for that class and it's methods.
1,726,122
1,726,165
SDL_image/C++ OpenGL Program: IMG_Load() produces fuzzy images
I'm trying to load an image file and use it as a texture for a cube. I'm using SDL_image to do that. I used this image because I've found it in various file formats (tga, tif, jpg, png, bmp) The code : SDL_Surface * texture; //load an image to an SDL surface (i.e. a buffer) texture = IMG_Load("/Users/Foo/Code/xcode/...
The reason the image is distorted is because it's not in the RGBA format that you've specified. Check the texture->format to find out the format it's in and select the appropriate GL_ constant that represents the format. (Or, transform it yourself to the format of your choice.)
1,726,236
1,727,044
system call does not work as in the command line
Ok I have two programs, and one calls another using executable from another. I am running it on Ubuntu terminal This is folder structure in place .../src/pgm1/pgm1 .../src/pgm0/pgm0 pgm1 and pgm0 are executables. This is how I call the other executable char cmd[1000]; string path = "/home/usr/src/"; // c...
You are using > which means something to many shells, but I suspect not to system. Try this: snprintf( cmd, sizeof cmd, "/usr/bin/bash -c '../pgm0/pgm0 xRes 400 xRes 400" " inFile tmp_output/%s.%04d.sc > tmp_output/%s.%04d.ppm'", g_outFile.c_str(), ti, g_outFile.c_str(), ti); And let us know how that goes...
1,726,242
1,726,325
Is there a way to customize the tool tip of a custom object in the VS Debugger?
Is there a way to customize the tool tip of a custom object in the VS Debugger? anyway to do same for unmanaged c++? thanks
Have you had a look at <VSInstallDir>\Common7\Packages\Debugger?
1,726,425
1,726,653
Adding elements to a vector inside a c++ class not being stored
Edit: My debugger was lying to me. This is all irrelevant Howdy all, I had a peek at Adding element to vector, but it's not helpful for my case. I'm trying to add an element (custom class LatLng) to another object (Cluster) from a third object (ClusterManager). When I pass my LatLng to Cluster (last line of ClusterMan...
The debugger is possibly lying. I've found Xcode has issues has viewing the contents of vectors, try using some asserts to make sure the vector in question is actually being filled.
1,726,462
1,726,528
Memory Leak Analysis
There is a memory leak in my application. The memory consumption shoots up after a couple of days of running the application. I need to dump call stack information of each orphaned block address. How is it possible with WinDbg? I tried referring to document created by my colleague, but I'm confused about how to speci...
You can use umdh.exe to capture and compare snapshots of the process before and after leak happens. This works best with Debug binaries - it will give you the callstacks of memory allocated between the 1st and the 2nd snapshot. http://support.microsoft.com/kb/268343
1,726,541
1,738,013
Failing to set COM+ ConstructorString on Win7 - CryptProtectData changes?
UPDATED I'm trying to programmatic-ally set a COM+ component's ConstructorString with a value for later initialization. The code in question works fine on WinXP, Win2k3, Vista and Win2k8. I'm failing on Win7 - Home Premium version. I've determined by trial and error that there seems to be a size limit on the constructo...
What do you do with dataOut to turn it into a string? I can't remember the exact details now, but I assume the constructor string is a BSTR. dataOut is a byte buffer, so you need to be very careful when converting it to a string, so you don't trip on embedded NUL characters, etc. Could you update your question to incl...
1,726,740
1,726,777
c++ error: operator []: 2 overloads have similar conversions
template <typename T> class v3 { private: T _a[3]; public: T & operator [] (unsigned int i) { return _a[i]; } const T & operator [] (unsigned int i) const { return _a[i]; } operator T * () { return _a; } operator const T * () const { return _a; } v3() { _a[0] = 0; // works _a[...
If you read the rest of the error message (in the output window), it becomes a bit clearer: 1> could be 'const float &v3<T>::operator [](unsigned int) const' 1> with 1> [ 1> T=float 1> ] 1> or 'built-in C++ operator[(const float *, int)' 1> while trying to matc...
1,727,081
1,727,187
typedef'ing STL wstring
Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, but when i ever attempt to create a new Foo::String from a wchar_t* i get an error, e.g.: namespace Bar { static const...
The following code compiled and ran under llvm-gcc: #include <string> namespace Foo { typedef std::wstring String; } namespace Bar { static const wchar_t* COMMON_BAR = L"Hello"; } int main() { Foo::String A(Bar::COMMON_BAR); }; Notice how you accidentally had COMMON_DATA_PATH instead. I'm not sure which c...
1,727,143
1,727,161
C++ enum value initialization
I have an enum declared in my code as: enum REMOTE_CONN { REMOTE_CONN_DEFAULT = 0, REMOTE_CONN_EX_MAN = 10000, REMOTE_CONN_SD_ANNOUNCE, REMOTE_CONN_SD_IO, REMOTE_CONN_AL, REMOTE_CONN_DS }; I expect the value of REMOTE_CONN_SD_IO to be 10002, but when debugging the value of ((int)REMOTE_CONN_SD_...
OK, I'll guess. The first component was built before you changed the code in the header. Try rebuilding the offending component.
1,727,174
1,727,182
Open source C/C++ 3d renderer (with support of 3ds max models)
Best, smallest, fastest, open source, C/C++ 3d renderer (with support of 3ds max models), better not GPL, It should support Lights, textures (better dynamic), simple objects, It should be really fast and it shall have lots of use examples
I would advise Ogre, it's pretty mature and really good API. Ogre license there is a plugin to export 3DSMax model to the orgre format there.
1,727,282
1,729,020
C++ Equivalent of Tidy
Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am basically looking for something to take code written by two people, and clean it up to a standardized style. Does such an app ...
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages. GC Great Code is a well known C/C++ source code beautifier.
1,727,361
1,745,044
How to read/write data into excel 2007 in c++?
How to read/write data into excel 2007 in c++?
Excel provides COM interface which you can use from your C++ application. I have experience with Excel 2003 only but I think for excel 2007 it will also work. This can be done e.g. with #import or in the way described in this article: http://support.microsoft.com/kb/216686
1,727,471
1,729,994
c++: generate function call tree
I want to parse current c++ files in a project and list out all the methods/functions in it and then generate the function call and caller trees. F.g. you can refer how doxygen generates the call tree. I have checked gccxml but it doesn't list the functions called from another function. Please suggest me some lightweig...
The static call tree isn't necessarily the runtime call tree. Callbacks and virtual functions muddy the water. So static analysis can only give you part of the answer. The only way I've ever been able to get a reliable call tree was to run gprof on the compiled executable. The output can be massaged into a very accu...
1,727,569
1,727,606
What are the benefits to passing integral types by const ref
The question: Is there benefit to passing an integral type by const reference as opposed to simply by value. ie. void foo(const int& n); // case #1 vs void foo(int n); // case #2 The answer is clear for user defined types, case #1 avoids needless copying while ensuring the constness of the object. However in the abov...
Passing a built-in int type by const ref will actually be a minor de-optimization (generally). At least for a non-inline function. The compiler may have to actually pass a pointer that has to be de-referenced to get the value. You might think it could always optimize this away, but aliasing rules and the need to supp...
1,727,594
1,733,370
Optimal datafile format loading on a game console
I need to load large models and other structured binary data on an older CD-based game console as efficiently as possible. What's the best way to do it? The data will be exported from a Python application. This is a pretty elaborate hobby project. Requierements: no reliance on fully standard compliant STL - i might us...
This is a common game development pattern. The usual approach is to cook the data in an offline pre-process step. The resulting blobs can be streamed in with minimal overhead. The blobs are platform dependent and should contain the proper alignment & endian-ness of the target platform. At runtime, you can simply cast...
1,727,608
1,727,755
How do I get hardware information on Linux/Unix?
How I can get hardware information from a Linux / Unix machine. Is there a set of APIs? I am trying to get information like: OS name. OS version. available network adapters. information on network adapters. all the installed software. I am looking for an application which collects this information and show it in a n...
If you need a simple answer, use: cat /proc/cpuinfo cat /proc/meminfo lspci lsusb and harvest any info you need from the output of these commands. (Note: the cut command may be your friend here if you are writing a shell script.) Should you need more detail, add a -v switch to get verbose output from the lspci and ls...
1,727,824
1,727,939
Does using callbacks in C++ increase coupling?
Q1. Why are callback functions used? Q2. Are callbacks evil? Fun for those who know, for others a nightmare. Q3. Any alternative to callback?
Regardless of "using callbacks in C++ increase coupling" or not, I suggest using event handler style especially process event-like things. For example, concrete a Design Pattern instead of callback concept as the below: class MyClass { public: virtual bool OnClick(...) = 0; virtual bool OnKey(...) = 0; virt...
1,727,881
1,727,896
How to use the PI constant in C++
I want to use the PI constant and trigonometric functions in some C++ program. I get the trigonometric functions with include <math.h>. However, there doesn't seem to be a definition for PI in this header file. How can I get PI without defining it manually?
On some (especially older) platforms (see the comments below) you might need to #define _USE_MATH_DEFINES and then include the necessary header file: #include <math.h> and the value of pi can be accessed via: M_PI In my math.h (2014) it is defined as: # define M_PI 3.14159265358979323846 /* pi */ but ch...
1,728,158
1,728,189
Why is new[] allocating extra memory?
I'm reading "Thinking in C++" and I'm confused by the new operator. Here is the code from the book: //: C13:ArrayOperatorNew.cpp // Operator new for arrays #include <new> // Size_t definition #include <fstream> using namespace std; ofstream trace("ArrayOperatorNew.out"); class Widget { enum { sz = 10 }; in...
When using new[] the runtime needs some way to remember the size of the array allocated, so it knows how much to deallocate when using delete[]. In your particular implementation it's way of remembering is allocating the extra four bytes which hold the size (it doesn't have to work this way). You can read more about th...
1,728,772
1,728,798
Is it correct to use declaration only for empty private constructors in C++?
For example is this correct: class C { private: C(); C(const & C other); } or you should rather provide definition(s): class C { private: C() {}; C(const & C other) {}; } ? Thanks for the current answers. Let's extend this question - does compiler generate better code in one of this exa...
If you do not wish your object to be copyable, then there is no need to provide the implementation. Just declare the copy ctor private without any implementation. The same holds for other ctors, if you do not want any body to use them, just declare them private without any implementation.
1,728,847
1,728,890
How can i find a value in a map using binders only
Searching in the second value of a map i use somthing like the following: typedef std::map<int, int> CMyList; static CMyList myList; template<class t> struct second_equal { typename typedef t::mapped_type mapped_type; typename typedef t::value_type value_type; second_equal(mapped_type f) : v(f) {}; ...
Use a selector to select the first or the second element from the value_type that you get from the map. Use a binder to bind the value (i) to one of the arguments of the std::equal_to function. Use a composer to use the output of the selector as the other argument of the equal_to function. //stl version CMyList::iterat...
1,728,909
1,728,925
How to find the number of data added in CStringArray
Helo guys, I am working wid CStringArray and i want to know how to find the number of datas added in a CStringArray . in the below i have a defined the size of the array as 10 but i have added only three 3 data,So i want to know the number of data's added to the array.(here its 3).Is there any way we can do it...
CStringArray::GetCount() Edit: In your code above you have actually created an array of CStringArray's. I am presuming you mean CStringArray from the Microsoft MFC library? I think you want to be doing something like: CStringArray filepaths; filepaths.Add( path1 ); filepaths.Add( path2 ); filepaths.Add( path3 ); file...
1,728,961
1,728,980
Extract statically linked libraries from an executable
I'm not sure if this is even possible, but given an executable file (foo.exe), with has many libraries which has been linked statically. Is there any software that extract from this file the .lib ( or .a ) that lay inside the executable ? Thanks.
Incredibly unlikely since, typically, you don't get the entire contents of the library injected into your executable. You only get enough to satisfy all the undefined symbols. This may actually only be a small part of the library. A library generally consists of a set of object files of which only those that are requir...
1,729,326
1,729,354
templated class can't redefine operator[]
I've this class namespace baseUtils { template<typename AT> class growVector { int size; AT **arr; AT* defaultVal; public: growVector(int size, AT* defaultVal ); //Expects number of elements (5) and default value (NULL) AT*& operator[](unsigned pos); int length(...
The problem is your declaration growVector<char> gv(); The compiler interprets this as declaring a function called gv which returns a growVector<char>, not as an object as you indend. Since there isn't a default constructor, this wouldn't compile anyway. Change it to: growVector<char> gv(0,0);
1,729,430
1,729,504
Cross compiler exception handling - Can it be done safely?
I am doing some maintenance on a C++ windows dll library that is required to work with different VC++ compilers (as I don’t want to address different mangling schemes). I have already eliminated any use of the STL in the interface. I have insured that heap corruption will not occur from mixing different new/delete’s. ...
Even considering your additional comment: This will fail whenever MS changes either the compiler's ABI or the class layout of the exception class(es) or even with different compiler settings. In fact, the latter might cause failure even with the same compiler. So I guess the answer is: No you cannot do this safely. If...
1,729,699
1,730,718
How do I correctly use SDL_FreeSurface when dealing with a vector of surfaces
I have setup a small shooter game as a tutorial for myself in SDL. I have a struct of a projectile struct projectile { SDL_Surface* surface; int x; int y; }; And I put that into a vector. vector<projectile> shot; projectile one_shot; And when I press space I create a new projectile and add it to the vecto...
If several projectiles use the same sprite (as in almost all sprite-based games), it's probably better to use an image cache containing all the images used by your games and do memory management only there. Fill it at start or on demand and flush it when exiting. Then projectiles just need to ask to this cache a pointe...
1,729,772
1,731,005
getline vs istream_iterator
Should there be a reason to preffer either getline or istream_iterator if you are doing line by line input from a file(reading the line into a string, for tokenization).
I sometimes (depending on the situation) write a line class so I can use istream_iterator: #include <string> #include <vector> #include <iterator> #include <iostream> #include <algorithm> struct Line { std::string lineData; operator std::string() const { return lineData; } }; std::istream& ope...
1,729,834
1,730,162
What's the purpose of IUnknown member functions in END_COM_MAP?
ATL END_COM_MAP macro is defined as follows: #define END_COM_MAP() \ __if_exists(_GetAttrEntries) {{NULL, (DWORD_PTR)_GetAttrEntries, _ChainAttr }, }\ {NULL, 0, 0}}; return _entries;} \ virtual ULONG STDMETHODCALLTYPE AddRef( void) throw() = 0; \ virtual ULONG STDMETHODCALLTYPE Release( void) throw() = ...
It's been a while since I used ATL but, IIRC, what ends up being instantiated is not CMyClass, but CComObject<CMyClass>. CComObject implements IUnknown and inherits from its template parameter. Edit: The "Fundamentals of ATL COM Objects" page on MSDN nicely illustrates what's going on.
1,730,427
1,734,006
Display message in windows dialogue box using "cout" - C++
Can a windows message box be display using the cout syntax? I also need the command prompt window to be suppressed / hidden. There are ways to call the messagebox function and display text through its usage, but the main constraint here is that cout syntax must be used. cout << "message"; I was thinking of invoking t...
First thing you should take into account is that MessageBox stops the thread until you close the window. If that is the behavior you desire, go ahead. You can create a custom streambuf and set it to std::cout: #include <windows.h> #include <sstream> #include <iostream> namespace { class mb_streambuf : public std::...
1,730,452
1,730,462
Link errors on Snow Leopard
I creating a small desktop application using Qt and Poco on Mac OS X Snow Leopard. Qt works fine, but once I started linking with Poco I get the following warning: ld: warning: in /Developer/SDKs/MacOSX10.6.sdk/usr/local/lib/libPocoFoundation.8.dylib, file is not of required architecture Also when I link against the 1...
Did you pull down the libraries from somewhere? Poco comes with all the source. Recompile it.
1,730,515
1,731,318
How to create a VB6 collection object with ATL
or a VB6 - compatible - collection object. We provide hooks into our .net products through a set of API's. We need to continue to support customers that call our API's from VB6, so we need to continue supporting VB6 collection objects (simple with VBA.Collection in .net). The problem is supporting some sites that use V...
Collections are more or less based on convention. They implement IDispatch and expose some standard methods and properties: Add() - optional Remove() - optional Item() Count - read-only _NewEnum - hidden, read-only, returns pointer to enumerator object that implements IEnumVariant The _NewEnum property is what allows...
1,730,739
1,730,790
Using non-abstract class as base
I need to finish others developer work but problem is that he started in different way... So now I found in situation to use existing code where he chooses to inherit a non-abstract class (very big class, without any virtual functions) that already implements bunch of interfaces or to dismiss that code (which shouldn't...
Although it is very tempting to say write it from scratch again, don't do it! The existing code may be ugly, but it looks like it does work. Since the class is big, I assume there is fair bit of history behind it as well. It might have solutions for some very obscure cases which you might not have imagined till now. ...
1,730,966
1,730,981
C# for UI, c++ for library
I have a numerical library coded in C++. I am going to make a UI for the library. I know some MFC. So one solution is to use MFC and make a native application. The alternative is C#. I know nothing about C#. But I think it should be easy to learn. Some tutorial for mixed programming of C++ and C# would be very helpfu...
I would recommend using Windows Forms or WPF via C# for your GUI. Take your numerical library, and use C++/CLI to make a .NET wrapper for it. This makes it trivial to use from C# (it looks like any other C# library). I highly recommend Nishant Sivakumar's C++/CLI articles on CodeProject for learning about C++/CLI and ...
1,731,226
1,731,444
Optimizing a LAN server for a game
I'm the network programmer on a school game project. We want to have up to 16 players at once on a LAN. I am using the Server-Client model and am creating a new thread per client that joins. However, a lot of CPU time is wasted just checking on each thread if the non-blocking port has received anything from the clie...
You should stop using non-blocking ports. They're really most useful for concurrency, and you have threads for that. Just make each thread in the team wait on the port, and when it unblocks, it'll have something to do so you don't waste time spinning. If you have other things to do (like update game state), do that wit...
1,731,404
1,731,512
Using a non-static class member inside a comparison function
I'm currently developing a syntaxic analyser class that needs, at a point of the code, to sort structs holding info about operators. Each operator has a priority, which is user-defined through public member functions of my analyser class. Thus, when sorting, I need my sorting function to order elements based on the pri...
Use a functor instead of a function: struct op_comp : std::binary_function<op_info, op_info, bool> { op_comp(parser * p) : _parser(p) {} bool operator() (const op_info& o1, const op_info& o2) { return _parser->op_comp(o1, o2); } parser * _parser; }; This way the method op_comp can stay non-...
1,731,675
1,731,691
Boost: what is a "convenience header"?
What is the difference between "header" and "convenience header" in boost?
A convenience header is typically (not just in Boost) a header which includes a number of other headers (that contain actual code) which are commonly used together, even though there are no hard dependencies between them (which is why they're separate in the first place).
1,731,784
1,731,824
Boost: how do we specify "any port" for a TCP server?
How can I specify "pick any available port" for a TCP based server in Boost? And how do I retrieve the port once a connection is accepted? UPDATED: By "available port" I mean: the OS can pick any available port i.e. I do not want to specify a port.
Question 1: Use port number 0 Question 2: Use acceptor.local_endpoint().port()
1,731,838
1,731,871
Magic in placement new?
I'm playing with dynamic memory allocation "by hand" and I wanted to see how placement new is implemented by guys from MS but when debugging I "stepped into" it moved me to code: inline void *__CRTDECL operator new(size_t, void *_Where) _THROW0() { // construct array with placement at _Where return (_Where); } Could...
The purpose of operator new is only to allocate memory for an object, and return the pointer to that memory. When you use placement new, you're essentially telling the compiler "I know this memory is good, skip allocation, and use this pointer for my object." Your object's constructor is then called using the pointer p...
1,731,996
1,743,346
Explicitly calling a destructor in a signal handler
I have a destructor that performs some necessary cleanup (it kills processes). It needs to run even when SIGINT is sent to the program. My code currently looks like: typedef boost::shared_ptr<PidManager> PidManagerPtr void PidManager::handler(int sig) { std::cout << "Caught SIGINT\n"; instance_.~PidManagerPtr(); ...
Turns out that doing this was a very bad idea. The amount of weird stuff going on is tremendous. What was happening The shared_ptr had a use_count of two going into the handler. One reference was in PidManager itself, the other was in the client of PidManager. Calling the destructor of the shared_ptr (~PidManager() ...
1,732,155
1,732,174
Question about the garbage collector in .NET (memory leak)
I guess this is very basic but since I'm learning .NET by myself, I have to ask this question. I'm used to coding in C, where you have to free() everything. In C++/.NET, I have read about the garbage collector. From what I understand, when an instance is no longer used (in the scope of the object), it is freed by the g...
Yeah, the garbage collector is freeing your objects when they're not used anymore. What we usually call a memory leak in .NET is more like: You're using external resources (that are not garbage collected) and forgetting to free them. This is solved usually by implementing the IDisposable interface. You think there are...
1,732,208
1,732,281
What is a safe way to pass an array of arrays to a DLL in C#?
I have an array of arrays that I want to pass into a DLL. I am running into the error "There is no marshaling support for nested arrays." I can pass a single array in fine but if I stack them up it fails. I need/want a "safe" way of passing in the array of arrays. private static extern int PrintStuff(string[][] someStr...
You could convert the double array to a single array (i.e. flatten it). This can be done by keeping width and height variables, and accessing the indices as such: string atXY = someStringsInSingleArray[(y * width) + x]; The array can then be converted as such: string * array = new string[width * height]; for (unsign...
1,732,376
1,732,420
Is nesting namespaces an overkill?
I'm writing a C++ program that has a large number of classes. In my head I can visualise them as distinct collections. For example there's a collection of classes for reading and storing config data, and another collection for drawing a user interface with various widgets. Each of those collections could be neatly stor...
It is not overkill. It is reasonable to nest your namespaces, e.g. piku::gui::screen etc. You could also collapse them to piku_gui_screen, but with the separate, nested namespaces you get the advantage that, if you're inside piku::gui, you can access all names in that namespace easily (e.g. screen will automatically r...
1,732,643
1,735,531
Choosing the right subclass to instantiate programmatically
Ok, the context is some serialization / deserialization code that will parse a byte stream into an 'object' representation that's easier to work with (and vice-versa). Here's a simplified example with a base message class and then depending on a 'type' header, some more data/function are present and we must choose the ...
It's a pretty basic question in fact (as you can imagine, you are definitely not the only one deserializing in C++). What you are looking for is called Virtual Construction. C++ does not define Virtual Construction, but it's easy to approximate it using the Prototype Design Pattern or using a Factory method. I personna...
1,732,717
33,875,437
How to determine how much free space on a drive in Qt?
I'm using Qt and want a platform-independent way of getting the available free disk space. I know in Linux I can use statfs and in Windows I can use GetDiskFreeSpaceEx(). I know boost has a way, boost::filesystem::space(Path const & p). But I don't want those. I'm in Qt and would like to do it in a Qt-friendly way....
I know It's quite old topic but somebody can still find it useful. Since QT 5.4 the QSystemStorageInfo is discontinued, instead there is a new class QStorageInfo that makes the whole task really simple and it's cross-platform. QStorageInfo storage = QStorageInfo::root(); qDebug() << storage.rootPath(); if (storage.isR...
1,732,772
1,732,783
Cocoa WebView cross-thread access
I have a C++ class running in its own thread that needs to execute some javascript in a WebView that's part of a Cocoa app. I have the C++ app call a method in the Cocoa window's controller and it in turns runs the javascript, passing in the data. It seems to work part of the time, but crash a lot of the time as well (...
Maybe [yourWebView performSelectorOnMainThread:...] and friends? (Or call a mediating controller class.)
1,732,821
1,732,886
What are your experiences with Code::Blocks?
I looked at Code::Blocks and it certainly looks great for c++ development, I like it's multiplatform capabilities (runs everywhere), but I wanted to get your feedback. Is it good/stable enough to be used in a professional environment? Thanks.
I have tried Code::Blocks for windows and found below things about - Pros: 1.) Supports and generates code using many compilers - GNU GCC for x86, GCC for ARM, MS-VS2005 compiler, ... many more(See list in Project Build options) 2.) Has decent source code browser with necessary stuff(syntax highlighting based on multi...
1,733,112
1,733,114
What is the reason for the entire C++ STL code to be included in the .h rather than .cpp/.c files?
I just downloaded the STL source code and I noticed all the definition for the STL template classes are included in the .h file. The actual source code for the function definition is in the .h file rather than .cpp/.c file. What is the reason for this? http://www.sgi.com/tech/stl/download.html
Because very few compilers implement linking of templates. It's hard. Here's a brief but (I think) informative article about it: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=53 I say "I think" because it's really not something I'm very familiar with other than that it's widely unimplemented. I initial...
1,733,143
1,733,153
Converting between C++ std::vector and C array without copying
I would like to be able to convert between std::vector and its underlying C array int* without explicitly copying the data. Does std::vector provide access to the underlying C array? I am looking for something like this vector<int> v (4,100) int* pv = v.c_array(); EDIT: Also, is it possible to do the converse, i.e. ...
You can get a pointer to the first element as follows: int* pv = &v[0]; This pointer is only valid as long as the vector is not reallocated. Reallocation happens automatically if you insert more elements than will fit in the vector's remaining capacity (that is, if v.size() + NumberOfNewElements > v.capacity(). You ...
1,733,272
1,736,542
IThumbnailProvider and IInitializeWithItem
I am trying to develop an IThumbnailProvider for use in Windows 7. Since this particular thumbnail would also be dependant on some other files in the same directory, I need to use something other than IInitializeWithStream to a path to work with, this being IInitializeWithItem. (Alternatively, I could use IInitializeWi...
Okay, I finally found out what is the matter. To quote the Building Thumbnail Providers link on the MSDN website: There are cases where initialization with streams is not possible. In scenarios where your thumbnail provider does not implement IInitializeWithStream, it must opt out of running in the isolated process wh...
1,733,484
1,734,057
Unit testing real-time / concurrent software
Possible Duplicate: How should I unit test threaded code? The classical unit testing is basically just putting x in and expecting y out, and automating that process. So it's good for testing anything that doesn't involve time. But then, most of the nontrivial bugs I've come across have had something to do with timin...
Most of the work I do these days involves multi-threaded and/or distributed systems. The majority of bugs involve "happens-before" type errors, where the developer assumes (wrongly) that event A will always happen before event B. But every 1000000th time the program is run, event B happens first, and this causes unpr...
1,733,488
1,733,655
Terrain minimap in OpenGL?
So I have what is essentially a game... There is terrain in this game. I'd like to be able to create a top-down view minimap so that the "player" can see where they are going. I'm doing some shading etc on the terrain so I'd like that to show up in the minimap as well. It seems like I just need to create a second c...
One way to do this is to create an FBO (frame buffer object) with a render buffer attached, render your minimap to it, and then bind the FBO to a texture. You can then map the texture to anything you'd like, generally a quad. You can do this for all sorts of HUD objects. This also means that you don't have to redraw...
1,733,627
1,830,639
Benchmarks for Intel C++ compiler and GCC
I have an AMD Opteron server running CentOS 5. I want to have a compiler for a fairly large C++ Boost based program. Which compiler I should choose?
I hope this helps more than hurts :) I did a little compiler shootout sometime over a year ago, and I am going off memory. GCC 4.2 (Apple) Intel 10 GCC 4.2 (Apple) + LLVM I tested multiple template heavy audio signal processing programs that I'd written. Compilation times: The Intel compiler was by far the slowest co...
1,733,656
1,734,647
Has anyone seen a 2-Sat implementation
I have been looking for a while, but I just can't seem to find any implementation of the 2-Sat algorithm. I am working in c++ with the boost library (which has a strongly connected component module) and need some guidance to either create an efficient 2-Sat program or find an existing library for me to utilise through ...
I suppose you know how to model a 2-Sat problem to solve it with SCC. The way I handle vars and its negation isn't very elegant, but allows a short implementation: Given n variables numbered from 0 to n-1, in the clauses -i means the negation of variable i, and in the graph i+n means the same (am I clear ?) #include <b...
1,733,857
23,632,871
How to set the padding of QTableView cells through CSS?
Is it possible to define the padding of QTableView cells? I would expect this to be possible using CSS stylesheets, but the documentation does not describe a method to do this. The following stylesheet does not have the desired effect: QTableView { padding: 5px; } as it influences the padding property of the widget ...
I know this is an old question but I've been struggling with this recently. I found out that by setting tableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); the padding set in your CSS will then be applied to the top and bottom of the cell, too!
1,734,026
1,734,050
Do types in QT applications for different platforms have similar size?
I created an application for Windows in C++ using QT. If I want to port it to Linux or Mac OS, will sizeof(int) or sizeof(long) change? In other words, do types in QT applications for different platforms have similar size?
In addition to stefaanv's answer, if you're worried about their size, use quint32 and friends. Qt guarantees them to be the same size on all supported platforms. Check out QtGlobal: The header file declares several type definitions that guarantee a specified bit-size on all platforms supported by Qt for various basic...
1,734,059
1,734,111
How do I set the icon for my program in Visual C++ 2008 Express Edition?
I want to set the embedded icon for my executable console program to a custom icon. I know this is pretty much the same question as this one here, but I'm using Visual C++ 2008 Express Edition, and the Resources View is not available (and the Project-context-menu->Add->Resource... is grayed out), so I'm at loss here. W...
You can still add a resource in Express edition, but there is no resource editor GUI, you have to create the resource yourself using external tools. The Win32 Platform SDK has a resource compiler (rc.exe) that will compile a resource script which is just a text file that you can write yourself. There are also free res...
1,734,522
1,734,542
Looking for a Java Graphics alternative
Any time I embark on a project that requires some rendering of primitive shapes and lines, I usually turn to Java because it's just so easy. For my latest project, I decided I might like to learn another API similar to but not Java Graphics2D. I would preferably like something that will work with C++ on Linux. Does ...
Anti-Grain geometry gives high quality 2D rendering from path and font primitives, is a good example of idiomatic use of templates in C++, and looks fantastic. It has more documentation on the algorithms than on the API, so be prepared to look at the examples for how to use it. It requires some OS specific code to tak...
1,734,556
1,734,600
C++ generic classes & inheritance
I'm new to generic class programming so maybe my question is silly - sorry for that. I'd like to know whether the following thing is possible and - if so, how to do it I have a simple generic class Provider, which provides values of the generic type: template <class A_Type> class Provider{ public: A_Type getValue(); ...
C++ has templates (class templates and function templates), not generics. Given this declaration: template <class A_Type> class ISubProvider; you can't do this: class IntegerProvider : public ISubProvider{ int getValue(){return 123;} }; because ISubProvider is not a class, it's a class template. You can though, d...
1,734,628
1,734,640
Copy constructor and = operator overload in C++: is a common function possible?
Since a copy constructor MyClass(const MyClass&); and an = operator overload MyClass& operator = (const MyClass&); have pretty much the same code, the same parameter, and only differ on the return, is it possible to have a common function for them both to use?
Yes. There are two common options. One - which is generally discouraged - is to call the operator= from the copy constructor explicitly: MyClass(const MyClass& other) { operator=(other); } However, providing a good operator= is a challenge when it comes to dealing with the old state and issues arising from self as...
1,734,893
1,734,905
Overloading a method in a subclass in C++
Suppose I have some code like this: class Base { public: virtual int Foo(int) = 0; }; class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0; }; class Concrete : public Derived { public: double Foo(double); }; If I have a object of type Concre...
Name lookup happens before overload resolution, so once Foo has been found in Concrete, base classes won't be search for other methods called Foo. int Foo(int) in Derived is hidden by the Foo in Concrete. You have a number of options. Change the call to be explicit. concrete.Derived::Foo(an_int); Add a using declarati...
1,734,927
1,734,961
Compare characters at the end of the string C++
This program supposed to find command line arguments entered on Unix which ends with “.exe”. For some reason it doesn't work. Here is the code: int main( int argc, char* argv[] ) { for ( int i = 1; i < argc; i++) if( findExe( argv[i] ) ) cout << argv[i] << endl; return 0; } bool findExe( char* arg...
Remove the else, I think (although I haven't compiled the code to check). In the case where the length is at least 4, but the string comparison returns non-zero, you reach the end of the function without returning. Your compiler should have warned you: turn on more warnings.
1,735,038
1,735,101
Why "not all control paths return a value" is warning and not an error?
I was trying to answer this question. As suggested by the accepted answer, the problem with that code is that not all control paths are returning a value. I tried this code on the VC9 compiler and it gave me a warning about the same. My question is why is just a warning and not an error? Also, in case the path which do...
Failing to return a value from a function that has a non-void return type results in undefined behaviour, but is not a semantic error. The reason for this, as far as I can determine, is largely historical. C originally didn't have void and implicit int meant that most functions returned an int unless explicitly declare...
1,735,085
1,735,116
C vs C++ (Objective-C vs Objective-C++) for iPhone
I would like to create a portable library for iPhone, that also could be used for other platforms. My question is the fallowing: Does anyone knows what is the best to be used on the iPhone: Objective-C or Objective-C++? Does it works with C++ the same way as Objective-C with C or not? Reasons: Objective-C is a superset...
They're not really different languages. Objective-C++ is just Objective-C with slightly limited support for including C++ code. Objective-C is the standard dialect, but if you need to work with C++, there's no reason not to use it. AFAIK, the biggest practical difference (aside from allowing use of different libraries)...
1,735,102
1,735,141
error C2664 + generic classes + /Wp64
I've got the following lines of code: p_diffuse = ShaderProperty<Vector4>(Vector4(1,1,1,1)); addProperty(&p_diffuse, "diffuse"); p_shininess = ShaderProperty<float>(10.0f); addProperty(&p_shininess, "shininess"); the addProperty function is implemented as follows: template <class A_Type> void IShader<A_Type>::addPro...
float != Vector4. Your whole class (IShader), is templated on A_Type, not just the addProperty method. /Wp64 has nothing to do with anything. The solution to this problem will need more context, you may want to define addProperty to be a template member function instead of IShader (or in addition to) being templated. A...
1,735,138
1,735,147
Copying a class that inherits from a class with pure virtual methods?
I've not used C++ in a while, and I've become far too comfortable with the ease-of-use of real languages. At any rate, I'm attempting to implement the Command pattern, and I need to map a number of command object implementations to string keys. I have an STL map of string to Command, and I'd like to copy the Command. E...
One way to do it would be to have add this to your Command class: public: virtual Command * Clone() const = 0; ... and then in the various subclasses of Command, implement Clone() to return a copy of the object: public: virtual Command * Clone() const {return new MyCommandSubclass(*this);} Once that's done, you...
1,735,179
1,735,195
Why would a blocking socket repeatedly return 0-length data?
I'm having a significant problem using a standard BSD-style socket in a C++ program. In the code below, I connect to a local web server, send a request, and simply create a loop waiting for data to return. I actually do receive the data, but then I get an endless stream of 0-length data as if it was a non-blocking sock...
From the man page of recv For TCP sockets, the return value 0 means the peer has closed its half side of the connection.
1,735,225
1,735,549
C++ print out limit number of words
I'm beginner to C++ and I wonder how to do this. I want to write a code which take in a text line. E.g. "Hello stackoverflow is a really good site" From the output I want only to print out the first three words and skip the rest. Output I want: "Hello stackoverflow is" If it was Java I would've used the string split()...
The operator >> breaks a stream into words. But does not detect end of line. What you can do is read a line then get the first three words from that line: #include <string> #include <iostream> #include <sstream> int main() { std::string line; // Read a line. // If it succeeds then loop is entered. So this ...
1,735,229
1,735,247
c++ overload < using a friend function in C++ for multiple classes?
i am experimenting with overloading the < operator (i'll add the > later) as a means for checking if one of the goldfish (please see code below) is within the territory of another (the territories can overlap). im getting multiple compile errors with teh code - primarily to do with being able to access the private vari...
I haven't checked the logic of your program, but there are some simple notes. I commented the additions: class territory; // declare the class used in operator< class point { private: float x; float y; public: point(float x_in, float y_in) { x = x_in; y = y_in; } float getx() { re...
1,735,324
1,735,343
Is there a linked list predefined library in C++?
Is there a linked list in C++ that I could just #include? Or do I need to create my own if I want to use one?
As daniel notes, yes, std::list. Usage would be: #include <list> // ... std::list<int> listOfInts; listOfInts.push_back(1); // ... And so on. You can find a complete list of STL classes here. The section you're after is 3.2, Container classes. Another useful reference of the C++ Standard Library is here.
1,735,539
1,735,649
GDB debugger problems - No source file named
For some reason I can't get gdb to recognize the files in my project when debugging. I've tried a variety of things, including downloading different version, etc. and the last thing I did was completely overwrite all of MingW with Twilight Dragon Media's Bundle Package. Does anyone know how to solve this issue? The odd...
GDB locates source files by file path/name from the object module debug information. So if you moved your sources you should rebuild your project. This can also happen if you are running on a different host which has no visibility to your source at all. The most important thing to remember is: Debug information doesn'...
1,735,576
1,735,587
Are there any major differences between Visual C++ and C++
I want to make win32 apps and games. Is there any major differences between C++ and Visual C++? What should I use.
Visual C++ is the IDE, C++ the language... Use the language you want, there is no best language... I would go for the .NET platform if you start something new, there you can use any language that targets the platform (Managed C++, C#, VB.NET, J# ...) and interoperability with native code is great + support for DirectX ...
1,735,640
1,735,701
Some memory seems to be left allocated after malloc() and free()
I am new to C. I am trying to get comfortable with malloc + free. I have coded following test but for some reason the memory isn't freed completely (top still indicates about 150MB of memory allocated to process). Why is that? #include <stdio.h> #include <malloc.h> typedef struct { char *inner; } structure; int m...
top will tell you the amount of physical memory assigned to your process. Virtual memory is an abstraction on top of physical memory, and malloc/free provide an abstraction on top of that. malloc reserves space from the heap of your program. The heap is simply an area your program's virtual address space used for temp...
1,735,796
1,735,816
Is it possible to choose a C++ generic type parameter at runtime?
Is there a way to choose the generic type of a class at runtime or is this a compile-time thing in C++? What I want to do is something like this (pseudocode): Generictype type; if(somveval==1) type = Integer; if(someval==2) type = String; list<type> myList; Is this possible in C++? and if yes, how?
It's a compile time thing. Template parameter types must be known to the compiler at compile-time. That being, said, using certain template meta-programming techniques, you can choose one type or another AT compile-time, but only if all possible types are known at compile-time, and only if the condition for selecting ...
1,735,841
1,735,910
Initializing a ublas vector from a C array
I am writing a Matlab extension using the C++ ublas library, and I would like to be able to initialize my ublas vectors from the C arrays passed by the Matlab interpeter. How can I initialize the ublas vector from a C array without (for the sake of efficiency) explicitly copying the data. I am looking for something alo...
Both std::vector and ublas::vector are containers. The whole point of containers is to manage the storage and lifetimes of their contained objects. This is why when you initialize them they must copy values into storage that they own. C arrays are areas of memory fixed in size and location so by their nature you can on...
1,735,865
1,735,880
C++ Constructor and Destructor
I'm getting some errors when compiling my program. They relate to the constructor and destructor of my class Instruction. Errors are: /tmp/ccSWO7VW.o: In function `Instruction::Instruction(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)': ale.c:(.text+0x241): undefined reference to `vtable ...
I would guess the problem is due to you declaring a virtual method 'execute' in the Instruction class, and never defining it anywhere. Compilers have to produce a vtable object for a class with virtual methods and really only want one copy of it, so they usually just do it in the compilation unit (source file) that de...
1,735,938
1,735,967
Problems with deltaTicks combined with high speed in a game loop
My game uses a d = vt calculation for movement of objects where t is the time since the last frame (one frame per loop). I'm using SDL and the gist of the timing calculation is that I create an instance of a Timer class and start it. I call GetSeconds() when it's needed which returns the difference between when the ti...
If you're running at 60Hz, then each frame should be roughly 16ms. Sounds like you have disabled vertical sync?
1,736,017
1,736,052
Getting Union, Intersection, or Difference of Sets in C++
I have a couple questions about how to use C++ sets (std::set) Is there a way to get the union, intersection, or difference of two C++ sets? (It's pretty easy to write my own functionto do that but I wanted to know if there was a built in function for it) Can C++ sets be used as keys in a map?
Use the set_difference(), set_union(), set_intersection() and set_symmetric_difference() functions. Sets and maps support any key type that can compare. By default this means the type has operator<() defined, but you can provide your own comparator. C++ sets don't have operator<() defined and therefore can't be used a...
1,736,056
1,736,069
How can you cast between wchar_t* and an int?
I have a function which returns the inner text of an xml element. It returns it, however, as a const wchar_t*. I wish to return this value as an integer (And a float in some other cases). What is the best method for doing so?
The C++ way would be: wchar_t* foo = L"123"; std::wistringstream s(foo); int i = 0; s >> i; With Boost, you could do: try { int i2 = boost::lexical_cast<int>(foo); } catch (boost::bad_lexical_cast const&) { ... } Depending on which CRT implementation you're using you may have "wide" atoi/strtol functions: int...
1,736,080
1,736,086
C++ cout cin string manipulation
I'm trying to get a line as input from the command line. My problem is that I'm not getting the whole line, but it's being tokenized by space. So if I entered something such as "I like Math a lot" instead of getting "you enterend: I like Math a lot" I get the follwoing: EDITING MODE: Enter a command i like Math a lot...
std::getline is the standard way to read a line of input at a time. You can use it like this: std::getline(std::cin, string); It returns a reference to the input stream which has an implicit conversion to void* so you can check for success easily like this: if (std::getline(std::cin, string)) { // successfully rea...
1,736,199
1,736,203
Assigning to pointer immediately after deleting
I was wondering if it is safe to do this... delete p_pointer; p_pointer = p_otherPointer; Rather than... delete p_pointer; p_pointer = 0; p_pointer = p_otherPointer; I would assume so since there aren't any new memory allocations between the deletion and assignment, but I just want to make sure.
Yes it is safe. It's useless to set the deleted pointer to NULL if you're about to reassign it anyway. The reason people set deleted pointers to NULL is so they can "mark" it as deleted, so later they can check if it has already been deleted.
1,736,267
1,736,309
C++ cout printing slowly
I noticed if I print out a long string(char*) using cout it seems to print 1 character at a time to the screen in Windows 7, Vista, and Linux(using putty) using Visual C++ 2008 on Windows and G++ on Linux. Printf is so much faster I actually switched from cout to printf for most printing in a project of mine. This is c...
NOTE: This experimental result is valid for MSVC. In some other implementation of library, the result will vary. printf could be (much) faster than cout. Although printf parses the format string in runtime, it requires much less function calls and actually needs small number of instruction to do a same job, comparing t...
1,736,295
1,736,359
C++ logging framework suggestions
I'm looking for a C++ logging framework with the following features: logs have a severity (info, warning, error, critical, etc) logs are tagged with a module name framework has a UI (or CLI) to configure for which modules we will actually log to file, and the minimum severity required for a log to be written to file. ...
Not sure about the configuration from a UI or CLI. I've used both of these logging frameworks at one point or other. https://sourceforge.net/projects/log4cplus/ https://logging.apache.org/log4cxx/index.html It wouldn't be too hard to drive your logging based on a configuration file that could be editable by hand or thr...
1,736,304
1,939,807
How to write bitmaps as frames to Ogg Theora in C\C++?
How to write bitmaps as frames to Ogg Theora in C\C++? Some Examples with source would be grate!)
Here's the libtheora API and example code. Here's a micro howto that shows how to use the theora binaries. As the encoder reads raw, uncompressed 'yuv4mpeg' data for video you could use that from your app, too by piping the video frames to the encoder.
1,736,403
1,736,414
Wait for a detached thread to finish in C++
How can I wait for a detached thread to finish in C++? I don't care about an exit status, I just want to know whether or not the thread has finished. I'm trying to provide a synchronous wrapper around an asynchronous thirdarty tool. The problem is a weird race condition crash involving a callback. The progression is:...
Yes, I believe that what you're describing is happening (race condition on deallocate). One quick way to fix this is to create a static instance of Wait, one that won't get destroyed. This will work as long as you don't need to have more than one waiter at the same time. You will also permanently use that memory, it wi...
1,736,458
1,736,477
Help un-noobify my C++ homework
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int twoify(int num, int times) { num *= 2; if (times > 0) { times--; return twoify(num, times); } return num; } int main() { srand(time(NULL)); const int BET = 1; const int TIMES = 100000; ...
First, avoid the useless recursion, turn it into iteration: int twoify(int num, int times) { do { num *= 2; --times; } while (times >= 0); return num; } But, you can do better (if times > 0 is guaranteed, which would also simplify the version above by allowing you to use a while instead of the ...
1,736,480
1,736,524
C++ new operator. Creating a new instance
I'm having some trouble creating an object in C++. I create a class called Instruction, and I am trying to create a new instance, but I get compiler errors. Class code: class Instruction{ protected: string name; int value; public: Instruction(string _name, int _value); ~Instruction(); void set...
inst is a pointer to an Instruction object and instList is a list of Instruction objects. So when you try instList.push_back(inst) it doesn't work (it expects a real object not the pointer to it). You should instead have instList.push_back(*inst).
1,736,502
1,736,505
Compile C++ in Eclipse?
How can I compile C++ .cpp files in the Eclipse IDE. I have CDT installed but when I try to execute it, I get a "Launch Failed. Binary not found." I do not want to install CYGWIN unless it is absolutely necessary.
The CDT only provides you with the facilities in Eclipse to edit and understand C files. It does not, to my knowledge, incorporate a compiler (unlike the JDT). You need to install and configure a C compiler that the CDT can use. If you're on Linux, you'll probably already have gcc installed that you can use. The only t...
1,736,620
1,736,781
SDL_Event.type always empty after polling
I have a general function that is supposed to handle any event in the SDL event queue. So far, the function looks like this: int eventhandler(void* args){ cout << "Eventhandler started.\n"; while (!quit){ while (SDL_PollEvent(&event)){ cout << "Got event to handle: " << event.type << "\n"; switch (e...
That nothing happens is a result of the missing case in front of SDL_KEYDOWN. With case missing the compiler sees a jump label which you would use for e.g. goto SDL_KEYDOWN;, which results in the default label being the only label in the switch statement. I don't see why event.type doesn't get output though unless you ...
1,736,654
1,736,711
Macros as arguments to preprocessor directives
Being faced with the question whether it's possible to choose #includes in the preprocessor I immediately thought not possible. .. Only to later find out that it is indeed possible and you only need to watch out for argument expansions (which e.g. Boost.Preprocessor can take care of). While I'd avoid actually doing tha...
From § 16.2-4 ("Source file inclusion") of C++ 2003 draft: A preprocessing directive of the form # include pp-tokens new-line (that does not match one of the two previous forms) is permitted. The preprocessing tokens after include in the directive are processed just as in normal text (each identifier currently defi...
1,736,745
1,736,750
C++ Class Inheritance problem
Hi I have two classes, one called Instruction, one called LDI which inherits from instruction class. class Instruction{ protected: string name; int value; public: Instruction(string _name, int _value){ //constructor name = _name; value = _value; } ~Instruction(){} Instructi...
The code: new LDI(name, val) specifically says "Call the LDI constructor with a name and val." There is no LDI constructor that takes name / val. In fact, I don't see a constructor for LDI at all. If you want to use the constructor of a base-class, here is how: public LDI(string _name, int _value) // Public constructor...
1,736,833
1,736,841
void pointers: difference between C and C++
I'm trying to understand the differences between C and C++ with regards to void pointers. the following compiles in C but not C++ (all compilations done with gcc/g++ -ansi -pedantic -Wall): int* p = malloc(sizeof(int)); Because malloc returns void*, which C++ doesn't allow to assign to int* while C does allow that. Ho...
In C, pointer conversions to and from void* were always implicit. In C++, conversions from T* to void* are implicit, but void* to anything else requires a cast.
1,736,919
1,736,932
<list> retreving items problem with iterator
I have a list of type Instruction*. Instruction is a class that I made. This class has a function called execute(). I create a list of Instruction* list<Instruction*> instList; I create an Instruction* Instruction* instPtr; instPtr = new Instruction("test",10); If I call instPtr.execute(); the function will be exec...
p is an iterator of Instruction * pointers. You can think of it as if it were of type Instruction **. You need to double dereference p like so: (*p)->execute(); *p will evaluate to an Instruction *, and further applying the -> operator on that will dereference the pointer.
1,737,111
1,737,622
C++ Debug Problem - pdb file
I have several DLLs in my project that are defined to create their *.pdb file (debug info) inside the same folder. The problem is that the only *.pdb file that actually exist inside this folder is the one that belongs to the last compiled DLL. As a result I can debug only the last project (each compilation deletes all ...
Or you can create separate folder for program releases, and always compile and execute your program from the newest release-folder. This way you can also manage all other external files like images and what not.