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,886,777
1,886,787
What are .rc2 files used for in Visual Studio
I am new to Windows environment of development. I see a lot of .rc2 files used where a mapping is performed against some MACRO type constants to strings. Q1. Why are these .rc2 files used? Can someone give me a start on these.
From MSDN: The RC2 file can be included at the top of the RC file in a project. An RC2 file is useful for including resources used by several different projects. Instead of having to create the same resources several times for different projects, you can put them in an RC2 file and include the RC2 fi...
1,886,913
1,886,929
How do you try out small/simple C or C++ source codes?
It is very easy on Linux to fire-up vi and write a 100-200 lines of code, compile and see the results: ie. Trying small simple examples of C/C++ code. On windows however, I like Visual Studio but to use it you have create a new solution then a project which then creates a new folder, generates very large PDB and cachin...
You can compile from the command line using cl.exe. See the MSDN article How to: Compile a Native C++ Program from the Command Line for detailed instructions.
1,887,041
1,887,113
What is a good way to test a file to see if its a zip file?
I am looking as a new file format specification and the specification says the file can be either xml based or a zip file containing an xml file and other files. The file extension is the same in both cases. What ways could I test the file to decide if it needs decompressing or just reading?
The zip file format is defined by PKWARE. You can find their file specification here. Near the top you will find the header specification: A. Local file header: local file header signature 4 bytes (0x04034b50) version needed to extract 2 bytes general purpose bit flag 2 bytes compres...
1,887,097
1,887,178
Why aren't variable-length arrays part of the C++ standard?
I haven't used C very much in the last few years. When I read this question today I came across some C syntax which I wasn't familiar with. Apparently in C99 the following syntax is valid: void foo(int n) { int values[n]; //Declare a variable length array } This seems like a pretty useful feature. Was there ever a...
There recently was a discussion about this kicked off in usenet: Why no VLAs in C++0x. I agree with those people that seem to agree that having to create a potential large array on the stack, which usually has only little space available, isn't good. The argument is, if you know the size beforehand, you can use a stat...
1,887,134
1,889,451
Can a Silverlight client talk to a C++ server?
Our company wants to transform our current user interface to a web client. We are considering to use Microsoft's Silverlight for this, but it will need to communicate with our legacy C++ server application (native C++, not C++/CLI). I am wondering whether it would be feasible to write such an IPC library by hand, our o...
You can certainly do this -- on my desktop right now, I'm running a C++ server application in one instance of Visual Studio, a Silverlight application in a second instance, and the Silverlight app is talking to the C++ server over sockets. However, there are several significant caveats: (1) Silverlight will only talk...
1,887,398
1,887,558
C++ class hierarchy for collection providing iterators
I'm currently working on a project in which I'd like to define a generic 'collection' interface that may be implemented in different ways. The collection interface should specify that the collection has methods that return iterators by value. Using classes that wrap pointers I came up with the following (greatly simpli...
If you want to use inheritance for your iterators, I would recommend you to use a different approach than STL's begin()/end(). Have a look on IEnumerator from .NET framework, for example. (MSDN documentation) Your base classes can look like this: class CollectionBase { // ... virtual IteratorBase* createIterat...
1,887,464
1,887,485
C++ preprocessor variable
I'm using the SKELETON_JAR variable on my C++ code in one header. However, I want to allow the user to define the place of the jar in the compile time easily. I think the easiest way to do that is to put this define in makefile is that so? #define SKELETON_JAR "./Util.jar"
In your code: #ifndef SKELETON_JAR #define SKELETON_JAR "./Util.jar" // default path #endif and then in the makefile use CPPFLAGS:=-DSKELETON_JAR="./Util.jar". Of course you have to make sure CPPFLAGS are passed to the compiler as part of the compile rule which is the case if you're using the default implicit rules....
1,888,003
1,888,213
How to implement a tiny RTSP server?
I am implementing a client/server application where video streaming occurs between two computers (in one direction). I would like to have the server publish an SDP file when it starts streaming. The client would then be able to download this SDP file and use it to get the stream. In order to implement this it seems I n...
Use Live555 LGPL library or for fun, read the RFC and implement :-)
1,888,247
1,888,259
Why does my inputchar function keep looping?
#include <iostream> using namespace std; struct Node { char item; Node *next; }; void inputChar ( Node * ); void printList (Node *); char c; int main() { Node *head; head = NULL; c = getchar(); if ( c != '.' ) { head = new Node; head->item = c; inputChar(head); ...
Perhaps you should add: c = getchar(); Still, it's kind of dangerous what you are doing. In some platforms, getchar() will return immediately after consuming the ENTER key of the previous getchar() call. So you should consider that in your loop. Perhaps adding an extra getchar() to the inputChar function? Also, what P...
1,888,293
1,888,337
union members may not have constructors, but `std::pair` okay?
union members may not have destructors or constructors. So I can't template the following class Foo on my own MyClass if MyClass has a constructor: template<class T> struct Foo { T val; Foo(T val_) : val(val_) {} size_t hash() const { union {T f; size_t s;} u = { val }; return u.s; } }; struct MyClass {...
EDIT: My original stance on std::pair was wrong, it shouldn't be allowed in a union. For a class to be a valid member of a union it must have a trivial constructor according to standard 9.5.1. The definition of a trivial constructor is this, from paragraph 12.1.5: If there is no user-declared constructor for class ...
1,888,652
1,888,665
How can I use iteration instead of recursion to input values into a linked list?
Ok so let's say we have a linked list of characters with a head pointer. How can I create a loop to enter a string of characters into the linked list? My problem is when I think of head and head->next and head->next->next . . . it only seems natural to use a recursive function to set the characters at each node.
It's trivial to do it with iteration. You would just start at head, and use a loop to iterate over the list by doing current = current->next, until you hit a NULL. Basically something like: node* n = head; while (n) { // ... do something with n n = n->next; }
1,888,672
1,889,395
Calling functions in a Lua table from C++
I have for example, a Lua table/object: bannana And this Lua table has a function inside it called chew, that takes a parameter bannana.chew(5) I have also used SWIG, and have for example a class CPerson: class CPerson { public: // .... void Eat(); // .... }; I can obtain an instance of t...
Ignoring any error checking ... lua_getglobal(L, "banana"); // or get 'banana' from person:Eat() lua_getfield(L, -1, "chew"); lua_pushinteger(L, 5); lua_pcall(L, 1, 0, 0);
1,888,915
1,889,048
How to write these classes using Google's protobuf?
I have just come accross Google's Protocol buffers. It seems to be the solution for a C++ backend application I am writing. Problem is I cant seem to find anything regarding vector types. The documentation mentions repeated_types, but I cant seem to find anything. Supposing I have these set of classes: class UnifiedBin...
I think you misunderstood the philosophy. IMHO Google's Protocol Buffers is meant to produce 'messages' class that are distinct from your application classes. Note that Protobuf is NOT a serialization library (though it may be used as such). It is a messaging library, which allows to exchange messages between differen...
1,889,137
1,889,314
Inherit from a template parameter and upcasting back in c++
I have tried to use this code in VS2008 (and may have included too much context in the sample...): class Base { public: void Prepare() { Init(); CreateSelectStatement(); // then open a recordset } void GetNext() { /* retrieve next record */ } private: virtual void Init() = 0...
After changing CreateSelectStatement to return a value for the implemented functions (not the pure virtual) string CreateSelectStatement() const { return ""; } and changing the declaration of reader (the declaration you have should strictly be interpreted as a function prototype in C++) SomeValueReader<A> reader; The...
1,889,170
1,889,272
Can someone help spot the errors in my low lock list?
I've written a low lock list in C++ on windows 32-bit. I'm getting BIG improvements over using critical sections but I'd like someone to sanity check that what I'm doing is correct and there aren't any errors in what I've done: #ifndef __LOW_LOCK_STACK_H_ #define __LOW_LOCK_STACK_H_ template< class T > class LowLockS...
You do not synchronize access to the list header member. This is bad at least on 2 levels: assigning values to the list header can be not as atomic as you think. Which means that an unsynchronized read operation can potentially get a corrupted value. another, more probable issue with this is that if your box has multi...
1,889,996
1,890,031
Inheritance mucking up polymorphism in C++?
Perhaps my knowledge of inheritance and polymorphism isn't what I thought it was. Can anyone shed some light? Setup (trivialization of problem): class X { }; class Y { }; class Base { public: void f( X* ) {} }; class Child: public Base { public: void f( Y* ) {} }; Question: This should work, right? int...
The virtual keyword will not help you here. Your base class Base::f is being hidden by your derived type. You need to do the following: class Child: public Base { public: using Base::f; void f( Y* ) {} }; Parashift goes into more detail.
1,890,041
1,890,069
Avoid making copies with vectors of vectors
I want to be able to have a vector of vectors of some type such as: vector<vector<MyStruct> > vecOfVec; I then create a vector of MyStruct, and populate it. vector<MyStruct> someStructs; // Populate it with data Then finally add someStructs to vecOfVec; vecOfVec.push_back(someStructs); What I want to do is avoid hav...
The swap trick is as good as it gets with C++03. In C++0x, you'll be able to use the vector's move constructor via std::move to achieve the same thing in a more obvious way. Another option is to not create a separate vector<MyStruct>, but instead have the code that creates it accept it a a vector<MyStruct>& argument, a...
1,890,448
1,890,553
What's the intended use of _fread_nolock, _fseek_nolock?
we have a C++ class which basically reads and writes vectors from a binary file. An exemplary read function that loads a single vector into memory looks like this: int load (const __int64 index, T* values) const { int re = _fseeki64(_file, index * _vectorSize + _offsetData, SEEK_SET); assert(re == 0); size_t read...
For some simple code, the lock within the FILE * is sufficient. Consider a basic logging infrastructure where you want all threads to log via a common FILE *. The internal lock will make sure the FILE * will not be corrupted by multiple threads and since each log line should stand alone, it doesn't matter how the ind...
1,890,502
1,890,597
how to hook control closing in an MFC custom control class
I am interested in allocating pointers, storing those in the LPARAM data of a comboboxex control, and making that control responsible for deleting those pointers when it is destroyed. Since I am working in MFC, I can subclass a CComboBoxEx, and add either a message handler or a virtual member function. The question is:...
During OnDestroy() your window will still be valid -- if it weren't, your window wouldn't have gotten the message at all, since it's sent via the standard Windows messaging system. You are on the right track -- this type of scenario is what OnDestroy() is for.
1,890,555
1,890,702
How can I obfuscate a test in code to prevent tampering with response processing?
I am looking for a way to obfuscate (in the object code) a test - something like what might be done to check that a license key is valid. What I am trying to prevent is someone searching through an image binary for the code that processes the response. bool checkError = foo(); if ( checkError ) // I'd like to avoid mak...
One approach would be to put the code that does the license check into a separate DLL. In the main application, load the DLL at runtime and calculate the checksum of the DLL itself. The app stores the checksum that was calculated with the DLL was built. If the checksums don't match, you have several options, show a ...
1,890,867
1,890,956
Add the upper and lower 64-bits of a 128-bit xmm register
I have two packed quadword integers in xmm0 and I need to add them together and store the result in a memory location. I can guarantee that the value of the each integer is less than 2^15. Right now, I'm doing the following: int temp; .... movdq2q mm0, xmm0 psrldq xmm0, 8 movdq2q mm1, xmm0 paddq mm0,mm1...
First off, why are you using quadwords to represent values that would fit in a 16-bit format? Leaving that aside, a couple solutions: pshufd xmm1, xmm0, EEh paddq xmm0, xmm1 movd temp, xmm0 or movdqa xmm1, xmm0 psrldq xmm1, 8 paddq xmm0, xmm1 movd temp, xmm0 or movhlps xmm1, xmm0 paddq xmm0, xmm1 movd tem...
1,891,194
1,935,082
InPlaceActivate on ATL control not called until mouse event
I have an ActiveX control written in C++ that I created with VS2008 and ATL. For the most part, it is a pretty standard (not modified much from the original template) control, except that instead of using IDispatchImpl, I have created my own IDispatchEx implementation. This control is only used in Internet Explorer, ...
I found the culprit. Aparently, the OLEMSIC_ACTIVATEWHENVISIBLE is used to auto-generate the %OLEMISC% variable in the .rgs file. However, I had overridden the default rgs handling to provide my own variables, and in the process one critical line got removed, which would have added a: [CLSID]/MiscStatus/1 = s '131473...
1,891,237
1,903,978
Sending a struct from C++ to WPF using WM_COPYDATA
I have a native C++ application that, for the time being simply needs to send its command line string and current mouse cursor coordinates to a WPF application. The message is sent and received just fine, but I cannot convert the IntPtr instance in C# to a struct. When I try to do so, the application will either crash ...
I am not sure what you are getting wrong necessarily without more info about your setup. I replicated the code as best I could (using WndProc in a WPF app, sending from my own win32 app) and it works fine for me. There are a few errors which will definetly crop up if you are running 64 bit applications, namely the Pack...
1,891,249
1,892,865
What's a pattern for getting two "deep" parts of a multi-threaded program talking to each other?
I have this general problem in design, refactoring or "triage": I have an existing multi-threaded C++ application which searches for data using a number of plugin libraries. With the current search interface, a given plugin receives a search string and a pointer to a QList object. Running on a different thread, the plu...
Why is it "completely wrong according to OO"? If your plugin needs access to that object, and it doesn't violate any abstraction you want to preserve, it is the correct solution. To me it seems like you blew your abstractions the moment you decided that your plugin needs access to the list itself. You just blew up your...
1,891,330
1,891,457
high speed interprocess associative array
Is there library usable from c++ for sharing fairly simple data (integers,floating point numbers, strings) between cooperative processes? Must be : high-speed (SQL-based methods too slow due to parsing) able to get,set,update,delete both fixed and variable data types (e.g. int and string) ACID (atomic,consistent,iso...
Take a look at boost::interprocess. For local use, you probably can't beat a map or hash table in shared memory. Allowing networking makes things more difficult, in that case something like memcached or CouchDB might be more appropriate.
1,891,836
1,901,663
Compiled FreeImage from source. #include FreeImage.h not found
I have compiled FreeImage 3.10.0 from source at /lib/FreeImage on Mac OS X 10.6. I can see that after compilation these files were copied: /usr/local/lib/libfreeimage-3.10.0.dylib /usr/local/lib/libfreeimage.a /usr/local/include/FreeImage.h CMake cannot find FreeImage, but I cannot even do #include <FreeImage.h> // n...
The 'INCLUDE +=' line looks like the one to attack: INCLUDE += -I/usr/local/include If the library is missing too, then you will need to find another line to add '-L/usr/include/lib' to.
1,891,843
1,891,870
C++ efficient inheritance of certain methods in child classes
I find my self repeating a single line of code in child constructors, which are passed two variables. The first of these variables is always used to initiate a protected variable (defined in the parent class). I was wondering if there is a way for me to do that assignment in the parent constructor - which is then inher...
If I understand you correctly, you need something like this class Parent { public: Parent(int Param1, doubel param2) :param1(Param1), param2(Param2) { } protected: int param1; double param2; }; class Derived: public Parent { public: Derived(int Param1, doubel param2) :Parent(Param1, Param2) { } };...
1,892,040
1,892,263
Linux multithreading would involve the pthreads library(in most cases) . What is the equivalent library used by MSVC?
I need to know which are the APIs/library used for multithreading by MSVC . If there are more than one , please let me know which is the most widely used. If my question sounds too naive , its because I've never done threading before , and from my past experience , I know there are people here who can get me started/po...
As others have suggested you can use CreateThread or _beginthread or the threadpool APIs, the process and threads reference is best for Win32 threading, you can also use boost::thread which is very close to the C++0x std::thread standard. The other option if you're using Visual Studio is to take a look at the Parallel ...
1,892,043
1,892,054
Self-sufficient header files in C/C++
I recently posted a question asking for what actions would constitute the Zen of C++. I received excellent answers, but I could not understand one recommendation: Make header files self-sufficient How do you ensure your header files are self-sufficient? Any other advice or best-practice related to the design and impl...
A self sufficient header file is one that doesn't depend on the context of where it is included to work correctly. If you make sure you #include or define/declare everything before you use it, you have yourself a self sufficient header. An example of a non self sufficient header might be something like this: ----- MyCl...
1,892,050
1,892,061
Why is my printList function not working?
#include <iostream> using namespace std; struct Node { char item; Node *next; }; void inputChar ( Node * ); void printList (Node *); char c; int main() { Node *head; head = NULL; c = getchar(); if ( c != '.' ) { head = new Node; head->item = c; inputChar(head); ...
if(p = NULL) That's your problem right there. It should be if(p == NULL)
1,892,064
1,904,124
How do I detect a custom plugin in Firefox/IE/Chrome?
My team wants to build a "plugin" for firefox/chrome/IE. How do I use javascript to detect if this plugin (not extension) is installed? I would like to have a piece of javascript that can detect if a certain plugin is installed. Returns true if installed, returns false otherwise. For example...how do I get a list of p...
solved: document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>", "<TH ALIGN=left>i", "<TH ALIGN=left>name", "<TH ALIGN=left>filename", "<TH ALIGN=left>description", "<TH ALIGN=left># of types</TR>") for (i=0; i < navigator.plugins.length; i++) { document.writeln("<TR VALIGN=TOP><TD>",i, "<TD>",navig...
1,892,104
1,892,138
Can a thread be pre-empted in the midst of a system call to kernel?
I'm running 2 threads ( assume they are pthreads for the moment) . Thread_1() makes a user-defined API call which ultimately does some work in the kernel . Thread_2() is totally in user-space. My question is : Can Thread_2() start executing by pre-empting Thread_1() while the API call is in progress , the control is s...
If you are asking whether a blocking kernel call like an fread() which requires disk IO can be pre-empted, then yes. More specifically a blocking call will basically put Thread_1 to sleep while waiting for whatever it's waiting for. If Thread_1 is asleep then Thread_2 will be scheduled to run (unless there's something ...
1,892,172
1,892,428
What is coming in IDataObject?
When you implement IDropTarget you must implement this: virtual HRESULT STDMETHODCALLTYPE Drop( /* [unique][in] */ __RPC__in_opt IDataObject *pDataObj, /* [in] */ DWORD grfKeyState, /* [in] */ POINTL pt, /* [out][in] */ __RPC__inout DWORD *pdwEffect)=0; I want to know ...
See IDataObject::EnumFormatEtc. As you can see from the documentation it may be possible to query for the data in multiple formats and EnumFormatEtc is a means to enumerate the various formats available.
1,892,229
1,892,417
c++ iterator confusion
I have a vector<list<customClass> > I have an iterator vector<list<customClass> >::const_iterator x When I try to access an member of customClass like so: x[0]->somefunc(), I get errors of a non-pointer type/not found.
Here's a complete working snippet. To answer your question, the line with the comment [1] shows how to dereference the const_iterator, while comment [2] shows how to dereference using the operator []. #include <vector> #include <list> #include <iostream> class Foo { public: void hello() const { std::cou...
1,892,379
1,892,388
Preferred implementation of '<' for multi-variable structures
Initially this may seem overly abstract or philosophical, but I am genuinely interested to see if someone has a convincing argument in favor of one implementation over the other. Given operator< for std::pair<T1, T2>, which would be the better implementation: return x.first < y.first || x.first == y.first && x.s...
It is not legitimate to assume that for any type, if it is less-than comparable, it is also equality comparable, since one can overload operator< but not overload operator==. Thus, if you anticipate having to handle user-defined types, the second approach is preferable. However, you should add some parentheses to clar...
1,892,566
1,892,571
C++ Bus error in SPARC arcitecture
I would like to understand why I am getting a bus error with this code. int main() { int p=34; int *pp= (int *) ((char *)&p+1); cout<<*pp<<"\n"; return 0; }
It will no doubt be an alignment issue. On many architectures, certain types have to be aligned properly, an example being that 4-byte integers must start on a 4-byte boundary. If you access non-aligned data, some architectures won't care, others will run slower, still others (such as in this case) will fall in a screa...
1,892,588
1,919,640
Linking error when compiling C and C++ code with g++
I am integrating a medium-sized (10,000 or so lines) program written in C into a C++ program. I have created a new class, BWAGenome as an interface to the C code, so any access to the C functions is encapsulated. I am compiling everything with the g++ compiler. The .o files are all generated correctly, but when I attem...
The error was in the order I was linking the object files together. I needed to link in the C code first, and then the BWAGenome class I created to call it. The linker couldn't find the C code symbols because they weren't linked yet. Thanks for all your help though. I imagine I frustrated some people, but thanks anyway...
1,892,619
1,892,640
Threads and simple Dead lock cure
When dealing with threads (specifically in C++) using mutex locks and semaphores is there a simple rule of thumb to avoid Dead Locks and have nice clean Synchronization?
A good simple rule of thumb is to always obtain your locks in a consistent predictable order from everywhere in your application. For example, if your resources have names, always lock them in alphabetical order. If they have numeric ids, always lock from lowest to highest. The exact order or criteria is arbitrary. The...
1,892,921
1,892,928
c++ operator overloading
i'm not sure if what im talking about is an operator overloading question. is it possible to overload keywords in C++?? for example : i need to write loopOver(i=0; ;i++) instead of for(i=0;;i++) ?? is that possible in C++ and i need to have something like 2 addTo 2 instead of 2 + 2 please help thanks in advance
You can't do that with operator overloading (you can't change the names of the operators, only how they work). However, evil as it is, if you don't want to change the way they work (just the names), you would be able to achieve things like this using macros: #define loopOver for #define addTo + (Use macros with extrem...
1,893,092
1,893,105
How do I write a public function to return a head pointer of a linked list?
class Newstring { public: Newstring(); void inputChar ( char); void display (); int length (); void concatenate (char); void concatenate (Newstring); bool substring (Newstring); void createList (); Node * getHead (); // error private: struct Node { char item; ...
Declare Node before you use it.
1,893,438
1,893,466
Tools for Unix <-> Windows C++ development
I am doing some C++ cross development - been doing that for a while on Windows and recently started on Unix. I suppose what I am after is to simplify Unix development experience - I have a local windows box I do development on, and a remote Solaris box which I use to compile and test code on unix environment. What I d...
If by any chance you want to run the same C++ IDE on both Windows and Solaris, I recommend taking a look at Code::Blocks. Also, as I suggested to Charles, running an X server on the Windows box gives you a lot more flexibility than running Putty or similar.
1,893,490
1,893,518
What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)
What is the difference between %d and %i when used as format specifiers in printf and scanf?
They are the same when used for output, e.g. with printf. However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0). So 033 would be 27 with %i b...
1,893,688
1,893,809
abstract class and using array polymorphically
i'm just reading meyers "More Effective C++ 35 New Ways" - item 33, and he suggest there always to inherit from an abstract base class, and not a concrete. one of the reason he claims, which i can't quite get , is that with inheriting from an abstract class, treating array polymorphically (item 3 in the book) is not a ...
While I think that avoiding inheritance from non-abstract classes is a good design guideline and something that should make you think twice about your design, I definitely do not think that it's in the category of 'never do this'. I will say that classes designed to be inherited from that have data in them should proba...
1,893,835
1,893,856
Internal enum as a base class template parameter
pragma once #include "stdafx.h" #include "Token.h" //I would like this enum to be inside class Number enum Number_enm {ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE}; class Number : public Token<Number_enm>//and this template parameter to be Number::Number_enm { private: public: Number(const Num...
No, you can't because it's not possible to forward declare an enum. Also, but not related, those contructor try blocks are a bad idea. See also article by Herb Sutter at http://www.ddj.com/cpp/184401297 - he is slightly less condemnatory than me. Anyway, as I said, the try blocks have nothing to do with your question.
1,893,865
1,893,890
How rethrow an exception without losing the original call stack?
The situation is as follows: Thread A catches an exception, saves the exception's data somewhere in memory (using GetExceptionInformation in the exception filter), and afterwords Thread B gets that exception information and wants to rethrow it. But the thing is, when thread B rethrows the caught exception, i'm missing ...
You could unwind the stack in the catch block and save it as part of the exception you are rethrowing. Unwinding the stack in C++ is a bit tricky, but you could have a al look at the crashdump collector code that comes with WxWidgets for an example.
1,894,236
1,894,422
Cross Platform C++ Tool Chain
Hello I am putting together a tool chain on my windows Box for Cross Platform C++ Development. I plan on using Boost.Build for building and Boost::Test for unit testing. I will be using Mercurial for my VCS because I can just throw the repo on my external HD and then pull it to either my windows or linux partition. ...
May I suggest CMake on Windows and Linux as you can generate native Visual Studio projects as well as Eclipse CDT projects and plain-old makefiles. If you are targeting multiple platforms, but find yourself primarily developing on a single platform, I highly recommend a continuous build/integration system to ensure a c...
1,894,446
1,894,855
Taking advantage of SSE and other CPU extensions
Theres are couple of places in my code base where the same operation is repeated a very large number of times for a large data set. In some cases it's taking a considerable time to process these. I believe that using SSE to implement these loops should improve their performance significantly, especially where many oper...
For your second point there are several solutions as long as you can separate out the differences into different functions: plain old C function pointers dynamic linking (which generally relies on C function pointers) if you're using C++, having different classes that represent the support for different architectures ...
1,894,683
1,894,689
Bitwise Or: C# versus C++
). Assume you have two integers, a = 8, b = 2. In C++ a | b is true. I used that behavior to work with collections of flags. For example the flags would be 1, 2, 4, 8 and so on, and any collection of them would be unique. I can't find how to do that in C#, as the | and & operators don't behave like they would in C++. I...
The & and | operators in C# are the same as in C/C++. For instance, 2 | 8 is 10 and 2 & 8 is 0. The difference is that an int is not automatically treated like a boolean value. int and bool are distinct types in C#. You need to compare an int to another int to get a bool. if (2 & 8) ... // doesn't work if ((2...
1,894,886
1,894,955
Parsing a comma-delimited std::string
If I have a std::string containing a comma-separated list of numbers, what's the simplest way to parse out the numbers and put them in an integer array? I don't want to generalise this out into parsing anything else. Just a simple string of comma separated integer numbers such as "1,1,1,1,2,1,1,1,0".
Input one number at a time, and check whether the following character is ,. If so, discard it. #include <vector> #include <string> #include <sstream> #include <iostream> int main() { std::string str = "1,2,3,4,5,6"; std::vector<int> vect; std::stringstream ss(str); for (int i; ss >> i;) { ve...
1,894,968
1,895,031
Help with object from mouse algorithm
I wasn't sure what to call this. I'm building a tile based game where the user can click on a tile. it is a 2d c++ vector of tiles. right now I have an algorithm that positions them like this: [][][][][][][][][][][] [][][][][][][][][][][] [][][][][][][][][][][] [][][][][][][][][][][] [][][][][][][][][][][] [][][][][][]...
If you're not using an event based environment, you do need to code your own object intersection, mouse detection, etc. Here's the formula in pseudo code for what you want to get: tile_width = 10; tile_height = 10; x_tile = Math.ceil(mousex/tile_width); y_tile = Math.ceil(mousey/tile_height);
1,895,262
1,895,271
How to override the ++ operator in C++ and then print the output using an overriden << operator?
I'm trying to learn overriding operators in C++. But I'm stuck with this: ..\src\application.cpp: In function `int main()': ..\src\application.cpp:29: error: no match for 'operator<<' in 'std::operator<< [with _Traits = std::char_traits](((std::basic_ostream >&)(&std::cout)), ((const char*)"Poly A: ")) << (&A)->Poly::...
I think the problem is that you declare your parameters as references: ostream& operator<<(ostream &out, Poly &robject) The reference will not bind to the temporaries that you return from your operator++. If you make the Poly parameter a const reference you should be able to output it.
1,895,322
1,895,332
adding const before the brackets in c++
Just wondering why the syntax for virtual functions uses a const before the curly braces, as below: virtual void print(int chw, int dus) const; Incidentally, the code doesnt seem to work without the const, which is interesting.. not sure why? many thanks!
The const in the function signature signifies a const member function - Anthony Williams gave a great answer on the implications. Note that there is nothing special about virtual member functions functions in that regard, constness is a concept that applies to all non-static member functions. As for why its not working...
1,895,342
1,895,897
specialization on const member function pointers
I am trying to specialize some utility code on const member functions, but have problems to get a simple test-case to work. To simplify the work i am utilizing Boost.FunctionTypes and its components<FunctionType> template - a MPL sequence which should contain the tag const_qualified for const member functions. But usin...
While its still unclear to me why the approach via function_types::components<> doesn't work, i realized that there is a simpler approach with Boost.FunctionTypes to specialize on const member functions: The classification meta functions like is_member_function_pointer<> optionally take a tag parameter ... template<typ...
1,895,412
1,895,480
Get the ip addresses of an interface
Using the output of "ipconfig /all" i can get what I need but I want a more reliable technique to get ip of an interface (practically the interface has to be identified by it's name) in case of ipconfig was corrupted or was not available for any reason.
Since you mentioned ipconfig, I assume you want to do this on windows. Windows has a set of IP Helper apis designed for retrieval and modify networking settings. And here is a simple sample: http://msdn.microsoft.com/en-us/library/aa366298(VS.85).aspx
1,895,437
1,895,521
CEditBox or CListBox which one is better for big amout of logging data
This always was a big question for me that for a very big amount of logs (like 100,000 line log) which one is better in performance, scrolling,... also consider formatting the text with color is a must.
Under the circumstances, I'd probably use a listbox. You can create a virtual listbox to support lots of items relatively well. Neither supports color1 but owner-drawn listboxes are easier. Edit controls are "flow" oriented, not line oriented. 1Other than one foreground and one background color.
1,895,595
1,895,602
Should screen dimension constants that hold magic numbers be refactored?
I have a few specific places in my code where I use specific pixel dimensions to blit certain things to the screen. Obviously these are placed in well named constants, but I'm worried that it's still kind of vague. Example: This is in a small function's local scope, so I would hope it's obvious that the constant's name...
Depends. Is there a particular reason those constants are what they are? (For instance, is that "430" actually 200 pixels to the left of some other element?) If so, then it'd probably make more sense to express it in terms of the constant used for the other element (or whatever reason results in that number). If they'r...
1,895,922
1,895,947
Sequence points and partial order
A few days back there was a discussion here about whether the expression i = ++i + 1 invokes UB (Undefined Behavior) or not. Finally the conclusion was made that it invokes UB as the value of 'i' is changing more than once between two sequence points. I was involved in a discussion with Johannes Schaub in that same ...
The C standard says this about assignment operators (C90 6.3.16 or C99 6.5.16 Assignment operators): The side effect of updating the stored value of the left operand shall occur between the previous and the next sequence point. It seems to me that in the statement: i=(i,i++,i)+1; the sequence point 'previous' to the...
1,896,341
1,896,349
Can constructor call another constructor in c++?
class A{ A(int a = 5){ DoSomething(); A(); } A(){...} } Can the first constructor call the second one?
Not before C++11. Extract the common functionality into a separate function instead. I usually name this function construct(). The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. S...
1,896,369
1,896,395
How to use a class object in C++ as a function parameter
I am not sure how to have a function that receives a class object as a parameter. Any help? Here is an example below. #include<iostream> void function(class object); //prototype void function(class tempObject) { //do something with object //use or change member variables } Basically I am just confused on how t...
class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself. e.g. class ANewType { // ... details }; This defines a new type ...
1,896,404
1,896,415
fread speeds managed unmanaged
Ok, so I'm reading a binary file into a char array I've allocated with malloc. (btw the code here isn't the actual code, I just wrote it on the spot to demonstrate, so any mistakes here are probably not mistakes in the actual program.) This method reads at about 50million bytes per second. main char *buffer = (char*)ma...
Transfers from or to main memory run at speeds of gigabytes per second. Inside the CPU data flows even faster. It is not surprising that, whatever you do at the software side, the hard drive itself remains the bottleneck. Here are some numbers from my system, using PerformanceTest 7.0: hard disk: Samsung HD103SI 5400 ...
1,896,432
2,811,327
How to mix C++ Qt objects and Qt Jambi objects
I'm trying to combine some existing Qt code written in C++ with some code written in Java using Qt Jambi, but I'm not quite sure how to do it. I'm basically trying to acieve two things: Pass a QObject from C++ to Java using JNI Pass a Qt Jambi QObject from Java to C++ It looks like I can pass the pointer directly and...
For other people looking at this, check this out: http://labs.trolltech.com/blogs/2007/08/24/extremely-interesting-jambi-trick-x-instantiating-java-widgets-from-c/ Especially this part: The qtjambi_from_QWidget() call will either create a new Java widget if the parent widget was created in C++, or it will return...
1,896,505
1,896,520
Strange error occurred while using cmake
Does anyone know what "The C compiler "cl" is not able to compile a simple test program." means? I am trying to compile Wt using CMake on MSVC 9. The OS is Windows XP. Here is the full log: Check for working C compiler: cl Check for working C compiler: cl -- broken CMake Error at I:/Program Files/CMake 2.8/sha...
I googled for the cmd.exe error and came up with this page. Looks like Visual studio needs to be configured with a few paths so it knows how to find cmd.exe. Here are the steps from that thread: What you must do is change MSVS options (Tools menu > Options > Project and Solutions > VC++ Directories) to ensure that $(S...
1,896,527
1,896,548
counting letters in a text file
Can sommebody please tell me what is not right about this code? It compiles and everything great but the output is solid zero's all the way down. So it is not counting the letters. #include <iostream> #include <fstream> #include <string> using namespace std; const char FileName[] = "c:/test.txt"; int main () { ...
You just have your if statement scoping wrong here. Each letter can be either uppercase or lowercase, but the way your if statements are scoped, you're only checking for lowercase if the letter is already uppercase, which of course is nonsensical. You want something more like: for(unsigned n = 0; n < lineBuffer.length...
1,896,597
1,896,627
Lame operator redefinition error
Sorry it's lame but I can't figure it out: class Address { public: uint32_t addr; uint16_t port; public: Address(); Address(uint32_t addr, uint16_t port); Address(const Address & src); Address& operator=(const Address &src); bool isNull(); friend std::ostream& operator<<(std::ostrea...
Well, if I include #include <cstdint> #include <iostream> at the beginning of your code, I can compile it using g++ -c -std=c++0x Account.cpp (g++ 4.4.1).
1,896,644
1,896,686
CSocket Server get the client IP Address
How can I get the ip address of a client when he tries to connect to the server? I'm using CSocket class.
void getPeer(unsigned short& port, std::string& peer); Returns information about the remote side of the socket. port is the port on which the connection is held, and peer is the host to which the socket is connected. The peer is either a fully qualified domain name (if the IP address can be resovled via ...
1,896,656
1,896,673
simple wildcard match with std::string
I have std::string with the follwing format std::string s = "some string with @lable" I have to find all instances of '@' and then find the identifier right after the '@' , this ID has a value (in this case 'lable' stored for it in a look up table. I will then replace the @ and the id with the found value. fo...
You can use std::find to search for the @, and get a pair of iterators forming a range which begins at the @ and ends at the next white space character (or end of the string). Then just pass the iterators to std::string::replace() to do the actual sub-string replacement. For example: std::string s = "some string with ...
1,896,830
1,896,864
Why should I use the "using" keyword to access my base class method?
I wrote the below code in order to explain my issue. If I comment the line 11 (with the keyword "using"), the compiler does not compile the file and displays this error: invalid conversion from 'char' to 'const char*'. It seems to not see the method void action(char) of the Parent class in the Son class. Why the compi...
The action declared in the derived class hides the action declared in the base class. If you use action on a Son object the compiler will search in the methods declared in Son, find one called action, and use that. It won't go on to search in the base class's methods, since it already found a matching name. Then that m...
1,896,833
1,896,881
linking assembly and c problem
Trying to understand how to link a function that is defined in a struct, the function is in the assembly code, and am trying to call it from c. I think am missing a step cause when I call the function, I get an unresolved external symbol... ;Assembly.asm .686p .mmx .xmm .model flat include Definitions.inc .code ?Ini...
Your assembly code defines a function whose decorated name decodes to public: static void __fastcall Foo::InitializeCurrentCpu(struct Fee *) As obtained through the undname.exe utility. Foo::InitializeCurrentCpu() won't be a match for Foo::Initialize(), the name doesn't match. Nor does the calling convention. Write...
1,897,006
1,897,203
Recursive calls when trying to wrap and override the global operator new
I have not programmed C++ for a while and encountered a strange behavior when toying with overloaded global operators new and delete. The essence of the problem seems to be that a wrapper build around the default global new and residing in a separate source file nevertheless calls an operator new overloaded in anothe...
If you read the wording in the standard, what you do to global operator new function when you define your own is called replacement (not overloading and not overriding). Most of the time when people talk about changing the global operator new functionality they use the term "overloading" and refer to new as an "operato...
1,897,026
1,898,361
Task Execution Framework for VC++?
Does anyone know of a Java ExecutorService equivlent in VC++ 2008? What I want is a framework which I can pass tasks to fixed size thread pool. The framework should manage the thread pool itself (i.e. creation and destruction of threads).
Vista has a new thread pool API (in addition to existing, rather spartan thread pool API windows has had for a while): http://msdn.microsoft.com/en-us/library/ms686766%28VS.85%29.aspx . This API is not bound to any specific version of MSVC/VS but of course to use the new stuff you need to have Vista/Server 2008 or bett...
1,897,030
1,898,745
Tile sizing algorithm
I'm making a tile game in c++. Right now when the game loads all the tiles place themselves based on: tilesize -> they are squares so this is width and height tile_count_x tile_count_y I have the following variables: desktop_width desktop_height game_window_width game_window_height tile_count_x tile_count_y Based on th...
Here is how I solved it... //WINDOW SIZE SETUP //choose the smaller TILE_SIZE if (DESKTOP_WIDTH / TILE_COUNT_X > DESKTOP_HEIGHT / TILE_COUNT_Y) { TILE_SIZE = DESKTOP_HEIGHT / TILE_COUNT_Y; } else { TILE_SIZE = DESKTOP_WIDTH / TILE_COUNT...
1,897,184
1,897,394
static variable initialisation code never gets called
I've got an application that's using a static library I made. One .cpp file in the library has a static variable declaration, whose ctor calls a function on a singleton that does something- e.g. adds a string. Now when I use that library from the application, my singleton doesn't seem to contain any traces of the stri...
If you have an object in a static library that is not EXPLICITLY used in the application. Then the linker will not pull that object from the lib into the application. There is a big difference between static and dynamic libraries. Dynamic Library: At compile time nothing is pulled from the dynamic library. Extra code i...
1,897,261
1,902,688
C++ Boost: Split String
How can I split a string with Boost with a regex AND have the delimiter included in the result list? for example, if I have the string "1d2" and my regex is "[a-z]" I want the results in a vector with (1, d, 2) I have: std::string expression = "1d2"; boost::regex re("[a-z]"); boost::sregex_token_iterator i (expression....
I think you cannot directly extract the delimiters using boost::regex. You can, however, extract the position where the regex is found in your string: std::string expression = "1a234bc"; boost::regex re("[a-z]"); boost::sregex_iterator i( expression.begin (), expression.end (), re); boost::sregex_iterat...
1,897,301
1,897,499
Vectored Exception Handling During StackOverflowException
If I've registered my very own vectored exception handler (VEH) and a StackOverflow exception had occurred in my process, when I'll reach to the VEH, will I'll be able to allocate more memory on the stack? will the allocation cause me to override some other memory? what will happen? I know that in .Net this is why the ...
In the case of a stack overflow, you'll have a tiny bit of stack to work with. It's enough stack to start a new thread, which will have an entirely new stack. From there, you can do whatever you need to do before terminating. You cannot recover from a stack overflow, it would involve unwinding the stack, but your entir...
1,897,675
1,897,701
Overriding multiple inherited templated functions with specialized versions
Okay, sample code first; this is my attempt at communicating what it is that I'm trying to do, although it doesn't compile: #include <iostream> template <class T> class Base { public: virtual void my_callback() = 0; }; class Derived1 : public Base<int> , public Base<float> { public: void my_callback<i...
Yes, you can make this work: #include <iostream> using namespace std; template <class T> class Base { public: virtual void my_callback() = 0; }; class Derived1 : public Base<int>, public Base<float> { public: void Base<int>::my_callback() { cout << "Int callback for Derived1.\n"; } void Base<float>::my_ca...
1,897,821
1,897,845
Performance of C++ Operators
Is there any sort of performance difference between the arithmetic operators in c++, or do they all run equally fast? E.g. is "++" faster than "+=1"? What about "+=10000"? Does it make a significant difference if the numbers are floats instead of integers? Does "*" take appreciably longer than "+"? I tried performing 1...
No, no, yes*, yes*, respectively. * but do you really care? EDIT: to give some kind of idea with a modern processor, you may be able to do 200 integer additions in the time it takes to make one memory access, and only 50 integer multiplications. If you think about it, you're still going to be bound by the memory access...
1,897,844
1,897,888
C++ templates and ambiguity problem
I have a subset of a pointer class that look like: template <typename T> struct Pointer { Pointer(); Pointer(T *const x); Pointer(const Pointer &x); template <typename t> Pointer(const Pointer<t> &x); operator T *() const; }; The goal of the last constructor is to allow to pass a Pointer...
The cure for your problem is called SFINAE (substitution failure is not an error) #include "boost/type_traits/is_convertible.hpp" #include "boost/utility/enable_if.hpp" template<typename T> class Pointer { ... template<typename U> Pointer(const Pointer<U> &x, typename boost::enable_if< boost::i...
1,897,860
1,902,525
Parsing the map file?
I am looking to use the map file to resolve addresses that I get from the exe. Is there a library for parsing it or a more easier to parse format?
The primary issue is that the format of map files varies with compiler vendors and there are too many compiler vendors out there for us to guess which one you are using. BTW, there is no standard format for map files; as there is no requirement for one. I look at the layout of the map file and write my own search pr...
1,897,940
1,897,979
In what ways do C++ exceptions slow down code when there are no exceptions thown?
I have read that there is some overhead to using C++ exceptions for exception handling as opposed to, say, checking return values. I'm only talking about overhead that is incurred when no exception is thrown. I'm also assuming that you would need to implement the code that actually checks the return value and does the ...
There is a cost associated with exception handling on some platforms and with some compilers. Namely, Visual Studio, when building a 32-bit target, will register a handler in every function that has local variables with non-trivial destructor. Basically, it sets up a try/finally handler. The other technique, employed b...
1,898,212
1,898,255
Convert a vector<unsigned char> to vector<unsigned short>
I'm getting data from a binary file, reading from file and writing in a vector of unsigned char. I can't edit it, because I'm using a external library. But the data that I'm reading from file is a 16 bits image, and I'd like to put the data in a vector of unsigned short Maybe I can do a cast for it? Rgds.
A generic approach (not bullet proof): #include <vector> #include <iostream> #include <iterator> #include <algorithm> typedef unsigned char u8; typedef unsigned short u16; u16 combine_two_bytes(u8 a, u8 b) { return a | (b << 8); } template<typename InIter, typename OutIter, typename InT, typename OutT> void comb...
1,898,284
1,898,302
Declare default parameter circular reference without pointers?
Is there any way to declare these classes in a header file without indirection? // Forwards declaration of B class B; class A { public: // Default parameter referring to B. May return its parameter const B& func(const B& b = B()); }; class B { public: // B ctors B() {} B(const B&) {} // B ha...
Instead of a default parameter declare two overloads, one that takes a B by reference and one that takes no parameter. In the one that takes no parameter, call the other with B(), which will work because that method can be defined after B is defined. ... void func(); void func(const B& b); }; class B... void...
1,898,374
1,898,404
Does the JVM create a mutex for every object in order to implement the 'synchronized' keyword? If not, how?
As a C++ programmer becoming more familiar with Java, it's a little odd to me to see language level support for locking on arbitrary objects without any kind of declaration that the object supports such locking. Creating mutexes for every object seems like a heavy cost to be automatically opted into. Besides memory usa...
Speaking as someone who has looked at the way that some JVMs implement locks ... The normal approach is to start out with a couple of reserved bits in the object's header word. If the object is never locked, or if it is locked but there is no contention it stays that way. If and when contention occurs on a locked obj...
1,898,524
1,898,556
Difference between pointer to a reference and reference to a pointer
What is the difference between pointer to a reference, reference to a pointer and pointer to a pointer in C++? Where should one be preferred over the other?
First, a reference to a pointer is like a reference to any other variable: void fun(int*& ref_to_ptr) { ref_to_ptr = 0; // set the "passed" pointer to 0 // if the pointer is not passed by ref, // then only the copy(parameter) you received is set to 0, // but the original pointer(outside the function) is...
1,898,729
1,898,979
Common algorithm for std::list and std::map?
I have a class of interest (call it X). I have a std::list<X*> (call it L). I have a function (call it F). F(L) returns a subset of L (a std::list<X*>) according to an algorithm that examines the internal state of each X in the list. I'm adding to my application a std::map<int,X*> (call it M), and I need to define F(...
First, all but the condition for both can be done with std::remove_copy_if. Despite the name, remove_copy_if, doesn't remove anything from the original collection. I think people would understand it more easily if it was called something like filtered_copy. It copies elements from one collection to another. For each el...
1,898,837
1,898,849
#include <FreeImage.h> not found
I have compiled FreeImage from source and installed it. When I run sudo make install in installs the following files on my system /usr/local/include/FreeImage.h /usr/local/lib/libfreeimage-3.10.0.dylib /usr/local/lib/libfreeimage.a However in my C++ program it says error file not found when I do this: #include <FreeIm...
You don't want those directories in your /etc/paths file. That files lists the directories where the shell searches for executables. Try: $ CFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" make $ sudo make install You might need to add /usr/local/lib to your DYLD_LIBRARY_PATH to make sure your executable runs...
1,898,920
1,898,960
How might I overload the "new" operator to allocate memory from a secondary memory device?
I am looking for a syntax to allocate memory from a secondary memory device and not from the default heap. How can i implement it? Using malloc() would by default take it from heap... Surely there must be another way!
#include <new> void* operator new(std::size_t size) throw(std::bad_alloc) { while (true) { void* result = allocate_from_some_other_source(size); if (result) return result; std::new_handler nh = std::set_new_handler(0); std::set_new_handler(nh); // put it back // this is clumsy, I know, but ther...
1,899,037
1,899,551
Calling a member function using boost::lambda
I am learning the boost::lambda library and for that I wrote this sample code to convert an vector<A> into vector<int> by extracting the value from A object. class A { public: A(int n) : m_n(n){} int get() const {return m_n;} private: int m_n; }; int _tmain(int argc, _TCHAR* argv[]) { using namespac...
I don't think what you're trying to do is possible. for_each applies function to each element in the range, but you are trying to call two member functions and you'll have to bind them both. I think your code is the best you can do when using for_each. Lambda documentation looks very complete to me, but there is no exa...
1,899,056
1,899,198
Get pContext in Try/Catch handler?
When an exception happens, as you know, it passes pContext to the SEH. Is there anyways to access the pContext in a Try/Catch? I guess I could have the exception class grab it when being initiated but that would only work for that class and not for every exception.
Hard to know what you're looking for... THE Guide for SEH: http://www.microsoft.com/msj/0197/Exception/Exception.aspx Have a look to that as well: http://www.programmingunlimited.net/siteexec/content.cgi?page=mingw-seh http://msdn.microsoft.com/en-us/library/swezty51(VS.80).aspx Note: take care depending on the versio...
1,899,091
1,899,255
How to find memory leaks in source code
If it is known that an application leaks memory (when executed), what are the various ways to locate such memory leak bugs in the source code of the application. I know of certain parsers/tools (which probably do static analysis of the code) which can be used here but are there any other ways/techniques to do that, spe...
There's valgrind and probably other great tools out there. But I'll tell you what I do, that works very well for me, given that many times I code in environments where you can't run valgrind: Be sure to pair each allocation with a deallocation. I always count news or mallocs and search for the delete or free. If in C...
1,899,105
1,899,135
Difference in behavior when returning a local reference or pointer
#include <iostream.h> using namespace std; class A { public: virtual char* func()=0; }; class B :public A { public: void show() { char * a; a = func(); cout << "The First Character of string is " << *a; } char * func(); }; char* B::func() { cout << "In B" << endl; char x[] = "Str...
When you do something like: char *f(){ return "static string"; } You're returning the address of a string literal, but that string literal is not local to the function. Rather, it is statically allocated, so returning it gives well-defined results (i.e. the string continues to exist after the function exits, so it wor...
1,899,250
1,899,260
Need Help for C++ Code Dissection at /*=NULL*/
Could you tell me the meaning of /*=NULL*/ below? CMyCla::CMyCla(CWnd* pParent /*=NULL*/) : CDialog(CCycleTimes::IDD, pParent) { // Some code here } And btw, i copied the same line. Commented successfully as the syte below // CMyCla::CMyCla(CWnd* pParent /*=NULL*/) // : CDialog(CCycleTimes::IDD, pParent) Oth...
Most likely in the class declaration the default value for that parameter is specified: class CMyCla { public: CMyCla(CWnd* pParent =NULL); }; now in the implementation of CMyCla::CMyCla() redefining the default value for the parameter is not allowed, but the author perhaps wanted to remind that there is the defau...
1,899,363
1,899,433
Most efficient method to parse small, specific arguments
I have a command line application that needs to support arguments of the following brand: all: return everything search: return the first match to search all*search: return everything matching search X*search: return the first X matches to search search#Y: return the Yth match to search Where search can be either a s...
The answer mostly depends on a balance between how much coding you want to do and how much libraries you want to depend on - if your application can depend on other libraries, you can use any of the many regular expression libraries - e.g. POSIX regex which comes with all Linux/Unix flavors. OR If you just want those s...
1,899,373
1,899,390
How do compilers know where to find #include <stdio.h>?
I am wondering how compilers on Mac OS X, Windows and Linux know where to find the C header files. Specifically I am wondering how it knows where to find the #include with the <> brackets. #include "/Users/Brock/Desktop/Myfile.h" // absolute reference #include <stdio.h> // system relative ref...
When the compiler is built, it knows about a few standard locations to look for header file. Some of them are independent of where the compiler is installed (such as /usr/include, /usr/local/include, etc.) and some of the are based on where the compiler is installed (which for gcc, is controlled by the --prefix option...
1,899,393
1,900,171
Using boost::bind output as an array subscript
How do I get boost::bind to work with array subscripts? Here's what I'm trying to achieve. Please advice. [servenail: C++Progs]$ g++ -v Reading specs from /usr/lib/gcc/i386-redhat-linux/3.4.6/specs Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr /share/info --enable-shared --enable-...
As Charles has explained, boost::bind returns a function object and not an integer. The function object will be evaluated for each member. A little helper struct will solve the problem: struct get_nth { template<class T, size_t N> T& operator()( T (&a)[N], int nIndex ) const { assert(0<=nIndex && nIndex...
1,899,564
1,899,623
a C++ hash map that preserves the order of insertion
I have the following code: #include <iostream> #include "boost/unordered_map.hpp" using namespace std; using namespace boost; int main() { typedef unordered_map<int, int> Map; typedef Map::const_iterator It; Map m; m[11] = 0; m[0] = 1; m[21] = 2; for (It it (m.begin()); it!=m.end(); ++...
#include <iostream> #include "boost/unordered_map.hpp" #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/sequenced_index.hpp> using namespace std; using namespace b...
1,900,010
1,900,021
Default argument in a function [C++]
I tried to do something like this: int& g(int& number = 0) { //maybe do something with number return number; } but it doesn't work. It has to be passed by reference. Thank you for any help. P.S. I think that "Related Questions" appearing once you type Title is a good idea, but I also think that they should be disp...
If you really want to do this: make the reference const, so that a temporary can be bound to it put the default in the function declaration, not the definition For example: // header const int & g( const int & number = 0 ); // implementation const int & g( const int & number ) { //maybe do something with number ...
1,900,160
1,900,313
Losing whitespace around escaped symbols in CDATA using Expat XML parser in C++
I'm using XML to send project information between applications. One of the pieces of information is the project description. So I have: <ProjectDescription>Test &amp; spaces around&amp;some &amp; amps!</ProjectDescription> Or: "Test & spaces around&some & amps!" <-- GOOD! When I then use Expat to parse it, my data...
I have just run a test with my own library that uses expat. My handler looks like this, with debug statements to display what is going on: void CharDataHandler( void * parser, const XML_Char *s, int len ) { std::cerr << "[" << s << "]\n"; std::cerr << len << "\n"; ...
1,900,665
1,900,672
C++ compiler differences ( VS2008 and g++)
I tried compiling the following code in Linux and VS 2008: #include <iostream> // this line has a ".h" string attached to the iostream string in the linux version of the code using namespace std; // this line is commented in the linux version of the code void main() { int a=100; char arr[a]; arr[0]='a'; cout...
This is a C99 feature: char arr[a]; // VLA: Variable Length Arrays (C99) but not C++! GCC supports many features from C99, but VC doesn't and I think it won't in the near future because they are concentrating on C++ more and more. Anyway, you could just change the declaration to: const int a=100; // OK the size is c...
1,900,756
1,901,498
How do you convert from a nsACString to a LPCWSTR?
I'm making a firefox extension (nsACString is from mozilla) but LoadLibrary expects a LPCWSTR. I googled a few options but nothing worked. Sort of out of my depth with strings so any references would also be appreciated.
It depends whether your nsACString (which I'll call str) holds ASCII or UTF-8 data: ASCII std::vector<WCHAR> wide(str.Length()+1); std::copy(str.beginReading(), str.endReading(), wide.begin()); // I don't know whether nsACString has a terminating NUL, best to be sure wide[str.Length()] = 0; LPCWSTR newstr = &wide[0]; ...
1,900,802
1,900,815
Where does the C++ compiler start?
If you have a c++ project with several source files and you hit compile, which file does the compiler start with? I am asking cause I am having some #include-dependency issues on a library. Compiler would be: VC2003.
It should not be order-dependent. The only relevant steps are: Each compilation unit includes what it depends on, and should be compilable individually. This means, first, that each CPP file includes all the headers it depends on; and second, that each header should in turn include what it needs so that it can compile...