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
423,335
423,580
What can C++ do that is too hard or messy in any other language?
I still feel C++ offers some things that can't be beaten. It's not my intention to start a flame war here, please, if you have strong opinions about not liking C++ don't vent them here. I'm interested in hearing from C++ gurus about why they stick with it. I'm particularly interested in aspects of C++ that are little...
I have stayed with C++ as it is still the highest performing general purpose language for applications that need to combine efficiency and complexity. As an example, I write real time surface modelling software for hand-held devices for the surveying industry. Given the limited resources, Java, C#, etc... just don't ...
423,730
450,293
How to pass a COM method as a function argument? And Microsoft Compiler error C3867
I would like to pass a COM method as a function argument but I get this error (Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86): error C3867: 'IDispatch::GetTypeInfoCount': function call missing argument list; use '&IDispatch::GetTypeInfoCount' to create a pointer to member What am I mis...
As morechilli pointed out this is a C++ issue. Here it is the solution, thanks to my colleague Daniele: #include <atlbase.h> template < typename interface_t > void update( interface_t* p, HRESULT (__stdcall interface_t::*com_uint_getter)(UINT*), UINT& u ) { UINT tmp; if ( S_OK == (p->*com_uint_getter)( &tmp ) )...
423,961
424,115
easy way to add 1 month to a time_t in C/C++
I have some code that uses the Oracle function add_months to increment a Date by X number of months. I now need to re-implement the same logic in a C / C++ function. For reasons I don't want/need to go into I can't simply issue a query to oracle to get the new date. Does anyone know of a simple and reliable way of add...
Method AddMonths_OracleStyle does what you need. Perhaps you would want to replace IsLeapYear and GetDaysInMonth to some librarian methods. #include <ctime> #include <assert.h> bool IsLeapYear(int year) { if (year % 4 != 0) return false; if (year % 400 == 0) return true; if (year % 100 == 0) return false;...
424,031
443,104
Symbian C++ - Use a TTF font in your application?
Is it possible to package a .TTF file in your application and use it to render text at runtime, and have the application release the font after use? I've found bits of information scattered around the forum, but nothing conclusive. Can anyone offer any advice?
The accepted answer above is wrong. You can use TTF in symbian without converting it into GRD. I did it two years back on older versions of Symbian (probably 8). Newer versions probably have built in support. In any case serch the net for a truetype font file driver for symbian (a .dll) file. Install it and you can us...
424,104
424,990
Can I access private members from outside the class without using friends?
Disclaimer Yes, I am fully aware that what I am asking about is totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot. I'm mainly looking to see if can be done. Now that that's out of the way, is there any way to access private class members in C++ from outsid...
If the class contains any template member functions you can specialize that member function to suit your needs. Even if the original developer didn't think of it. safe.h class safe { int money; public: safe() : money(1000000) { } template <typename T> void backdoor() { // Do s...
424,105
424,136
What kind of code library should I build for distribution?
I need to build a C++ library to distribute among our customers. The library must be able to be accessed from a wide range of languages including VB6, C++, VB.net and C#. I've being using ActiveX controls (ocx files) until now. But I wonder if there is a better kind of library (dll, etc.) that I can build. What do you ...
Almost every language has a way of loading dynamic libraries and accessing exported C functions from them. There is nothing preventing you from using C++ inside the dll but for maximum portability, export only C functions. I have some more about this in this post.
424,503
424,621
How do I open a new document in running application without opening a new instance of the application?
I have a situation that has been partially covered by other answers at SO, but I cannot find a complete answer. In short, we are trying to use URL's for our specific data types that when double clicked will open up our application and load those data sets into that app. We have this part working. (for example, an URL...
Create a named mutex when application launches as David Grant said, then before displaying the UI for the second URL, check for this mutex, if it is already created then just quit by passing the new URL to the first launched application (Have interface in the application to set the URL and tell to redirect programatica...
424,549
424,653
Difference between C/C++ Runtime Library and C/C++ Standard Library
Can you guys tell me the difference between them? By the way, is there something called C++ library or C library?
The C++ Standard Library and C Standard Library are the libraries that the C++ and C Standard define that is provided to C++ and C programs to use. That's a common meaning of those words, i haven't ever seen another definition of it, and C++ itself defines it as this: The C++ Standard Library provides an extensible fr...
425,400
425,436
C++ DLL: Not exposing the entire class
How can I "hide" parts of a class so that whoever is using the libary does not have to include headers for all the types used in my class. Ie take the MainWindow class below, ho can I have it so when compiled in a static/dynamic libary, whoever is useing the libary does NOT have to include windows.h, ie HWND, CRITICAL_...
You can hide parts of a class using the so-called "cheshire cat", "letter/envelope", or "pimpl" technique (which are, all, different names for the same technique): class MainWindow { private: //opaque data class ImplementationDetails; ImplementationDetails* m_data; public: ... declare your public method...
425,430
425,456
How do you return a vector iterator from a variable in a templated class?
I'm trying to return an iterator for a vector in a templated class (I'm not sure if that makes a difference, but I've read that may, so I thought I'd mention it). The problem is that I get an error about C++ not supporting default-int when I try this. I've looked online and from what I can see in forums and explanaio...
Also remember to use typename when declaring the template-dependent return type: typename vector< shared_ptr< vector< T > > >::iterator GetRowIterator(); and the method definition typename vector< shared_ptr< vector< T > > >::const_iterator Table<T>::GetRowIterator() { return data.begin(); } Notice also that when d...
425,457
425,615
Inheriting from a non-templated class that has a templated constructor - how to resolve ambiguity?
Let's say we have a class, MyParent: class MyParent { public: template<namespace T> MyParent() { T* Something; } }; And a derived class, which uses this constructor: class MyDerived : public MyParent { public: MyDerived() : MyParent<int>() { } }; Then I get a compiling error, because there's ambig...
It is not possible. From the standard section 14.8.1 Explicit template argument, it notes: [Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name...
425,576
425,715
Template instantiation with VARIANT return type
An explicit instantiation of a static template member function keeps failing to compile with the message error C2785: 'at_Intermediate CUtil::convert_variant(const VARIANT &)' and '<Unknown>' have different return types When I make a corresponding class with non-static member functions, the compiler likes me. // util...
Apparently you may only use explicit template specialization at namespace scope although I can't find this in the standard (but GCC says as much). The following works for me (on GCC): struct CUtil { template< typename at_Intermediate > static at_Intermediate convert_variant( const VARIANT &v ) ; }; template<> VARI...
425,891
426,214
Is it possible to manage C++ application via JMX?
We have a distributed application containing C++ and Java modules, interacting via CORBA. Are there any C++ libraries/tools for exposing "variables" and "methods" to JMX tools (to create unified management) ?
So even though your application is C++ and Java, you're only looking to expose C++ module attributes to the JMX manager ? If so, or actually, even if you are exposing both, I would look at using an SNMP library for both instances, since trying to get C++ to support JMX directly could be hairy. JMX and SNMP are broadly ...
425,987
426,000
How to prevent memory leaks while cancelling an operation in a worker thread?
Currently i am working on a desktop application which consists mathematical analysiss.I am using qt for GUI and project written in c++. When user starts an analysis, i open a worker thread and start a progress bar.Everything is ok up to now, problem starts when user cancels operation.Operation is complex, i am using se...
A pretty common way to close down worker threads, is to mark it with a flag, and let the worker thread inspect this flag at regular intervals. If marked, it should discontinue its workflow, clean up and exit. Is that a possibility in your situation?
426,162
426,592
Is Polymorphism worth an increase in coupling?
I'm writing a simplistic game to learn get some more C++ experience, and I have an idea where I feel polymorphism almost works, but doesn't. In this game, the Party moves fairly linearly through a Map, but can occasionally encounter a Fork in the road. A fork is (basically) an std::vector<location*>.Originally I was go...
All problems can be solved by adding a level of indirection. I would use your suggested variant, and decouple Location from Party by allowing getNext to accept an object that resolves directional choices. Here is an example (untested): class Location; class IDirectionChooser { public: virtual bool ShouldIGoThisWay(...
426,736
426,767
Error: macro names must be identifiers using #ifdef 0
I have the source code of an application written in C++ and I just want to comment something using: #ifdef 0 ... #endif And I get this error error: macro names must be identifiers Why is this happening?
The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit: identifier: identifier-nondigit identifier identifier-nondigit identifier digit identifier-nondigit: nondigit universal-character-nam...
426,737
426,768
Does this type of memory get allocated on the heap or the stack?
In the context of C++ (not that it matters): class Foo{ private: int x[100]; public: Foo(); } What I've learnt tells me that if you create an instance of Foo like so: Foo bar = new Foo(); Then the array x is allocated on the heap, but if you created an instance of Foo like so: Foo bar; Then i...
Given a slight modification of your example: class Foo{ private: int x[100]; int *y; public: Foo() { y = new int[100]; } ~Foo() { delete[] y; } } Example 1: Foo *bar = new Foo(); x and y are on the heap: sizeof(Foo*) is ...
427,266
427,279
Why does std::auto_ptr operator = trash objects?
Seem to be having an issue with std::auto_ptr and assignment, such that the object referenced seems to get trashed for some reason. std::auto_ptr<AClass> someVar = new AClass(); // should work, but mangles content std::auto_ptr<AClass> someVar( new AClass() ); // works fine. std::auto_ptr<AClass> someVar = std::auto_p...
The first line: std::auto_ptr<AClass> someVar = new AClass(); // should work, but mangles content should result in a compiler error. Because there is no implicit conversion from the raw AClass pointer to an auto_ptr (the constructor for an auto_ptr that takes a raw pointer is marked explicit), initialization using th...
427,289
427,310
Access a COM Interface method C++
Both: CLSID IID Having specified the above, and using: CoCreateInstance() To returning a single uninitialised object of the class specified by the CLSID above. How can I then access an Interface's method from C++? Without: ATL MFC Just plain C++ Afterwards, I use CreateInstance() I'm having trouble, using CreateIns...
By doing a CoCreateInstance you get an interface pointer. Through QueryInterface(...) method you can get the interface pointer of some other interface easily. e.g., IUnknown* pUnk = NULL; HRESULT hr = ::CoCreateInstance(clsid,NULL,CLSCTX_ALL,__uuidof(IUnknown),(void**)&pUnk); IS8Simulation* pSim = NULL; hr = pUnk->...
427,329
428,796
Reading from 2 sockets in 2 threads causes data loss
I have a multi-threaded Windows C++ app written in Visual Studio 6. Within the app 2 threads are running each trying to read UDP packets on different ports. If I protect the reading from the socket with a critical section then all the date read is fine. Without that protection data is lost from both sockets. Is readi...
Within the app 2 threads are running each trying to read UDP packets on different ports. How much UDP data are you sending/reading? How fast are you sending it? How much of your data is lost? This could be a race condition... Not between the two threads, but between the thread and the socket! I've seen problems in t...
427,589
427,633
Inspecting standard container (std::map) contents with gdb
Supposing to have something like this: #include <map> int main(){ std::map<int,int> m; m[1] = 2; m[2] = 4; return 0; } I would like to be able to inspect the contents of the map running the program from gdb. If I try using the subscript operator I get: (gdb) p m[1] Attempt to take address of value no...
I think there isn't, at least not if your source is optimized etc. However, there are some macros for gdb that can inspect STL containers for you: http://sourceware.org/ml/gdb/2008-02/msg00064.html However, I don't use this, so YMMV
427,678
427,936
Design of a polling event API
Say you were designing a C++ windowing library. It may or may not provide a callback API, but needs to provide a polling API to facilitate a functional style of programming. What would the polling API look like? Some options SDL style struct Event { enum { MousePress, KeyPress } type; union { struct { P...
To answer your question quickly, I prefer the simplicity of the "SDL-style code". Mainly because your slightly more complicated "State Style" wastes memory and buys you absolutely nothing (see below), and the recursion in your tortured "Functional pseudo-C++" style will overflow the stack within a few milliseconds. "S...
427,693
429,395
How to use a program which is not in the source code's folder?
For example: I'm on MS DOS, I have a source code in the folder C:\Documents and Settings\Programs. Can i make my source code use a program (for example gnuplot) that is in a random folder?
Here are some options: Search in the system PATH for the executable you want to run Allow the user to specify the location on the command-line Store the location in a configuration file, and allow the user to specify it during install (if you have an install process) or by editing the file by hand Ideally you'd do al...
427,761
427,797
Variable sized class - C++
I've seen a class which is a class which is defined like this.. class StringChild : public StringBase { public: //some non-virtual functions static StringChild* CreateMe(int size); private: unsigned char iBuf[1]; }; The static factory function has the following implementation.. return new(malloc(__...
It's an old C trick that was used to work around the non-availablity of variable length arrays in plain C. Yes, it also works in C++ as long as you use suitable allocator constructs (like allocating a bunch of raw memory the desired size and then placement newing the object in there). It's safe as long as you don't wan...
427,927
439,121
C++ Library to Convert HTML to PDF?
I am looking for a C/C++ library to convert HTML (Actually XHTML + CSS) documents to PDF. It is for commercial use and source would be nice but not essential. Anybody have any recommendations or experience doing this? UPDATE: To clarify, I am targeting the Windows platform only. I am developing with Borland C++ Builder...
Just to bump this, I have evaluated both VisPDF and PDFDoc Scout and will probably go with PDFDoc Scout as it can format HTML input. Thanks for everybody else's input.
428,013
428,117
Regex Replacing &#58; to ":" etc
I've got a bunch of strings like: "Hello, here's a test colon&#58;. Here's a test semi-colon&#59;" I would like to replace that with "Hello, here's a test colon:. Here's a test semi-colon;" And so on for all printable ASCII values. At present I'm using boost::regex_search to match &#(\d+);, building up a string as I ...
The big advantage of using a regex is to deal with the tricky cases like &#38;#38; Entity replacement isn't iterative, it's a single step. The regex is also going to be fairly efficient: the two lead characters are fixed, so it will quickly skip anything not starting with &#. Finally, the regex solution is one without ...
428,153
428,179
How do I call a C++ static library from Perl?
I'm writing a C++ static library that needs to be shared among several applications, one of them written in Perl. Unfortunately, I only barely know the core Perl language (I read the Llama book), and I'm not all that familiar with its libraries. How do you make calls to an external C++ binary from a Perl script? By G...
You want to look at using XS, which is how Perl normally interfaces with C/C++ libraries. It's not quite trivial. A couple of relevant portions of the Perl documentation: perlxs perlxstut
428,553
530,860
Unable to get hudson to parse JUnit test output XML
EDIT: This issue has been fixed by google in gtest 1.4.0; see the original bug report for more information. I've recently switched to gtest for my C++ testing framework, and one great feature of it which I am presently unable to use is the ability to generate JUnit-style XML test reports, which could then be read in by...
Edit: Google test has fixed this issue, which is included in the gtest 1.4.0 release. See the original bug report for more info. Bah! I've finally found the cause of this problem -- it's because gtest produces one giant XML file for all test results, and hudson expects one XML test report per class. I've written a p...
428,630
428,674
Assigning cout to a variable name
In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like: ofstream outFile; if (outFileRequested) outFile.open("foo.txt", ios::out); else outFile = cout; // Wi...
Use a reference. Note that the reference must be of type std::ostream, not std::ofstream, since std::cout is an std::ostream, so you must use the least common denominator. std::ofstream realOutFile; if(outFileRequested) realOutFile.open("foo.txt", std::ios::out); std::ostream & outFile = (outFileRequested ? real...
429,125
429,236
Override and overload in C++
Yes, I do understand the difference between them. What I want to know is: why OVERRIDE a method? What is the good in doing it? In case of overload: the only advantage is you haven't to think in different names to functions?
Overloading generally means that you have two or more functions in the same scope having the same name. The function that better matches the arguments when a call is made wins and is called. Important to note, as opposed to calling a virtual function, is that the function that's called is selected at compile time. It a...
429,322
429,884
Unresolved external symbol CompleteAuthToken referenced
While porting a desktop application to windows mobile I've reached the following error: Error LNK2019: unresolved external symbol CompleteAuthToken referenced in function Reading MSDN it tell me that CompleteAuthToken is supported on Windows CE 2.10 and later and I should link against Secur32.lib, but adding that...
I think the MSDN docs are wrong. Looking in the Platform Builder source, I see that CompleteAuthToken() is in schannel.def and that it gets built into schannel.lib, not secure32.lib. See if making that change helps.
429,632
430,668
How to speed up floating-point to integer number conversion?
We're doing a great deal of floating-point to integer number conversions in our project. Basically, something like this for(int i = 0; i < HUGE_NUMBER; i++) int_array[i] = float_array[i]; The default C function which performs the conversion turns out to be quite time consuming. Is there any work around (maybe a h...
Most of the other answers here just try to eliminate loop overhead. Only deft_code's answer gets to the heart of what is likely the real problem -- that converting floating point to integers is shockingly expensive on an x86 processor. deft_code's solution is correct, though he gives no citation or explanation. Here i...
429,995
430,049
How do C and C++ store large objects on the stack?
I am trying to figure out how C and C++ store large objects on the stack. Usually, the stack is the size of an integer, so I don't understand how larger objects are stored there. Do they simply take up multiple stack "slots"?
The stack is a piece of memory. The stack pointer points to the top. Values can be pushed on the stack and popped to retrieve them. For example if we have a function which is called with two parameters (1 byte sized and the other 2 byte sized; just assume we have an 8-bit PC). Both are pushed on the stack this moves th...
430,386
430,396
C# is probably not the best choice for a security application?
I have stumbled in this phrase in the web: C# is probably not the best choice for a system-level application like this. I believe plain C++ is much better here as you will need to do lots of low-level API calls. I was searching about security programs made using C#, like firewall, parental control, anti-virus, an...
Things like firewalls often need hooks into kernel-level facilities which aren't (trivially) exposed by managed runtimes like .NET. You can jump through hoops to use the C# language to do this sort of thing, but then, well, you'd be jumping through hoops.
430,401
430,513
C++ Standard and Global Symbol Removal
Anyone have a link to what the C++ standard says regarding a compiler removing global and static symbols? I thought you weren't guaranteed that the compiler will remove global symbols if they're not referenced. A colleague of mine asserts that if your global symbols are included in the main translation unit, those sym...
Interestingly, all I can find on this in the C++2003 standard is this: 3.7.1 Static storage duration [basic.stc.static] All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3). ...
430,424
430,435
Are there any macros to determine if my code is being compiled to Windows?
I would like to detect whether the OS I'm compiling on is Windows. Is there a simple macro I can check to verify that?
[Edit: I assume you want to use compile-time macros to determine which environment you're on. Maybe you want to determine if you're running on Wine under Linux or something instead of Windows, but in general, your compiler targets a specific environment, and that is either Windows (DOS) or it isn't, but it's rarely (n...
431,082
431,114
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time. If I have multiple threads waiting to insert using pthread_join then spawning a new thread when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume...
From opengroup.org on pthread_join: The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. So, you really should not have several threads joining your previous insertThread. First, as you use C++, I recommend boost.thread. They resemble the POSIX model of thread...
431,206
433,891
No type definitions in pre-defined IDL FILE
Firstly, Using plain C++, without ATL, MFC attempting to use COM Object interface. Using oleview (OLE/COM Object viewer) - used to engineer the IDL code. At this stage, using MIDL Compiler, now I'm having trouble trying to produce the following: Syntax on cmd line: midl /nologo /env win32 /tlb ".\S8_.tlb" /h ".\S8_.h" ...
MIDL compiler error S8.IDL(513) : error MIDL2025 : syntax error : expecting a type specification near "S8SimObject" SOLVED Add a forward declaration - at the TOP of IDL file: import "ocidl.idl"; interface S8SimObject;
431,311
431,319
How to decide where to handle an exception - in scope of function it been thrown or in global one?
I`m writing client-server app for windows using WinSock and I have class for server. while initialising server I have such code: class Server { static const int MaxClients = 10; std::vector connections; CRITICAL_SECTION cs; int port; SOCKET ServerSocket; sockaddr_in ServerAddress; void init...
It depends on whether you're actually going to handle the exception, e.g. retry with a slightly different input, or decide to ignore the problem and proceed anyway (rarely appropriate, but can be useful). In this case, you may well want to catch the exception close to its source. In most cases, the only thing you can r...
431,429
431,434
Class vs Struct for data only?
Is there any advantage over using a class over a struct in cases such as these? (note: it will only hold variables, there will never be functions) class Foo { private: struct Pos { int x, y, z }; public: Pos Position; }; Versus: struct Foo { struct Pos { int x, y, z } Pos; }; Similar questions: W...
There is no real advantage of using one over the other, in c++, the only difference between a struct and a class is the default visibility of it's members (structs default to public, classes default to private). Personally, I tend to prefer structs for POD types and use classes for everything else. EDIT: litb made a go...
431,469
431,489
How expensive is it to dereference a pointer?
How expensive is it to perform the dereference operation on a pointer? I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.
Dereferencing, when translated into machine code, can mean different things depending on what you do with the dereferenced object. Accessing a single member of a class through a pointer is typically cheap. For example if c is a pointer to an instance of class C with an int member n then something like this: int n = c->...
431,470
431,548
window border width and height in Win32 - how do I get it?
::GetSystemMetrics (SM_CYBORDER) ...comes back with 1 and I know the title bar is taller than ONE pixel :/ I also tried: RECT r; r.left = r.top = 0; r.right = r.bottom = 400; ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE); _bdW = (uword)(r.right - r.left - 400); _bdH = (uword)(r....
The GetWindowRect and GetClientRect functions can be used calculate the size of all the window borders. Suite101 has a article on resizing a window and the keeping client area at a know size. Here is their sample code: void ClientResize(HWND hWnd, int nWidth, int nHeight) { RECT rcClient, rcWind; POINT ptDiff; G...
431,533
431,578
C++: Dynamically loading classes from dlls
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at ...
Easiest way to do this, IMHO, is to have a simple C function that returns a pointer to an interface described elsewhere. Then your app, can call all of the functions of that interface, without actually knowing what class it is using. Edit: Here's a simple example. In your main app code, you create a header for the inte...
431,827
432,058
Message Window C++ Win32 class/example
Is there a class/example application for a message-only window that is in C++ Win32?
If I recall, the standard solution is to create a basic styleless window with a message pump as you normally would, but never call ShowWindow on it. This way you can receive and process the standard messages like WM_QUERYENDSESSION which are sent to all windows.
432,143
432,166
Multiple inheritance in C++ leading to difficulty overriding common functionality
In a C++ physics simulation, I have a class called Circle, and Square. These are Shapes, and have a method called push(), which applies force to it. There is then a special case of Circle, call it SpecialCircle, in which push() should exhibit slightly different properties. But in fact, there is also SpecialSquare() w...
Another solution (it may or may not fit your needs, it depends on the details of your implementation): Have the class Behavior, and let NormalBehavior and SpecialBehavior inherit from it. Have the class Shape, and let Square and Circle inherit from it. Let Shape be an aggregate type, with a Behavior member (i.e. you p...
432,173
438,532
What are the disadvantages of the Spirit parser-generator framework from boost.org?
In several questions I've seen recommendations for the Spirit parser-generator framework from boost.org, but then in the comments there is grumbling from people using Spirit who are not happy. Will those people please stand forth and explain to the rest of us what are the drawbacks or downsides to using Spirit?
It is a quite cool idea, and I liked it; it was especially useful to really learn how to use C++ templates. But their documentation recommends the usage of spirit for small to medium-size parsers. A parser for a full language would take ages to compile. I will list three reasons. Scannerless parsing. While it's quite ...
432,230
432,236
Why can I assign an existing reference to a literal value in C++?
Consider the following: int ival = 1.01; int &rval = 1.01; // error: non-const reference to a const value. int &rval = ival; rval = 1.01; The first assignment of &rval to a literal value fails as expected. If I comment out that line the code compiles and runs. I understand why the initialization fails, but I'm conf...
ival isn't a literal value, 1.01 is the literal value. It's been copied to ival which is a variable, which most definitely can have it's references assigned to another variable.
432,361
432,365
Is it necessary to remember lots of Win32 Api for a C++ programmer?
I always work in windows environment and most often to write the program in C/C++. Is it necessary to a Windows Application Programmer to remember Win32 APIs as more as possible?? Dazza
Well, I can't say it would hurt, but I think that it's better to remember how to quickly reference the API documentation instead of actually remebering the documentation itself. That mental currency (of which there is a limited amount, of course) could be better used remembering other things to make you a better devel...
432,443
432,453
Why are there digraphs in C and C++?
I learned today that there are digraphs in C99 and C++. The following is a valid program: %:include <stdio.h> %:ifndef BUFSIZE %:define BUFSIZE 512 %:endif void copy(char d<::>, const char s<::>, int len) <% while (len-- >= 0) <% d<:len:> = s<:len:>; %> %> My question is: why do they exist?
Digraphs were created for programmers that didn't have a keyboard which supported the ISO 646 character set. http://en.wikipedia.org/wiki/C_trigraph
432,520
432,563
Is there a O(1) way in windows api to concatenate 2 files?
Is there a O(1) way in windows API to concatenate 2 files? O(1) with respect to not having to read in the entire second file and write it out to the file you want to append to. So as opposed to O(n) bytes processed. I think this should be possible at the file system driver level, and I don't think there is a user mo...
If the "new file" is only going to be read by your application, then you can get away without actually concatenating them on disk. You can just implement a stream interface that behaves as if the two files have been concatenated, and then use that stream as opposed to what ever the default filestream implementation use...
432,567
435,605
Debugging Best Practices for C++ STL/Boost with gdb
Debugging with gdb, any c++ code that uses STL/boost is still a nightmare. Anyone who has used gdb with STL knows this. For example, see sample runs of some debugging sessions in code here. I am trying to reduce the pain by collecting tips. Can you please comment on the tips I have collected below (particularly which ...
Maybe not the sort of "tip" you were looking for, but I have to say that my experience after a few years of moving from C++ & STL to C++ & boost & STL is that I now spend a lot less time in GDB than I used to. I put this down to a number of things: boost smart pointers (particularly "shared pointer", and the pointer ...
432,570
433,214
How to get a user token from Logonuser for a user account with no password?
How can you get a user token from Logonuser for a user account with no password? In particular Logonuser will fail for accounts that do not have passwords. You can validate an account by checking for a blank password + checking for GetLastError() == ERROR_ACCOUNT_RESTRICTION. But I need to actually get a token return...
This will fail if the registry setting LimitBlankPasswordUse is enabled, which it is by default. In order to disable this change the LimitBlankPasswordUse value under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa to zero. Or change the group policy setting under Security Options. Be aware that this creates a...
432,982
434,074
Is it feasible to convert a desktop based MFC C++ application to a web app
I have a very large app, 1.5 million lines of C++, which is currently MFC based using the Document/View architecture. The application includes a lot of 3d vector graphics, spreadsheets, and very many dialogs and Windows. Within the constraints of the DVA it is fairly well written, in that there is no significant prog...
The short answer is that it is feasible, don't use java, and that it will be a considerable amount of work. A good few years ago (around the time of IE5) I was asked by a client to answer a similar question to this one. The application in question was a well structured three tier desktop application. The upshot of the ...
433,164
433,207
What happens to an STL iterator after erasing it in VS, UNIX/Linux?
Please consider the following scenario: map(T,S*) & GetMap(); //Forward decleration map(T, S*) T2pS = GetMap(); for(map(T, S*)::iterator it = T2pS.begin(); it != T2pS.end(); ++it) { if(it->second != NULL) { delete it->second; it->second = NULL; } T2pS.erase(it); //In VS2005, after...
Yes, if you erase an iterator, that iterator gets a so-called singular value, which means it doesn't belong to any container anymore. You can't increment, decrement or read it out/write to it anymore. The correct way to do that loop is: for(map<T, S*>::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it++)) { ...
433,220
433,269
QNX c++ thread question
I have a question concerning this code which I want to run on QNX: class ConcreteThread : public Thread { public: ConcreteThread(int test) { testNumber = test; } void *start_routine() { for(int i = 0; i < 10; i++) { sleep(1); cout << testNumber << e...
Note 1: If you only have 1 processor the code can only be done sequentially no matter how many threads you create. Each thread is given a slice of processor time before it is swapped out for the next threads. Note 2: If the main thread exits pthreads will kill all child threads before they have a chance to execute. Now...
433,274
433,405
C++ Parameter's Value Changes Between Stack Frames in std::vector
I've run into a really strange bug, that I'm hoping someone can explain. I have a simple std::vector<V3x>, where V3x is a 3d vector (the linear algebra kind.) The following code causes a std::length_error exception to be thrown: std::vector<V3x> vertices; int vertexCount = computeVertexCount(); vertices.resize(vertexCo...
The value 3435973836 is significant. In hex, that's 0xcccccccc. That's the value assigned to local variables in Debug mode by the stack frame initialization code. When you see it back while debugging, you'd say "ah, variable not initialized". Maybe that gets you a bit closer to solving this. You mention DLL. That'...
433,301
433,343
Portable and simple unicode string library for C/C++?
I'm looking for a portable and easy-to-use string library for C/C++, which helps me to work with Unicode input/output. In the best case, it will store its strings in memory in UTF-8, and allow me to convert strings from ASCII to UTF-8/UTF-16 and back. I don't need much more besides that (ok, a liberal license won't hur...
UTF8-CPP seems to be exactly what you want.
433,325
433,666
Running background services on a PocketPC
I've recently bought myself a new cellphone, running Windows Mobile 6.1 Professional. And of course I am currently looking into doing some coding for it, on a hobby basis. My plan is to have a service running as a DLL, loaded by Services.exe. This needs to gather som data, and do som processing at regular intervals (ev...
CERunAppAtTime is a much-misunderstood API (largely because of the terrible name). It doesn't have to run an app. It can simply set a named system event (see the description of the pwszAppName parameter in the MSDN docs). If you care to know when it has fired (to lat your app put the device to sleep again when it's ...
433,327
434,587
Minimal XML library for C++?
What XML libraries are out there, which are minimal, easy to use, come with little dependencies (ideally none), can be linked statically and come with a liberal license? So far, I've been a pretty happy user of TinyXML, but I'm curious what alternatives I have missed so far.
I recommend rapidxml. It's an order of magnitude smaller than tinyxml, and doesn't choke on doctypes like tinyxml does. If you need entity support or anything advanced, forget about static linking and use expat or libxml2.
433,356
433,633
Editing the IDL created by OLE view for a C++ component
What things do I need to consider when doing this: What to remove/manipulate/add Regards
Defining interfaces in IDL for client neutrality A number of issues are described in the link above to take note
433,853
433,877
What are some common Java pitfalls/gotchas for C++ programmer?
As the question says, what are some common/major issues that C++ programmers face when switching to Java? I am looking for some broad topic names or examples and day to day adjustments that engineers had to make. I can then go and do an in-depth reading on this. I am specifically interested in opinions of engineers wh...
In C++ you'd use destructors to clean up file descriptors, database connections and the like. The naive equivalent is to use finalizers. Don't. Ever. Instead use this pattern: OutputStream os; try { os = ... // do stuff } finally { try { os.close(); } catch (Exception e) { } } You'll end up doing stuff lik...
433,895
433,988
Why are C character literals ints instead of chars?
In C++, sizeof('a') == sizeof(char) == 1. This makes intuitive sense, since 'a' is a character literal, and sizeof(char) == 1 as defined by the standard. In C however, sizeof('a') == sizeof(int). That is, it appears that C character literals are actually integers. Does anyone know why? I can find plenty of mentions of ...
discussion on same subject "More specifically the integral promotions. In K&R C it was virtually (?) impossible to use a character value without it being promoted to int first, so making character constant int in the first place eliminated that step. There were and still are multi character constants such as 'ab...
433,965
433,980
Protected derived class
#include <iostream> using namespace std; class Base { public: Base(){cout <<"Base"<<endl;} virtual ~Base(){cout<<"~Base"<<endl;} virtual void foo(){ cout<<"foo base"<<endl;} }; class Derived: private Base { public: Derived(){cout<<"Derived"<<endl;} virtual ~Derived(){c...
Why its not possible to create Derived object with base pointer???? Because the base is private. This explicitly forbids treating your class as a Base instance from the outside. Seen from the outside, your class Derived is not a subclass of Base, only from inside the class itself. The same counts for protected inheri...
434,099
434,173
Mac OSX - Xcode/Leaks problem
I'm new to development using Xcode, and am having trouble using the built-in Leaks Instrument. I have enabled guard malloc and put MallocStackLogging YES & MallocStackLoggingNoCompact YES in the environmental variables for the executable. Then running the process by clicking Run->Start with performance tool->Leaks Bu...
The problem seems to be compiling the app as 64 bit. A simple test Xcode project #include <iostream> void leaks(){ char * newleak = (char* ) malloc(2000); return; } int main (int argc, char * const argv[]) { void * leak = malloc(100); leak = NULL; while(1){ leaks(); sleep(10);...
434,140
434,153
Array of structs and new / delete
I have a struct like this: class Items { private: struct item { unsigned int a, b, c; }; item* items[MAX_ITEMS]; } Say I wanted to 'delete' an item, like so: items[5] = NULL; And I created a new item on that same spot later: items[5] = new item; Would I still need to call delete[] to clean t...
You need to call delete before setting it to NULL. (Setting it to NULL isn't required, it just helps reduce bugs if you accidentally try to dereference the pointer after deleting it.) Remember that every time you use new, you will need to use delete later on the same pointer. Never use one without the other. Also, new ...
434,522
434,529
Anyone knows how to fix compile error: LNK2005? (Source Code inside)
I have the below code in stdafx.h. using namespace std; typedef struct { DWORD address; DWORD size; char file[64]; DWORD line; } ALLOC_INFO; typedef list<ALLOC_INFO*> AllocList; //AllocList *allocList; Without the commented code (last line), it compiles just fine. But when I add the commente...
Don't put definitions in header files, just declarations. Declarations specify that something exists while definitions actually define them (by allocating space). For example typedef, extern and function prototypes are all declarations, while things like struct, int and function bodies are definitions. What's happening...
434,592
434,644
Create user exception derived from std::exception?
How a user exception class is created from standard exception? Addressing below cases Say i have a class with some enum that indicates type of object so based on type, member functions are available.Calling member function that is not available should throw an exception.Similarly when a getter of uninitialized is call...
You should probably derive from std::runtime_error or one of the other standard exceptions (see <stdexcept>) rather than directly from std::exception. It defines the what() method correctly in addition to describing what is exactly happening. Also it is usually better to define a different exception for each problem ra...
434,702
438,052
Normal main to WinCE main
I'm porting an existing (mostly) cross-platform application to WinCE 4.2. The current entry point for the function is int main(int argc, char *argv[]){} I would like to keep this part as-is, and have the WinCE entry point simply call it. I believe something like the following should work: int WINAPI WinMain( HINSTA...
Thank you both for your helpful answers. I wrote the following, which works as well as we need it for now. Only our code will be calling this executable, and never with quotes, although that wouldn't be too hard to add. Also, it might not do well if there is more than one space between arguments, but again, we don't ...
435,147
435,190
What is the best way to store UTF-8 strings in memory in C/C++?
Looking at the unicode standard, they recommend to use plain chars for storing UTF-8 encoded strings. Does this work as expected with C++ and the basic std::string, or do cases exist in which the UTF-8 encoding can create problems? For example, when computing the length, it may not be identical to the number of bytes -...
There's a library called "UTF8-CPP", which lets you store your UTF-8 strings in standard std::string objects, and provides additional functions to enumerate and manipulate utf-8 characters. I haven't tested it yet, so I don't know what it's worth, but I am considering using it myself.
435,322
435,334
Good or Bad C++ Idiom - Objects used purely for constructor/destructor?
I have a few classes which do nothing except in their constructors/destructors. Here's an example class BusyCursor { private: Cursor oldCursor_; public: BusyCursor() { oldCursor_ = CurrentCursor(); SetCursor(BUSY_CURSOR); } ~BusyCursor() { SetCursor(oldCursor_); } } ...
This technique is very common and is known as the design pattern: Resource Acquisition Is Initialization (RAII). I would not hesitate to use this design pattern at all. It's much better that you are coding using this design pattern because you will avoid bugs by forgetting to reset the cursor, or whatever the resourc...
435,429
483,736
Browser agnostic C++ DOM interface
When programming in C++ against the browser's DOM each engine has a different set of interfaces, IE has the COM based [MSHTML](http://msdn.microsoft.com/en-us/library/aa752279(VS.85).aspx), Mozilla has the XPCOM based Gecko DOM etc. Is there a common API that has adapters for major browsers (and versions)? As a clari...
Your best bet seems to be to define your own interface and write different adapters. In the likeliness that your C++ code won't be employing all DOM traversing capabilities, your interface will only have to define a compact set of traversal functions. As a bonus of defining your own interface, you can easily write a mo...
435,627
439,278
How to correctly benchmark a [templated] C++ program
< backgound> I'm at a point where I really need to optimize C++ code. I'm writing a library for molecular simulations and I need to add a new feature. I already tried to add this feature in the past, but I then used virtual functions called in nested loops. I had bad feelings about that and the first implementation pr...
If you want to force any compiler to not discard a result, have it write the result to a volatile object. That operation cannot be optimized out, by definition. template<typename T> void sink(T const& t) { volatile T sinkhole = t; } No iostream overhead, just a copy that has to remain in the generated code. Now, if...
436,013
436,029
Is there any way to check if an iterator is valid?
For two threads manipulating a container map for example, what the correct way to test whether an iterator still valid (for performance reason) ? Or would be of only indirect way that this can be done. The sample code for this : #define _SECURE_SCL 1 //http://msdn2.microsoft.com/en-us/library/aa985973.aspx #define _SEC...
std::maps are not at all thread-safe. You'll end up with much worse problems than invalidated iterators, if you have more than one thread at a time modifying the same map. I don't even think you have a guarantee that you can read anything out of a map while it's being modified by another thread. Some pages on the STL...
436,265
436,284
Emptying a C++ object
Often I add an Empty method to my C++ objects to clear the internal state using code similar to the following. class Foo { private: int n_; std::string str_; public: Foo() : n_(1234), str_("Hello, world!") { } void Empty() { *this = Foo(); } }; This seems to be better than dupl...
I'd let the constructor call my function instead: class Foo { private: int n_; std::string str_; public: Foo() { Reset(); } void Reset() { n_ = 1234; str_ = "Hello, world!"; } }; Yes, you're unnecessarily initializing the string as an empty string first, then do...
436,367
436,549
Best way to safely printf to a string?
Does anyone know a good safe way to redirect the output of a printf-style function to a string? The obvious ways result in buffer overflows. Something like: string s; output.beginRedirect( s ); // redirect output to s ... output.print( "%s%d", foo, bar ); output.endRedirect(); I think the problem is the same as ask...
This StackOverflow question has a similar discussion. Also in that question I present my favorite solution, a "format" function that takes identical arguments to printf and returns a std::string.
436,513
436,561
char!=(signed char), char!=(unsigned char)
The code below compiles, but has different behavior for the char type than for the int types. In particular cout << getIsTrue< isX<int8>::ikIsX >() << endl; cout << getIsTrue< isX<uint8>::ikIsX >() << endl; cout << getIsTrue< isX<char>::ikIsX >() << endl; result in 3 instantiations of templates for three t...
Here is your answer from the standard: 3.9.1 Fundamental types [basic.fundamental] Objects declared as characters (char) shall be large enough to store any member of the implementation's basic character set. If a character from this set is stored in a character object, the integral value ...
436,622
436,644
Quick and dirty operator!=
In my classes I often write a quick operator!= by returning !(*this == rhs), e.g.: class Foo { private: int n_; std::string str_; public: ... bool operator==(const Foo& rhs) const { return n_ == rhs.n_ && str_ == rhs.str_; } bool operator!=(const Foo& rhs) const { return...
I believe that's the preferred method of implementing operator!= so that you don't repeat yourself, and you have a guaranteed correct relationship with operator==.
436,671
438,852
How can I guarantee catching a EXCEPTION_STACK_OVERFLOW structured exception in C++ under Visual Studio 2005?
Background I have an application with a Poof-Crash[1]. I'm fairly certain it is due to a blown stack. The application is Multi-Threaded. I am compiling with "Enable C++ Exceptions: Yes With SEH Exceptions (/EHa)". I have written an SE Translator function and called _set_se_translator() with it. I have written functio...
Everything prior to windows xp would not (or would be harder) generally be able to trap stack overflows. With the advent of xp, you can set vectored exception handler that gets a chance at stack overflow prior to any stack-based (structured exception) handlers (this is being the very reason - structured exception handl...
436,804
436,895
Lifetime management of encapsulated objects
What is the best approach to encapsulate objects and manage their lifetime? Example: I have a class A, that contains an object of type B and is solely responsible for it. Solution 1, clone b object to ensure that only A is able to clean it up. class A { B *b; public: A(B &b) { this->b = b.clone(); ...
You should define your object so that the ownership semantics are, as much as possible, defined by the interface. As David Thornley pointed out, std::auto_ptr is the smart pointer of choice to indicate transfer of ownership. Define your class like so: class A { std::auto_ptr<B> b; public: A(std::auto_pt...
437,150
437,178
Can someone explain this template code that gives me the size of an array?
template<typename T, size_t n> size_t array_size(const T (&)[n]) { return n; } The part that I don't get is the parameters for this template function. What happens with the array when I pass it through there that gives n as the number of elements in the array?
Well, first you have to understand that trying to get a value out of an array can give you a pointer to its first element: int a[] = {1, 2, 3}; int *ap = a; // a pointer, size is lost int (&ar)[3] = a; // a reference to the array, size is not lost References refer to objects using their exact type or their base-class ...
437,279
437,295
Is it safe to use getenv() in static initializers, that is, before main()?
I looked in Stevens, and in the Posix Programmer's Guide, and the best I can find is An array of strings called the enviroment is made available when the process begins. This array is pointed to by the external variable environ, which is defined as: extern char **environ; It's that environ variable that has me hesi...
I think you can run your program with LD_DEBUG set to see the exact order: LD_DEBUG=all <myprogram> EDIT: If you look at the source code of the runtime linker (glibc 2.7), specifically in files: sysdeps/unix/sysv/linux/init-first.c sysdeps/i386/init-first.c csu/libc-start.c sysdeps/i386/elf/start.S you will see tha...
437,416
437,452
C++ Builder or Visual Studio for native C++ development?
I've decided I want to get more into native code development with C++. I'm trying to decide if I would be better served using CodeGear C++ Builder 2009 or Visual Studio 2008. I currently use Delphi 2007, so I'm very comfortable with C++ Builder's IDE (its the same as Delphi), as well as the VCL and RTL. I've never been...
Coming from Delphi, you'll find the VCL straightforward to use with C++ Builder. There are a few oddities, like C++ doesn't hide the fact that TObjects are all really pointers (which Delphi hides from you), and some things like array properties are accessed differently. Two or three years back, I was looking for any wa...
437,432
443,714
Is there a way to find all the functions exposed by a dll
I've been searching for a way to get all the strings that map to function names in a dll. I mean by this all the strings for which you can call GetProcAddress. If you do a hex dump of a dll the symbols (strings) are there but I figure there must me a system call to acquire those names.
It takes a bit of work, but you can do this programmaticly using the DbgHelp library from Microsoft. Debugging Applications for Microsoft .Net and Microsoft Windows, by John Robbins is an excellent (if a little older) book which contains use details and full source. And, you can pick it up on Amazon for the cheap!
437,685
437,718
Reduce windows executable size
I have a C++/MFC app on windows - dynamically linked it's only 60kb static it's > 3Mb. It is a being distributed to customers by email and so needs to be as small as possible. It statically links the MFC and MSCVRT libraries - because it is a fix to some problems and I don't want more support calls about missing lib...
You can't mix the CRT/MFC dlls. Going from memory... As the other answer suggested, you can #define WIN32_LEAN_AND_MEAN and VC_EXTRALEAN. These probably won't help though. They tend to be about minimizing build time - not the final exe size. Short of rebuilding MFC (Which is an option - you could rebuild it /Os, or ...
438,003
438,083
Environment overrides for Linux linker/loader
Earlier today I asked a question about environ, and one of the more interesting replies suggested that I could gather information using LD_DEBUG. Now I've known about some linker/loader environment variables (such as LD_PRELOAD) for awhile, but this one was new to me. Googling, I found a Linux-specific man page discuss...
My favorite is using LD_PRELOAD to work around bugs or misfeatures in GNU libc; for a while connect was doing strange things with IPv6 and I just wrote my own version that always, always used IPv4. Linux users can try man ld.so Also, the ldd command, which tells how dynamic libraries are resolved, deserves to be more ...
438,012
438,057
STL __merge_without_buffer algorithm?
Where can I get a decent high-level description of the algorithm used in __merge_without_buffer() in the C++ STL? I'm trying to reimplement this code in the D programming language, with some enhancements. I can't seem to grok what it's doing at the algorithmic level from just reading the STL source code because there...
__merge_without_buffer() is performing an in-place merge, as the merge step of an in-place merge sort. It takes as input two ranges of data [first, middle) and [middle, last) which are assumed to already be sorted. The len1 and len2 parameters are equal to the lengths of the two input ranges, namely (middle - first) ...
438,059
438,098
Use C++ class from C#
Alright so I have this C++ image capturing class. I was wondering if I could get some help..I know basic C++ (I have done one intro to c and one intro to c++ class) and I have NO idea how to do this: I need to use this class (ie create a new c++ project in my solution) and use c# to reference it and use it to save a s...
You cannot easily use C++ classes from C# without knowing some somewhat specialized information about C++/CLI - either rewrite your C++ class in C and use P/Invoke, or find a fully C# solution. But I'd like to use this c++ class for speed and memory. I question this, unless you are capturing images thousands of times...
438,067
438,100
What's the best way to get started in modern game programming and application programming?
I want to get started game programming in C/C++, or C# with DirectX or OpenGL. I'm not really sure what I want to get started, but a smallish project like a simple engine would be nice to get started with. Additionally, I would like to learn about designing applications in Windows with C#, .NET 3.5, and WPF. Utilizing ...
Modern game programming is tremendously complex as a whole but it is also very fractionated in terms of division of labor which helps reduce this complexity. Modern games are usually too complicated and large for one person to have a detailed and in-depth knowledge of the entire process. There are a lot of specialties...
438,192
438,210
A 'using' declaration with an enum
A using declaration does not seem to work with an enum type: class Sample{ public: enum Colour {RED, BLUE, GREEN}; } using Sample::Colour; does not work! Do we need to add a using declaration for every enumerators of enum type? Like below: using sample::Colour::RED;
A class does not define a namespace, and therefore "using" isn't applicable here. Also, you need to make the enum public. If you're trying to use the enum within the same class, here's an example: class Sample { public: enum Colour { RED, BLUE, GREEN }; void foo(); } void Sample::foo() { Colour foo = RED; } A...
438,227
438,797
exception hierarchy vs error enumeration
I read somewhere (can't find it now) that large exception hierarchies are a waste of time. The justification for this statement seemed sound at the time and the idea stuck with me. In my own code when I have a code base that can have a range of error conditions I use a single exception with an enumeration member to di...
Simple rule of thumb: If you end up rethrowing exceptions after examining them, then you need a more finegrained exception hierarchy (Except for the rare case where the examination entails considerable logic). If you have Exception classes that are never caught (only their supertypes are), then you need a less finegr...
438,444
438,480
Passing object ownership in C++
What is the best way to indicate that an object wants to take ownership of another object? So far, I've been using a std::auto_ptr in the public interface, so the client knows that the interface wants to take ownership of the passed object. However, the latest GCC tells me auto_ptr is deprecated, so I wonder what is re...
boost::interprocess is a library for interprocess communication, so I wouldn't use it for different purposes. As discussed on this forum: http://objectmix.com/c/113487-std-auto_ptr-deprecated.html std::auto_ptr will be declared deprecated in the next version of the standard, where it will be recommended the usage of st...
438,515
439,876
How to track memory allocations in C++ (especially new/delete)
How can I track the memory allocations in C++, especially those done by new/delete. For an object, I can easily override the operator new, but I'm not sure how to globally override all allocations so they go through my custom new/delete. This should be not a big problem, but I'm not sure how this is supposed to be done...
I would recommend you to use valgrind for linux. It will catch not freed memory, among other bugs like writing to unallocated memory. Another option is mudflap, which tells you about not freed memory too. Use -fmudflap -lmudflap options with gcc, then start your program with MUDFLAP_OPTIONS=-print-leaks ./my_program. ...
438,809
438,947
Testing framework for functional/system testing for C/C++?
For C++, there are lots of good unit test frameworks out there, but I couldn't find a good one for functional testing. With functional testing, I mean stuff which touches the disk, requires the whole application to be in place etc. Point in case: What framework helps with testing things like whether your I/O works? I'v...
I wrote one from scratch three times already - twice for testing C++ apps that talked to exchanges using FIX protocol, once for a GUI app. The problem is, you need to emulate the outside world to do proper system testing. I don't mean "outside of your code" - outside of your application. This involves emulating end use...
439,097
439,168
Query building in a database agnostic way
In a C++ application that can use just about any relational database, what would be the best way of generating queries that can be easily extended to allow for a database engine's eccentricities? In other words, the code may need to retrieve data in a way that is not consistent among the various database engines. Wh...
I would think that what you would want to do, if you needed the ability to support multiple databases, would be to create a data provider interface (or abstract class) and associated concrete implementations. The data provider would need to support your standard query operators and other common, supported functionalit...
439,219
442,993
How to make a single static library from multiple static libraries?
We recently converted a C++ project from Visual Studio 6 to Visual Studio 8. Everything went well until we reached the compilation of a project who put all the static libraries inside one big static library. By default after the conversion between the two version of projects the project didn't do anything (no big stati...
You can use the method described in the answer by nobugz also with multiple configurations and different directories for debug and release input libs. Just add all input libs, debug and release, and use "exclude from build". In the debug configuration exclude all release input libs from the build, in the release config...
439,288
439,306
Gently kill a process
I have a Windows service(C#), that sprawns few child native processes (C++). I'd like to gently kill those processes once in a while. (gently = let the procs to finalize its work before going down). I tried to use the SetConsoleCtrlHandler() routine to register the child procs to console events and to call the CloseMa...
Kernel event objects come to mind: your "manager" raises a named event. Your child processes should check the state of this event at least once in a while (or have a thread that continuously checks it).
439,402
439,559
Building a subset of boost in windows
I'm trying setup a subset of boost and get it properly compiled using bjam, however I'm not getting the result I'm looking for. I'm working on windows using boost 1.37.0. Let's say I want the libraries smart_ptr and filesystem built/installed. I intentionally chose a header only library and one library needing to compi...
Solved it. The bcp solution had make files for the projects, however I needed to copy the tools directory and the root of the boost directory to the place I copied all my libs to get things up running.
439,540
439,587
Function pointer to class member function problems
First of all I have to admit that my programming skills are pretty limited and I took over a (really small) existing C++ OOP project where I try to push my own stuff in. Unfortunately I'm experiencing a problem which goes beyond my knowledge and I hope to find some help here. I'm working with a third party library (whi...
The reason "&MyFrameGrabber::HookFunction" cannot be converted to a BUF_HOOK_FUNCTION_PTR is that, being a member of the class, it has implicitly as first parameter the "this" pointer, thus you cannot convert a member function to a non-member function: the two signatures look the same but are actually different. I woul...
439,561
439,650
Regular Expression to match {if cond}foo{else}bar{/if}
I'm having difficulty throwing away the bits of the expression I don't want, and keeping the bits I do. The problem is - given the input string: {if cond}foo{else}bar{/if} I'd like just to have: 0: {if cond}foo{else}bar{/if} 1: cond 2: foo 3: bar And for the input string: {if cond}foo{/if} I'd like just to have: 0: ...
What about this? \{if ([a-z0-9]+)\}([^\{]*)(?:\{else\})?([^\{]*)\{/if\}
439,573
439,589
How to convert a single char into an int
I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int? I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on...
You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this). Therefore the integer value for any digit is the digit minus '0' (or 48). char c = '1'; int i =...