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
572,979
572,992
Howto create software package in Unix/Linux?
How can we create a software package, so that after extracting our software tar ball user can do the typical steps? $ gunzip < mycode.tar.gz | tar xvf - $ ./configure $ make $ make install
An alternative to the hard to understand GNU/Autools is CMake. http://www.cmake.org/cmake/help/examples.html e.g. KDE is using it.
573,275
573,424
Python C-API Object Allocation
I want to use the new and delete operators for creating and destroying my objects. The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the object and delete which destructs and deallocates the object. Which of the python tp_* methods do I need to provide and what must they do? Also I want to be able to create the object directly in c++ eg "PyObject *obj = new MyExtensionObject(args);" Will I also need to overload the new operator in some way to support this? I also would like to be able to subclass my extension types in python, is there anything special I need to do to support this? I'm using python 3.0.1. EDIT: ok, tp_init seems to make objects a bit too mutable for what I'm doing (eg take a Texture object, changing the contents after creation is fine, but change fundamental aspects of it such as, size, bitdept, etc will break lots of existing c++ stuff that assumes those sort of things are fixed). If I dont implement it will it simply stop people calling __init__ AFTER its constructed (or at least ignore the call, like tuple does). Or should I have some flag that throws an exception or somthing if tp_init is called more than once on the same object? Apart from that I think ive got most of the rest sorted. extern "C" { //creation + destruction PyObject* global_alloc(PyTypeObject *type, Py_ssize_t items) { return (PyObject*)new char[type->tp_basicsize + items*type->tp_itemsize]; } void global_free(void *mem) { delete[] (char*)mem; } } template<class T> class ExtensionType { PyTypeObject *t; ExtensionType() { t = new PyTypeObject();//not sure on this one, what is the "correct" way to create an empty type object memset((void*)t, 0, sizeof(PyTypeObject)); static PyVarObject init = {PyObject_HEAD_INIT, 0}; *((PyObject*)t) = init; t->tp_basicsize = sizeof(T); t->tp_itemsize = 0; t->tp_name = "unknown"; t->tp_alloc = (allocfunc) global_alloc; t->tp_free = (freefunc) global_free; t->tp_new = (newfunc) T::obj_new; t->tp_dealloc = (destructor)T::obj_dealloc; ... } ...bunch of methods for changing stuff... PyObject *Finalise() { ... } }; template <class T> PyObjectExtension : public PyObject { ... extern "C" static PyObject* obj_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { void *mem = (void*)subtype->tp_alloc(subtype, 0); return (PyObject*)new(mem) T(args, kwds) } extern "C" static void obj_dealloc(PyObject *obj) { ~T(); obj->ob_type->tp_free(obj);//most of the time this is global_free(obj) } ... }; class MyObject : PyObjectExtension<MyObject> { public: static PyObject* InitType() { ExtensionType<MyObject> extType(); ...sets other stuff... return extType.Finalise(); } ... };
The documentation for these is at http://docs.python.org/3.0/c-api/typeobj.html and http://docs.python.org/3.0/extending/newtypes.html describes how to make your own type. tp_alloc does the low-level memory allocation for the instance. This is equivalent to malloc(), plus initialize the refcnt to 1. Python has it's own allocator, PyType_GenericAlloc, but a type can implement a specialized allocator. tp_new is the same as Python's __new__. It's usually used for immutable objects where the data is stored in the instance itself, as compared to a pointer to data. For example, strings and tuples store their data in the instance, instead of using a char * or a PyTuple *. For this case, tp_new figures out how much memory is needed, based on the input parameters, and calls tp_alloc to get the memory, then initializes the essential fields. tp_new does not need to call tp_alloc. It can for example return a cached object. tp_init is the same as Python's __init__. Most of your initialization should be in this function. The distinction between __new__ and __init__ is called two-stage initialization, or two-phase initialization. You say "c++ just has new" but that's not correct. tp_alloc corresponds a custom arena allocator in C++, __new__ corresponds to a custom type allocator (a factory function), and __init__ is more like the constructor. That last link discusses more about the parallels between C++ and Python style. Also read http://www.python.org/download/releases/2.2/descrintro/ for details about how __new__ and __init__ interact. You write that you want to "create the object directly in c++". That's rather difficult because at the least you'll have to convert any Python exceptions that occurred during object instantiation into a C++ exception. You might try looking at Boost::Python for some help with this task. Or you can use a two-phase initialization. ;)
573,294
573,345
When to use reinterpret_cast?
I am little confused with the applicability of reinterpret_cast vs static_cast. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word static. This is the cast the C++ compiler uses internally for implicit casts also. reinterpret_casts are applicable in two scenarios: convert integer types to pointer types and vice versa convert one pointer type to another. The general idea I get is this is unportable and should be avoided. Where I am a little confused is one usage which I need, I am calling C++ from C and the C code needs to hold on to the C++ object so basically it holds a void*. What cast should be used to convert between the void * and the Class type? I have seen usage of both static_cast and reinterpret_cast? Though from what I have been reading it appears static is better as the cast can happen at compile time? Though it says to use reinterpret_cast to convert from one pointer type to another?
The C++ standard guarantees the following: static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address: int* a = new int(); void* b = static_cast<void*>(a); int* c = static_cast<int*>(b); reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following: int* a = new int(); void* b = reinterpret_cast<void*>(a); int* c = reinterpret_cast<int*>(b); a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.) For casting to and from void*, static_cast should be preferred.
573,430
573,496
Include header path change from Windows to Linux
I'm porting an application written in C++ from Windows to Linux. I have a problem with the header files path. Windows uses \ and Linux uses /. I am finding it cumbersome to change this in each and every source and header file. Is there some work around?
Always use forward slashes in #include paths. It is the compiler's job to map the path to whatever slash/directory scheme the underlying OS supports.
573,540
574,987
How to reference Resources folder in code
I'm porting a c++ Qt application from Windows to OSX and cannot wrap my head around the .app bundle concept. I hope someone can help me understand. My executable lives here: MyProgram.app/Content/MacOS/MyProgram.exe My resource folder lives here: MyProgram.app/Content/Resources/ In my code I use a relative path to reference items in the resource folder: "../Resources/something.png" This works great if I open the .app bundle and run the .exe directly. But that is not how the .app bundle is meant to work. The user is supposed to click on the .app bundle in the Finder to run the program. But in that case my relative path no longer works, and this is what I don't understand. Does anyone understand my problem and how I can fix it?
QApplication::applicationDirPath() http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath
573,649
575,428
Excel automation. How to copy more than one cell?
For instance: //omitted vector<_bstr_t> cellData; Excel::_WorksheetPtr pSheet = application->ActiveSheet; Excel::RangePtr pRange = application->Cells; _bstr_t cellValue = pRange->Item[1][1]; //single cell cellData.push_back(cellValue); //omitted Without: MFC ATL Question: How to copy, multiple cells, for instance A1:B1, into the vector? Is there a more appropriate method, instead of Item?
I've never done any Excel automation using C++, but if it works similarly as VBA macros, the WorkSheet class should have a Range property that returns a range of cells in the sheet. You can specify what range you want either by giving two cells id, or a string representing the range. Code in pseudo VBA: Dim range As Range Set range = ActiveSheet.Range("B12:D34") Set range = ActiveSheet.Range("B12", "D34") Set range = ActiveSheet.Range("B12", ActivSheet.Range("D34")) ... See MSDN for more information about the Range class.
574,060
574,088
Declare a vector of elements of struct C,and have the number of elements be i (a input of type int)
Please look at this code (and forgive the lack of knowledge). It outputs errors that I couldn't solve. I need to declare a vector of elements of struct C,but I need the number of elements be i (a input of type int). I also tried others approaches but in all of them I received an error (cannot convert C to int,etc). How can I do this? # include < iostream > using std::cout; using std::cin; using std::endl; # include < vector > using std::vector; struct C{ int cor; vector<int>cores; }; void LerVector( vector< C> &array ) ; int main () { int n; bool done=false; bool don=false; vector<C>cidade; int i; while(!done){ cout<<"Entre o número de cidades "<<endl; cin>>n; if(n>500) { cout<<endl; cout<<"O número máximo é 500"<<endl; } else done=true; } n--; while(!don){ cout<<"Entre o número de confederações"<<endl; cin>>i; if(i>100){ cout<<endl; cout<<"Número máximo de 100 cidades"<<endl; } else { LerVector( cidade) ; don=true; } } cin.get(); return 0; } //resolve... void LerVector( vector< C> &array ) { for ( size_t i = 0; i < array.size(); i++ ) cin>>array[i]; } // end function inputVector
Let's try with an explanation :) cin >> array[i]; That tries to extract from cin into an object of struct C. Well, so it needs an operator>> that actually does that work: istream & operator>>(istream &is, C &c) { is >> c.cor; // or into whatever member return is; } In addition, as another one mentioned, you have to actually add the elements to the vector first: while(!don){ cout<<"Entre o número de confederações"<<endl; .... } else { cidade.resize(i); // resize to i elements LerVector(cidade); don = true; } For the next time, please format the text (correct indent it). It was hard for me to step through it :)
574,159
574,172
What is a buffer overflow and how do I cause one?
I have heard about a buffer overflow and I would like to know how to cause one. Can someone show me a small buffer overflow example? New(And what they are used for?)
A buffer overflow is basically when a crafted section (or buffer) of memory is written outside of its intended bounds. If an attacker can manage to make this happen from outside of a program it can cause security problems as it could potentially allow them to manipulate arbitrary memory locations, although many modern operating systems protect against the worst cases of this. While both reading and writing outside of the intended bounds are generally considered a bad idea, the term "buffer overflow" is generally reserved for writing outside the bounds, as this can cause an attacker to easily modify the way your code runs. There is a good article on Wikipedia about buffer overflows and the various ways they can be used for exploits. In terms of how you could program one yourself, it would be a simple matter of: char a[4]; strcpy(a,"a string longer than 4 characters"); // write past end of buffer (buffer overflow) printf("%s\n",a[6]); // read past end of buffer (also not a good idea) Whether that compiles and what happens when it runs would probably depend on your operating system and compiler.
574,177
574,183
Styles of buttons on win32 C++
i know there are some styles you can put on a button in C++ win32 exa. like BS_DEFPUSHBUTTON BS_RADIOBUTTON but i do not know all of them and also how would i go about making a user drawn button
You can find the reference of all button styles on MSDN (as usual). And an overview of the Button control in general. To create an owner drawn button, you need to specify the BS_OWNERDRAW flag and pocess the WM_DRAWITEM notification in the button parent window.
574,206
574,222
Making a groupbox button win32 C++
i have a button that is a rectangle how would i put words in it i want to make so ican click the word and it starts the progrma i know ShellExecute the style is BS_GROUPBOX
If you have more than one program you want to start, you need a button per program you want to start. To start you external progrma, in the button parent window, you need to process the WM_COMMAND message with the BN_CLICKED notification. To set the text of the button, you need to send WM_SETTEXT message to the button with the text you want shown. Btw, BS_GROUPBOX is used for creating the rectangle around radio buttons. This style is not going to work for your scenario. If you want an alternative to using multiple Button controls, you can use a Toolbar. In fact, it seems to me that a toolbar would be a better control for you. You can read more about creating a toolbar.
574,285
575,181
Checking existence of a txt file with C++ code
First of all, i'd to establish that i do have the text file in my Folders directory. Im using visual studio and it is where my source code is compiling. The code below should demonstate why its not working. In visual studio. int main( const int argc, const char **argv ) { char usrMenuOption; const char *cFileName = argv[ 1 ]; checkName( cFileName ); // supplying the checkName function with contents of argv[1] usrMenuOption = getUsrOption(); // calling another function fgetc(stdin); return 0; } ifstream *openInputFile( const char *cFileName ) { // this function might be the pronblem. ifstream *inFile; inFile = new ifstream; inFile->open( cFileName, ios::in ); return inFile; } bool checkName( const char *cFileName ) { // it works fine if i use a regular ifstream obj and not the one from the function ifstream *inFile; inFile = openInputFile( cFileName ); inFile->open( cFileName, ios::in ); if ( inFile->good() ) { return true; } else { cout << '"' << cFileName << '"' << ": File does not exist! " << endl; return false; } } It does work if i use a non-pointer object for the ifstream. however i need to open all of my input files this way, using the function i made. I'm a little confused because i did not have this issue compiling in dev-cpp
I always check ifs.is_open() where ifs is a ifstream.
574,543
574,554
Writing ALL program output to a txt file in C++
I need to write all my program output to a text file. I believe it's done this way, sOutFile << stdout; where sOutFile is the ofstream object that creates the file like this: sOutFile("CreateAFile.txt" ); // CreateAFile.txt is created. When I insert the stdout into the sOutFile object, I get some code which seems to resemble octal [hexadecimal] code or an address of some kind in the text file that I created. 0x77c5fca0 But what's confusing to me is that in my program I use cout several times. Mostly just literal statement. If I'm not mistaken that is the program output. If this code is an address, would it contain all of my output? Could I read it back in to the program and find out that way? What can I do to get ALL of my program output written to a text file?
This is a duplicate of: this question You can redirect stdout, stderr and stdin using std::freopen. From the above link: /* freopen example: redirecting stdout */ #include <stdio.h> int main () { freopen ("myfile.txt","w",stdout); printf ("This sentence is redirected to a file."); fclose (stdout); return 0; } You can also run your program via command prompt like so: a.exe > stdout.txt 2> stderr.txt
574,801
574,810
Call C++ library in C#
I have a lot of libraries written in C++. I want to call these libraries from C#, however, I have met many problems. I want to know if there is a book or guideline to tell me how to do that.
DllImport - http://msdn.microsoft.com/en-us/library/aa984739(VS.71).aspx Wrapper class - http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/67cc9eea-a4fe-48bd-b8d5-f3c8051ba896
574,973
574,980
Exporting a class from a C++ dll?
How do I expose a class from a dll ? The application importing the dll should be able to create the objects of the class and also he should be able to call into the member functions of the class . Is it similar to exposing C type functions using __declspec(dllexport) ? And also when I built the dll ( which only contains class definition in a header file and its member function definitions in a cpp file ) , no corresponding lib file is created .
Is it similar to exposing C type functions using _declspec(dllexport) ? Yes. And the __declspec can be applied to the class. no corresponding lib file is created IIRC this is the default, but you can override default linker options.
575,455
576,031
Simplest way to move an array from C++ to C#, modify it, and pass it back to C++
I have a C# class library that contains methods that need to be used with an external application. Unfortunately this external application only supports external APIs in C/C++. Now I've managed to get a very simple COM example working between a C++ dll and a C# DLL, but I am stuck on how I can move around array data. This is what I've got so far, just as a little example I found on the web of communicating via COM: DLL_EXPORT(void) runAddTest(int add1,long *result) { // Initialize COM. HRESULT hr = CoInitialize(NULL); // Create the interface pointer. IUnitModelPtr pIUnit(__uuidof(UnitModel)); long lResult = 0; // Call the Add method. pIUnit->Add(5, 10, &lResult); *result = lResult; // Uninitialize COM. CoUninitialize(); } This works fine to call the add method in my C# class. How can I modify this to take and return an array of doubles? (ill also need to do it with strings down the line). I need to take an unmanaged array , pass this array to a C# class for some calculations, and then pass it back the results to the array reference specified in the original function call (unmanaged) C++. I'll need to expose a function like this: *calcin - reference to array of doubles *calcOut - reference to array of doubles numIN - value of size of input array DLL_EXPORT(void) doCalc(double *calcIn, int numIn, double *calcOut) { //pass the calcIn array to C# class for the calcuations //get the values back from my C# class //put the values from the C# class //into the array ref specified by the *calcOut reference } I think I can use a C++\CLI DLL for the external application so if this is easier than straight COM then i'll be willing to look at that. Please be gentle as I am primarily a C# developer but have been thrown in the deep end of Interop and C++ .
I experimented with this a while ago but have unfortunately forgotten how it all fitted together... for my purpose it turned out to be woefully slow so I cut out the C# and went back to all C++. When you say you're primarily a C# developer I hope you understand pointers because if you don't there's no way to be gentle. Passing arrays basically came down to using CoTaskMemAlloc family of functions on the C++ side (http://msdn.microsoft.com/en-us/library/ms692727(VS.85).aspx) and the Marshal class on the C# side (http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx - which has methods like AllocCoTaskMem). For C# I ended up with a utility class: public class serviceUtils { unsafe public long stringToCoTaskPtr( ref str thestring ) { return (long)Marshal.StringToCoTaskMemAnsi(thestring.theString).ToPointer();//TODO : what errors occur from here? handle them } unsafe public long bytesToCoTaskPtr( ref bytes thebytes, ref short byteCnt) { byteCnt = (short)thebytes.theArray.Length; IntPtr tmpptr = new IntPtr(); tmpptr = Marshal.AllocCoTaskMem(byteCnt); Marshal.Copy(thebytes.theArray, 0, tmpptr, byteCnt); return (long)tmpptr.ToPointer(); } public void freeCoTaskMemPtr(long ptr) { Marshal.FreeCoTaskMem(new IntPtr(ptr));//TODO : errors from here? } public string coTaskPtrToString(long theptr) { return Marshal.PtrToStringAnsi(new IntPtr(theptr)); } public byte[] coTaskPtrToBytes(long theptr, short thelen) { byte[] tmpbytes = new byte[thelen]; Marshal.Copy(new IntPtr(theptr), tmpbytes, 0, thelen); return tmpbytes; } } Just to throw some more code at you: this c++ #import "..\COMClient\bin\Debug\COMClient.tlb" named_guids raw_interfaces_only int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(NULL); //Initialize all COM Components COMClient::IComCalculatorPtr pCalc; // CreateInstance parameters HRESULT hRes = pCalc.CreateInstance(COMClient::CLSID_ComCalculator); if (hRes == S_OK) { long size = 5; LPVOID ptr = CoTaskMemAlloc( size ); if( ptr != NULL ) { memcpy( ptr, "12345", size ); short ans = 0; pCalc->changeBytes( (__int64*)&ptr, &size, &ans ); CoTaskMemFree(ptr); } } CoUninitialize (); //DeInitialize all COM Components return 0; } called this c# public short changeBytes(ref long ptr, ref int arraysize) { try { IntPtr interopPtr = new IntPtr(ptr); testservice.ByteArray bytes = new testservice.ByteArray(); byte[] somebytes = new byte[arraysize]; Marshal.Copy(interopPtr, somebytes, 0, arraysize); bytes.theArray = somebytes; CalculatorClient client = generateClient(); client.takeArray(ref bytes); client.Close(); if (arraysize < bytes.theArray.Length) { interopPtr = Marshal.ReAllocCoTaskMem(interopPtr, bytes.theArray.Length);//TODO : throws an exception if fails... deal with it } Marshal.Copy(bytes.theArray, 0, interopPtr, bytes.theArray.Length); ptr = interopPtr.ToInt64(); arraysize = bytes.theArray.Length; //TODO : do we need to free IntPtr? check all code for memory leaks... check for successful allocation } catch(Exception e) { return 3; } return 2; } Sorry, but I don't have the time to work all this out and explain it properly, hopefully this will give you pointers in the right direction, at the very least some things to google. Good Luck PS : I got all the info to write this stuff off the net, so it is out there.
575,695
575,707
Pass more than one argument to CreateThread
Question: How to pass specifically two arguments to CreateThread, when: Argument one, of type SOCKET Argument two, an interface pointer: _COM_SMARTPTR_TYPEDEF(Range, __uuidof(Range)); RangePtr pRange; //pass pRange Suggestions: For interface pointer, using CoMarshalInterThreadInterfaceInStream, accordingly,
create a structure of these two types and pass a pointer to it. This is the standard way of passing data to threads over single pointer.
576,325
576,338
Compiling with operator() under GCC 3.3 Problem in Boost
I have the following snippet: #include <boost/random/lognormal_distribution.hpp> #include <boost/random/lagged_fibonacci.hpp> int main() { const double mean = 0.0; const double sigma = 1.0; boost::lognormal_distribution<double> lognorm_dist(mean, sigma); boost::lagged_fibonacci44497 engine; // the following line give error in GCC 3.3 const double value = lognorm_dist.operator() <boost::lagged_fibonacci44497>((engine)); } It compile fine under i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465) But under: g++ (GCC) 3.3.3 (SuSE Linux) It gave the following error: Mycode.cc:10:error: `operator()' not defined How can I fix the problem?
Why not just lognorm_dist( engine );? Providing "function-like" syntax is the whole point of operator(). That said, lognorm_dist.template operator() <boost::lagged_fibonacci44497>((engine)) should solve your compilation issues if I am not mistaken.
576,396
576,403
Why does strlen() appear to return <void> in the VC++ debugger?
I have a string in C++ of type const char* passed as argument to strlen, but it returns void. it goes like strlen(astruct.string); Thanks.. EDIT: Did some checking, strlen("test"); still gives void.. why? EDIT: Here's the image http://img14.imageshack.us/img14/1808/strlen.png Sorry for being unclear previously. Formatting was not working quite well. Anyway, the confusion was solved by both Evan Teran and Vlad Romascanu. Also take a look at Brian R. Bondy's answer. Thanks. Feel free to close.
Referring to your screen shot: your debugger is displaying <void> for strlen(...) when in fact it should display an error. You cannot call methods and display their results in the debugger watch. The debugger will only display existing variables and data. It cannot invoke arbitrary methods on demand since the methods can alter the state of the program being debugged in ways that were not anticipated by either the author of the code nor by the debugger. What you can do is, in your code, temporarily add: size_t tmp_len = strlen(struc.string); then compile, and add tmp_len to the watch.
576,572
576,580
In need to program an algorithem to be very fast, should I do it as php extension, or some otherway?
Most of my application is written in PHP ((Front and Back ends). There is a part that works too slowly and I will need to rewrite it, probably not in PHP. What will give me the following: 1. Most speed 2. Fastest development 3. Easily maintained. I have in my mind to rewrite this piece of code in CPP as a PHP extension, but may be I am locked on this solution and misses some simpler/better solutions? The algorithm is PorterStemmerAlgorithm on several MB of data each time it is run.
The answer really depends on what kind of process it is. If it is a long running process (at least seconds) then perhaps an external program written in C++ would be super easy. It would not have the complexities of a PHP extension and it's stability would not affect PHP/apache. You could communicate over pipes, shared memory, or the sort... If it is a short running process (measured in ms) then you will most likely need to write a PHP extension. That would allow it to be invoked VERY fast with almost no per-call overhead. Another possibility is a custom server which listens on a Unix Domain Socket and will quickly respond to PHP when PHP asks for information. Then your per-call overhead is basically creating a socket (not bad). The server could be in any language (c, c++, python, erlang, etc...), and the client could be a 50 line PHP class that uses the socket_*() functions. A lot of information needs evaluated before making this decision. PHP does not typically show slowdowns until you get into really tight loops or thousands of repeated function calls. In other words, the overhead of the HTTP request and network delays usually make PHP delays insignificant (unless the above applies) Perhaps there is a better way to write it in PHP? Are you database bound? Is it CPU bound, Network bound, or IO bound? Can the result be cached? Does a library already exist which will do the heavy lifting. By committing to a custom PHP extension, you add significantly to the base of knowledge required to maintain it (even above C++). But it is a great option when necessary. Feel free to update your question with more details, and I'm sure Stack Overflow will be happy to help out.
576,610
2,379,294
Which is better code for converting BSTR parameters to ANSI in C/C++?
So far I've discovered I can convert incoming BSTRs to ANSI in two (of many?) ways, and I'm curious to know whether one is "better" than the other with respect to speed / efficiency etc. The way I've been using for a while is use the USES_CONVERSION and W2A macros, e.g. BSTR __stdcall F(BSTR p1, BSTR p2 ) { USES_CONVERSION; LPSTR sNum1 = W2A( p1 ); LPSTR sNum2 = W2A( p2 ); Recently, however, I came across another technique: BSTR __stdcall F(BSTR p1, BSTR p2 ) { long amt = wcstombs( NULL, p1, 1 ); sNum1 = (char *) malloc( amt ); wcstombs( sNum1, p1, amt ); *(sNum1 + amt) = '\0'; amt = wcstombs( NULL, p2, 1 ); sNum2 = (char *) malloc( amt ); wcstombs( sNum2, p2, amt ); *(sNum2 + amt) = '\0'; Now I grant you, it's wordier, and has two calls to wcstombs but for all I know the USES_CONVERSION and W2A macros may be hiding all sorts of fun and games. Which is the more efficient / faster code? Or, is there another technique I could use that would do the job better?
Note in the approved answer by Nick, which whilst correct shares the same problem there is with the MSDN documentation that describes the macros. The problem is that some of the macros such as the one listed by @Nick - COLE2A, don't actually exist. However further down the MSDN page there is some text that clues you into this fact and leads you to be able to figure out the correct macro! The text is listed in the table under the following text: There are several important differences between the older string conversion macros and the new string conversion classes: In the New ATL 7.0 Conversion Classes column. Which says: OLE is always equivalent to W So the macro in @Nick's example is actually CW2A
576,620
576,629
How do display functions like sprintf convert numbers to strings?
I'm trying to extract the integer and decimal parts of a floating point value, and I seem to be running into some strange rounding problems, due probably to the imprecise way floats are stored. I have some code like this to extract the fractional part: double number = 2.01; int frac = int(floor(number * 100)) % 100; However the result here instead of 1 comes out as 0. This seems to be because the original double actually gets stored as: 2.0099999... However running sprintf seems to get such a conversion correct: char num_string[99]; sprintf(num_string,"%f",number); How is sprintf getting the correct answer while the above method does not?
> However the result here instead of 1 comes out as one. What do you mean? 2.099999... Or, more like 2.00999... As you've noted: int frac = int(floor(number * 100)) % 100; will be: int frac = int(floor(2.00999... * 100)) % 100; = int(floor(200.999...)) % 100; = int(floor(200.999...)) % 100; = int(200) % 100; = 200 % 100; = 0; You may be interested in this. Also, see modf from math.h: double modf(double x, double *intptr) /* Breaks x into fractional and integer parts. */ modf() is a better alternative than doing the juggling yourself.
576,677
576,710
How do I skip reading a line in a file in C++?
The file contains the following data: #10000000 AAA 22.145 21.676 21.588 10 TTT 22.145 21.676 21.588 1 ACC 22.145 21.676 21.588 I tried to skip lines starting with "#" using the following code: #include <iostream> #include <sstream> #include <fstream> #include <string> using namespace std; int main() { while( getline("myfile.txt", qlline)) { stringstream sq(qlline); int tableEntry; sq >> tableEntry; if (tableEntry.find("#") != tableEntry.npos) { continue; } int data = tableEntry; } } But for some reason it gives this error: Mycode.cc:13: error: request for member 'find' in 'tableEntry', which is of non-class type 'int'
Is this more like what you want? #include <iostream> #include <sstream> #include <fstream> #include <string> #include <algorithm> using namespace std; int main() { fstream fin("myfile.txt"); string line; while(getline(fin, line)) { //the following line trims white space from the beginning of the string line.erase(line.begin(), find_if(line.begin(), line.end(), not1(ptr_fun<int, int>(isspace)))); if(line[0] == '#') continue; int data; stringstream(line) >> data; cout << "Data: " << data << endl; } return 0; }
576,767
576,782
Name mangling of c++ classes and its member functions?
Is there no way I could avoid name mangling of C++ classes and its member functions when exposed from a c++ dll. Can't I use a def file mechanism in this regard ?
I think the best way to do this is to provide C wrappers around the C++ library. This was quite popular 10 or more years back when I was programming in C++ but I don't know if it is done any more. Basically, for every class C, for every constructor ctor to be exposed to create an extern "C" CPtr cCtor(....) method that returns an opaque pointer CPtr and for every function func to be exposed you create extern "C" cFunc(CPtr,....) Another approach is to create a CStruct that has member variables of function pointer types, implement them to call the class methods and let the client do all the hard work.
577,006
577,037
Makefiles on windows with g++, linking a library
I've gotten fed up with MSVC++6 and how everyone is always telling me that it's a crappy compiler and such. So now I've decided to try to use vim plus g++ and makefiles. Here's my problem; I have the following makefile: # This is supposed to be a comment.. CC = g++ # The line above sets the compiler in use.. # The next line sets the compilation flags CFLAGS=-c -Wall all: main.exe main.exe: main.o Accel.o $(CC) -o main.exe main.o Accel.o main.o: main.cpp Accel.h $(CC) $(CFLAGS) main.cpp Accel.o: Accel.cpp Accel.h $(CC) $(CFLAGS) Accel.cpp clean: del main.exe *.o This gives an error when trying to make, because I need to link to a windows library called Ws2_32.lib, which is needed by Winsock2.h, which I include in one of my .h files. So how do I do this? I've tried the -l option, but I can't make it work. How does it work with a path that has spaces?
First step: locate the library you are looking for. For me, it's in : C:\Program Files\Microsoft Visual Studio\VC98\Lib Second step, pass that directory with -L : LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib" Third step, pass the name of the library with -l (lowercase L): LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib" -lWs2_32 Then use it: main.exe: main.o Accel.o $(CC) $(LINKFLAGS) -o main.exe main.o Accel.o
577,243
577,334
Is there any reason to use this->
I am programming in C++ for many years, still I have doubt about one thing. In many places in other people code I see something like: void Classx::memberfunction() { this->doSomething(); } If I need to import/use that code, I simply remove the this-> part, and I have never seen anything broken or having some side-effects. void Classx::memberfunction() { doSomething(); } So, do you know of any reason to use such construct? EDIT: Please note that I'm talking about member functions here, not variables. I understand it can be used when you want to make a distinction between a member variable and function parameter. EDIT: apparent duplicate: Are there any reasons not to use "this" ("Self", "Me", ...)?
To guarantee you trigger compiler errors if there is a macro that might be defined with the same name as your member function and you're not certain if it has been reliably undefined. No kidding, I'm pretty sure I've had to do exactly this for that reason!
577,270
577,338
Creating new exception in C++
I have a C++ class and I am trying to run it in Ubuntu: #ifndef WRONGPARAMETEREXCEPTION_H_ #define WRONGPARAMETEREXCEPTION_H_ #include <iostream> #include <exception> #include <string> using namespace std; #pragma once class WrongParameterException: public exception { public: WrongParameterException(char* message): exception(message) {}; virtual ~WrongParameterException() throw() {}; }; #endif when I try to compile it, the compiler gives me this error: WrongParameterException.h: In constructor ‘WrongParameterException::WrongParameterException(char*)’: WrongParameterException.h:14: error: no matching function for call to ‘std::exception::exception(char*&)’ /usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception() /usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&) Can anyone tell me what am I doing wrong? I tried changing the message variable to string or const string or const string& but it didn't help. Here is how I use the new exception that I created from main: try { if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL)) { throw WrongParameterException("Error in the config or commands file"); } } catch(WrongParameterException e) { log.addMsg(e.what()); }
First, #pragma once is the wrong way to go about it, learn about header include guards. Related question on SO explains why using #pragma once is the wrong way to go about it. Wikipedia explains how to use include guards which serve the same purpose without any of the downsides. Second, you are calling the constructor of std::exception with a parameter it does not know, in this case a pointer to a character array. #include <stdexcept> #include <string> class WrongParameterException : public std::runtime_error { public: WrongParameterException(const std::string& message) : std::runtime_error(message) { }; }; Would probably be what you want. For more information on exceptions, check out C++ FAQ Lite article on Exceptions and the exceptions article at cplusplus.com. Good luck!
577,330
12,493,518
MAP file analysis - where's my code size comes from?
I am looking for a tool to simplify analysing a linker map file for a large C++ project (VC6). During maintenance, the binaries grow steadily and I want to figure out where it comes from. I suspect some overzealeous template expansion in a library shared between different DLL's, but jsut browsign the map file doesn't give good clues. Any suggestions?
This is a wonderful compiler generated map file analysis/explorer/viewer tool. Check if you can explore gcc generated map file. amap : A tool to analyze .MAP files produced by 32-bit Visual Studio compiler and report the amount of memory being used by data and code. This app can also read and analyze MAP files produced by the Xbox360, Wii, and PS3 compilers.
577,421
577,442
Is C++ friendship among peers healthy?
Although class friendship is one of the last resorts of C++, does this pattern make sense? class Peer { public: friend class Peer; void GetSecret(const Peer& other) { const std::string& secret = other.GiveSecret(); std::cout << secret << std::endl; } private: const std::string& GiveSecret() const { return "secrety stuff"; } }; int main(int argc, char* argv[]) { Peer peerA; Peer peerB; peerA.GetSecret(peerB); return 0; } Ok the reason for this pattern is because the Peers are all of the same rank, and they need to share knowledge among each other, however this knowledge is secret, because no one but the peers should use it, or the program is no longer valid. One very real example of this is that when one peer is copy-constructed from another peer it needs to access secret information from its source peer, but again there is no reason for anyone else to know about these internals, just the peers.
friend is not necessary in this case. An object of a class can access the private members of any other object of the same type. It should work just fine without the friend declaration.
577,423
577,446
Saving an array value into a double variable
Greetings everyone. Having an issue compiling my script containing the following function. Three errors occur, all on the same line where I set distance += to distances [][]: error C2108: subscript is not of integral type error C2108: subscript is not of integral type error C2297: '+=' : illegal, right operand has type 'double (*)[15]' Assistance would be much appriciated. double S_initial; double distances [15][15]; double order [15]; void Initialize() { double x, y ,z; double distance = 0; for (int i = 0; i <= 14; i++) { x = order [i]; y = order [i + 1]; distance += distances [x][y]; } S_initial = distance; }
Well, the array subscripts x and y are not of an integral type like int, but of type double: double x, y, z; ... distance += distances[x][y]; And something like the 1.46534th element of an array doesn't make sense, so the compiler complains.
577,465
577,468
in C++, can I derive a class from a struct
The question says it all really. Am I allowed derive a class from a struct, or should I create a class that embeds my struct and defines copy constructors and an = operator to move between the two?
In C++ struct is (almost) synonymous to a class (except of different default access level), so yes, you can. struct A { // fields are public by default }; class B: public A { // fields are private by default }; I'm not familiar with MFC, but it looks like an attempt to maintain both C and C++ APIs.
577,622
577,751
How can I index a lot of txt files? (Java/C/C++)
I need to index a lot of text. The search results must give me the name of the files containing the query and all of the positions where the query matched in each file - so, I don't have to load the whole file to find the matching portion. What libraries can you recommend for doing this? update: Lucene has been suggested. Can you give me some info on how should I use Lucene to achieve this? (I have seen examples where the search query returned only the matching files)
I believe the lucene term for what you are looking for is highlighting. Here is a very recent report on Lucene highlighting. You will probably need to store word position information in order to get the snippets you are looking for. The Token API may help.
577,780
577,863
send(), returns Winsock Error 10038
Problem: Call to send(), returns Winsock Error 10038 against socket handle Illustration: acceptedSocket = accept (server, (sockaddr *)&sin, &len); accept(), returns 0 A new thread, is created for each connection send(), (in thread function) returns 10038 Illustration: - in thread function //omitted SOCKET RemoteSocket = (SOCKET) client; //omitted send (RemoteSocket, stringToSpend, strlen(stringToSpend), 0) Suggestions: Possible, race condition? Could use I/O completion ports, but not at this stage
Isn't the problem in the line acceptedSocket = accept (server, (sockaddr *)&sin, &len) == INVALID_SOCKET) You make acceptedSocket the result of the comparison, but you should store the actual socket returned from accept somehow: acceptedSocket = accept (server, (sockaddr *)&sin, &len); isOK= acceptedSocket!=INVALID_SOCKET; Although I'm a bit confused by the unbalanced parentheses in your post, so I may be wrong
577,853
577,980
IDE Module for Hand Drawing?
I'm currently looking for a hand drawing (2D) library/module (that would be like Paint, Paint.Net or Photoshop - but I don't need all the power of Photoshop...) that would allow me to add a drawing module to an IDE application. That application is in it's early design phase : for instance I'm only estimating if I will be able to work on it on my spare time. I'm thinking to use C#/Mono or C++/QT as the IDE framework but it's not decided yet. That application would be open-source. A separate module to handle the drawing part would be a good thing - allowing me to concentrate on the other important feature of the application, instead of implementing it myself. That module would be instantiated by the user to create or edit an image (no need for Photoshop power). That image would then be manipulated by the application (with other data). I've been searching in Google, Sourceforge and code.google.com for hours but couldn't find something like that in C# or C++/QT - only drawing by code libraries. Maybe I'm not searching right... Anyway, any suggestion is welcome.
I think that you will need to create a module for drawing. I have done some drawing utilities using QGraphicsView from Qt >4.3 and it's pretty easy. I will consider it. Good luck! :D
578,021
578,532
Is it possible to statically link Qt::phonon on windows?
Because of the dependency on DirectShow on windows, is it possible to use a static Qt with my application?
If you link Qt statically and want to distribute your application, you will most likely require a commercial license. The LGPL license (using Qt for free) in practice mandates that you link Qt dynamically.
578,217
578,280
Bug in Visual Studio C++ compiler?
This code behaves weird in MS Visual Studio: char *s = "hello"; s[0] = 'a'; printf(s); In release build with optimization turned on it ignores s[0] = 'a' and prints "hello". Without optimization or in debug build it crashes with access violation. Is this behavior is c++ standard compliant or no? In my opinion, compiler should only allow constant references to string literals, i.e. const char *s = "hello"; EDIT: I know why it works like this, I do not understand why I am allowed to make non const reference to read only memory.
The reason why this code is allowed in the first place (rather than requiring the declaration to be of type char const*) is backwards compatibility to old C code. Most modern compilers in strict mode will issue a warning for the above code, though!
578,259
578,838
How to pass and then invoke generic callback functions without causing circular dependency
Couldn't creatively shorten the title :) I have been using a variation of the below solution, however I always wondered if there is a better/cleaner way to implement it. I am looking for non-boost solution. We can, though, look at the implementation of boost and C++0x, as it will soon be relevant. //Notice the use of template template parameter template <template <typename> class Callback> class A { Callback <A> m_func; public: A (Callback <A> func): m_func (func) {} void call () { m_func(*this);} }; template <typename T> struct MYCallback { void operator () (const T&t) {} }; void Test() { typedef A<MYCallback> AType; MYCallback<AType> callback; AType a (callback); a.call (); } Another, a more suncinct way, is to use tr1::function, which will become defuct-to with new standardization: #include <tr1/functional> class A { std::tr1::function <void (const A&)> m_func; public: template <class Callback> A (Callback func) : m_func (func) {} void call () { m_func(*this);} }; template <class T> struct My_callback { void operator () (const T&t) {} }; void Test () { My_callback <A> c; A a (c); a.call (); }
If you're just looking for clean-up advice, I'd suggest making 'My_callback' a normal class, not a class template. There's not obvious need for it to be a template in this case. Instead, make its apply operator templated or fill in A directly if My_callback only deals with A instances: #include <tr1/functional> class A { std::tr1::function <void (const A&)> m_func; public: template <class Callback> A (Callback func) : m_func (func) {} void call () { m_func(*this);} }; struct My_callback { template <class T> void operator () (const T&t) {} }; int main () { My_callback c; A a (c); a.call (); } Otherwise, It looks pretty good as is. Could you be more specific in how you hope to clean it up or simplify it?
578,293
579,004
Are things like "afx_msg" decorators still used by VS/MFC?
I'm working on an MFC program that started way back in the VC6 days. Back then there was a class wizard that used a bunch of decorators and markup in comments to parse class files. For example, it would insert afx_msg in front of message handlers that it maintained. It would mark a block of code with //{{AFX_MSG_MAP(TheApp) and /}}AFX_MSG_MAP comments to help it find the parts of the message map it wanted to handle. AFAIK, this isn't needed anymore. Besides that, there were so many shortcomings with the class wizard that we had to do a lot of manual editing of these managed blocks and we never used it very often anyways. Are there any other reasons to keep using afx_msg and its ilk?
afx_msg still exists but has always been purely informative. A decorator as you put it. It's always been #defined as an empty string. the {{ and }} markers are no longer needed since VS2003: VS is now smart enough to put things in the right place without having to rely on these markers. You'll notice that VS2003+ no longer includes these lines in the projects it creates.
578,304
578,370
How would you shorten this so that action1 and action2 only show up once in code?
if (x() > 10) { if (y > 5) action1(p1, p2, p3, p4); else action2(p1, p2); } else { if (z > 2) action1(p1, p2, p3, p4); else action2(p1, p2); } I real project on mine, action1 and action2 are actually 2-3 lines of code and those functions that are invoked take 6-8 parameters in total, so writing them as a single function doesn't seem right. UPDATE: I forgot to mention this, and now I see many answers just don't work. x() is expensive operation and has side-effects, so it should not be called twice.
bool condition_satisfied = (x() > 10 ? y > 5 : z > 2); if (condition_satisfied) action1(p1, p2, p3, p4); else action2(p1, p2); Or, alternatively, what Roger Lipscombe answered.
578,479
578,699
What are the Best Components of Boost?
I've been browsing revision 1.38.0 of the Boost libraries, in an attempt to decide if there are enough jewels there to justify negotiating my company's external software approval process. In the course of writing test programs and reading the documents, I've reached a couple conclusions of course, not everything in Boost will ever be of use in my engineering group more importantly, some of these libraries seem more polished than others In fact, some libraries seem a bit toy-like to me. There are a number of fairly accessible libraries that I can see putting to use after only a short period of investigation, such as boost::variant (I really like the visitor component and the fact that the compiler barfs if a visitor lacks an operator for one of the variant types). I'd use boost::shared_ptr except for the fact that our group already has a set of smart pointer types. So based on the broad experience of Stack Overflow users, which Boost libraries have high quality? are more than toys? are there any which have a high entry barrier but which are well worth learning? Note that this is a somewhat different question than that posed in Boost considered harmful? P.S. - Has one of the answers (from litb) been deleted? I can't see it here, and only an excerpt on my user page...
I use quite frequently (and it makes my life simpler): smart pointers (shared_ptr, scoped_ptr, weak_ptr, interprocess unique_ptr): scoped_ptr for basic RAII (without shared ownership and ownership transfer), at no cost. shared_ptr for more complex operations - when shared ownership is needed. However there is some cost. unique_ptr - there is active work at boost on unifying various approaches (present at Boost) to unique_ptr with move emulation. They are really simple to use (header only), easy to learn and very well tested (well, except maybe the unique_ptr) Boost Thread - actively developed (threads are now movable) library for working with threads. Hides the complexity of thread implementation on a given platform. Boost MPL and Fusion - these are more difficult to explain. For long time I didn't use compile time power, but after some reading and learning it turned out that some of my code can be nicely simplified. Still, beware of the compilation time... Boost Asio Contrary to the first impression (at least some time ago) it is not only the networking library. It provides asynchronous I/O model that can be used for virtually anything. Boost Format (powerful output formatting, but very heavy) Boost Spirit2x (Karma and Qi used both for parsing and generating output based on a given grammar). Really powerful, can create a parser without resorting to external tools. Yet the compilation time might be a problem. Also version 2x is being actively developed and the documentation is rather scarce (the spirit-devel mailing list is very helpful though) Boost Bind, Function and Lambda to make your life easier and Boost Phoenix - just to experiment lexical_cast (something similar might be born soon as boost::string) Regex/Xpressive - regular expressions Type traits and concept checks - once again to make your life easier Math: various random number generators various statistical distributions ublas - for using LAPACK/BLAS bindings in C++ like way some mathematical functions, normally not available in C++ some tools for controlling the conversions between numreric types interval arithmetics Boost Iterator (specialized adaptors for iterators and facade for creating your own) Boost Unit Testing framework And still there are some parts that I'd barely touched in Boost. Probably I also forgot to mention few obvious ones. Remember to use right tools (hammers) for right problems (nails). Remember to keep the solutions simple. Remember about the cost of received functionality (for example shared_ptr or boost::format runtime overhead or MPL/Fusion/Spirit/Phoenix compile time costs and executable sizes). But experiment and learn - it's where the fun is. And when it comes to convincing the management to use the new libraries - you don't have to start with all the libraries. Start with the simple things (probably the ones that have a long and stable Boost history, broad compiler support, are planned for inclusion in TR2/C++1x, etc) and simple examples that show the benefits.
578,654
578,672
Static Constant Class Members
Consider the following snippet: struct Foo { static const T value = 123; //Where T is some POD-type }; const T Foo::value; //Is this required? In this case, does the standard require us to explicitly declare value in a translation unit? It seems I have conflicting information; boost and things like numeric_limits from the STL seem to do this sort of thing just like in my snippet. OTOH, I remember reading somewhere (albeit a long long time ago) that you're still required to provide a declaration in a translation unit. If this is the case, what about template specialization? Will each specialization require a declaration? I'd appreciate your comments as to what the "right way" is.
You have to provide a definition in a translation unit too, in case you use the value variable. That means, if for example you read its value. The important thing is that the compiler is not required to give a warning or error if you violate that rule. The Standard says "no diagnostic required" for a violation. In the next C++ Standard version, the rule changed. A variable is not used when it is used as a constant expression. Simply reading value above where the variable is initialized directly in the class means that still no definition is required then. See the definition of use in section 3.2 One Definition Rule of the Standard and requirement for a definition for static data-members in 9.4.2, paragraph 4 and 5 (in the C++98 Standard. Appears in paragraph 3 and 4 in the n2800 draft of the next Standard). Correction: The rule already changed for c++03: If the variable appears where a integral constant expression is required, no definition is needed (quoting from an unofficial revisions list for the 2003 update), see resolution for this language defect report: An expression is potentially evaluated unless it appears where an integral constant expression is required (see 5.19), is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8)... Note that even then, many uses are in cases where an integral constant is not required. Cases where one is, is in array dimensions or in template metaprogramming. So strictly speaking (see this report), only the c++1x solution provides really guarantee that in obvious cases also like "s == string::npos" where an integral constant is not required the definition of the static member is not needed, because the next Standard has a different, better wording of 3.2. This is however quite theoretical stuff, since most (all?) compiler don't moan anyway. Thanks for the guy in the comment section for telling me.
578,753
578,762
Forcing ints to initialize to 0 msvc++
Is there any compiler setting or other way to force an int to be initialized to 0?
Is there any compiler setting or other way to force an int to be initialized to 0? Unfortunately, there is no way in the language and if the compiler offers such a setting it goes against the standard and therefore should not be used. May I ask why you need this? Is explicit initialization not enough? Or would you like to be warned when uninitialized memory i used? The latter can be achieved using valgrind's memory profiler.
578,794
578,822
How boost.asio discover which port is my server app listening on?
it is a little bit strange to me that boost.asio doesn`t use basic concept when client app connecting to the server - using IP address and port. May be I am a little bit noobie in Boost - and I accept that - but anyway I do not understand. So, I have code like this to get client connected to the server on the localhost: boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query("localhost", "daytime"); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; tcp::socket socket(io_service); boost::system::error_code error = boost::asio::error::host_not_found; while(error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } Windows in its WinSock 2.0 uses two parameters - IP and port - to identify the server. So, the qurestion is - how exactly Asio finds out which port is server listening to connections on? Does it scans all ports? And, if it does, what will happen if two servers listening on different ports at the same time?
You are telling it that you want to connect to localhost on the port used by the daytime service. It will look up the appropriate port number in the services file (usually C:\WINDOWS\system32\drivers\etc\services under Windows, I believe /etc/services under Unix). You could also use an explicit port number there.
578,950
580,882
I need platform-independent version of CharToOem. Does Boost have any?
I need to convert string to support multi-language messaging in my client-server app. Can I find it in boost?
For platform-independent codepage conversions you can use libiconv library. Anyway, why bother using codepages at all? Use unicode.
579,556
579,570
cygwin compile error in sys/_types.h
I am trying to use cywin to get some linux code building on a win32 machine. I get the following VS.net 2003 error in ym compiler: "c:\cygwin\usr\include\sys_types.h(15): error C2144: syntax error : '__int64' should be preceded by ';' " and c:\cygwin\usr\include\sys_types.h(15): error C2501: 'extension' : missing storage-class or type specifiers The code line is __extension__ typedef long long _off64_t; Obviously I am missing something here but I have never used cygwin before and this is killing me. I want to be able to at least compile my CPP files on my win32 machine for a few reasons. (this is just the first two errors of hundreds it looks like) thanks, tim EDIT: the simple workaround I have chosen as the answer - though I do understand that is not as complete or as desirable as using gcc to compile... This is a quick and dirty compilation so that I can use my familiar tools before trying to integrate with linux machines. (oh the joys of cross-platform development) I've voted up each of those answers so far and appreciate the help)
I think that the extension macro may not be defined. You may want to do a text search on your cygwin header dir to see if this is the case. If so, make sure that you header search path is defined correctly, etc.
579,673
579,696
Where should my win32 program keep its files?
Our win32 applications (written in C++) have been around for over 10 years, and haven't been updated to follow "good practices" in terms of where they keep files. The application defaults to installing in the "C:\AppName" folder, and keeps application-generated files, configuration files, downloaded files, and saved user documents in subfolders of that folder. Presumably, it's "best practices" to default to installing under "c:\Program Files\AppName" nowadays. But if we do that, where should we keep the rest of our files? Starting from Vista, writing to the program files folder is problematic, and there seem to be a million other places that you can put different files, and I'm confused. Is there a reference somewhere for what goes where? Edit: To expand on questions people have asked so far: I'm familiar with the SHGetFolderPath function, but there are lots and lots of options that you can get from it, and I can't find a resource that says "Here is exactly what each of these options is used for, and when you might want to use it". Up until now, we've done the "All files, including saved user files, under one folder" thing, and it's worked fine - but not when people want to install the app under the Program Files folder. For some reason, the virtualization monkeying around that Vista does isn't working for our application; if we're going to be making changes anyway, we might as well make an effort to do things the "right" way, since we don't want to have to change it again in 12 months time. Further question: We include some "sample" documents with our app, which we update every now and again. Is it appropriate to install them into My Documents, if we'll be overwriting them every few months? Or is My Documents assumed to be totally safe for users to mess around in? If we can't install them to My Documents, where should we put them so that users can see them easily?
Presumably, it's "best practices" to default to installing under "c:\Program Files\AppName" Close, but not quite. Users can configure the name of the Program Files folder and may not even have a C: drive. Instead, install to the %ProgramFiles%\AppName environment variable folder. Note you should assume you only have read access to this folder after the installation has finished. For program data files where you might need write access, use %AppData%\AppName. Finally, are you sure yours is the only app with that name? If you're not 100% certain of that, you might want to include your company name in there as well. The mechanisms you use to retrieve those variables will vary depending on your programming platform. It normally comes down to the SHGetFolderPath() Win32 method in the end, but different platforms like Java or .Net may provide simpler abstractions as well.
579,783
580,090
How to detect IP address change programmatically in Linux?
Is there a way to detect IP address changes on the local machine in Linux programmatically using C++?
In C, to get the current IP I use: int s; struct ifreq ifr = {}; s = socket(PF_INET, SOCK_DGRAM, 0); strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name)); if (ioctl(s, SIOCGIFADDR, &ifr) >= 0) printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); Replace "eth0" with the interface you're looking at. All you now need to do is poll for a change.
579,838
579,915
accessing member variable of boost thread object
I'm using an object to start boost thread and it has some public member variables which I modify in the thread (in the () operator). How can I access the object's member variables from outside the thread? I tried using a mutex (defined in the object's class) that is locked both in the operator() of the object and from outside, but it doesn't seem to work. Here's the thread object code: struct Mouse { int x, y; string port; boost::mutex mutex; Mouse(const string& p) : port(p) { x = y = 0; } Mouse(const Mouse& m) : mutex() { x = m.x; y = m.y; port = m.port; } void operator()() { ifstream ifs; ifs.open (port.c_str(), ios::binary ); if (!ifs.is_open()) { cout << "Impossible d'ouvrir " << port.c_str() << "\n"; exit(0); } while (true) //modify x, y in infinit loop { char buf[3]; ifs.read(buf, 3); unsigned char * msg = (unsigned char *) buf; unsigned char xsign = (msg[0]>>4) & 1; unsigned char ysign = (msg[0]>>5) & 1; unsigned char always1 = (msg[0]>>3) & 1; short dx = msg[1] - 256*xsign; short dy = msg[2] - 256*ysign; { boost::mutex::scoped_lock lock(mutex); x += abs(dx); y += dy; } } } }; And this is where I try to access the x and y variables of the mouse: { boost::mutex::scoped_lock leftlock(leftMouse.mutex); xLeft = leftMouse.x; yLeft = leftMouse.y; } { boost::mutex::scoped_lock rightlock(rightMouse.mutex); xRight = rightMouse.x; yRight = rightMouse.y; } cout << xRight << " " << yRight << endl; //this always prints 0 0
boost::thread copies the passed thread function to internal storage, so if you start your thread like this, the thread will operate on a different copy of mouse: int main() { Mouse mouse("abc.txt"); boost::thread thr(mouse); // thr gets a copy of mouse ... // thread changes it's own copy of mouse ... } You can use boost::ref to pass a reference to an existing object instead: Mouse mouse("abc.txt"); boost::thread thr(boost::ref(mouse)); // thr gets a reference of mouse In this case thr will modify the global mouse object, but you have to make sure that mouse doesn't go out of scope or gets destroyed otherwise before thr is finished.
580,053
580,082
When should I use a vector of objects instead of a vector of pointers?
I have a collection of polymorphic objects, all derived from my Animal class: Cat, Dog, and MonkeyFish. My usual mode of operation is to store these objects in a vector of Animal pointers, like so: std::vector< Animal * > my_vector; my_vector.push_back( new Animal_Cat() ); my_vector.push_back( new Animal_Dog() ); my_vector.push_back( new Animal_MonkeyFish() ); And life is great...or is it? I've recently been told that I should really try to avoid allocating memory in this fashion, because it makes memory management a chore. When I need to destroy my_vector, I have to iterate through all the elements and delete everything. I don't think that I can store a vector of references (I might be wrong about this), so it seems like storing a vector of Animal objects is my only alternative. When should I choose to use a vector of pointers versus a vector of objects? In general, which method is preferable? (I would like to reduce object copying as much as possible.)
You should use a vector of objects whenever possible; but in your case it isn't possible. Containers of pointers let you avoid the slicing problem. But then you have to call delete on each element, like you are doing. That's annoying but possible. Unfortunately there are cases (when an exception is thrown) where you can't be sure that delete is properly called, and you end up with a memory leak. The main solution is to use a smart pointer. Pre-C++11 comes with auto_ptr, but that cannot be used in a standard container. C++11 has std::unique_ptr and std::shared_ptr which are designed to be usable in containers (I prefer std::unique_ptr unless I really need reference counting). If you can't use C++11, the best solution is Boost smart pointers.
580,229
580,307
Member Variable Pointers in 64 bit environment
I've discovered while trying to use a luaBind-style class binding system that passing pointers to member variables doesn't seem to work right when compiling as a 64 bit app. Specifically: class Foo { int a; int b; }; With the above class getting &Foo::b in 32 bit will return (as expected) 0x00000004. The same call in 64 bit returns 0xCCCCCCCC00000004, which is 32 bits of correct and 32 bits of WTF. My first thought is that this is a bug in the compiler (I'm using Visual Studio 2005 SP1 on Vista 64 Business), but that seems like a pretty big bug for a IDE that proudly claims 64 bit compatibility. Googling turns up nothing (but I may be using the wrong term. Member Variable Pointer? Anyone care to correct me?), so I'm curious if this is just me or a more widespread issue.
Try printing sizeof(&Foo::b). IIRC, in 64-bit VS2005 a pointer to member could occupy 4 or 12 bytes (depending on virtual/multiple inheritance), but IDE always displays 8 bytes (which (IMHO) is a bug in IDE ).
580,263
580,560
Windows API and GetClassName()? Another name?
I have some code that has a dynamic-class system in C++ that has a member called GetClassName(), a rather harmless name one would imagine. However when included in a large project with Windows headers all hell broke loose. Apparently Windows uses a #define GetClassName (GetClassNameA or GetClassNameW) which screws up everything, and my virtual call tree became all messed up making me lose a day in stupid compiler debugging in the dark, trying to figure out what was wrong. So besides the point that I'm cursing Microsoft for using such a horribly easy to clash name for a #define (I mean someone should honestly be shot for this!) I'm asking for 3 purposes. What's another good name for GetClassName() ? Is there anyway to fix this, so in the future, other developers of my code base won't suffer similar fate And for posterity when someone else encounters this similarly inexplicable error
I would rename the method. Of course one can say #include <windows.h> #undef GetClassName but it is not clean, users of one's code should remember to write ::GetClassNameW when they call win32 function. One can provide GetClassNameA and GetClassNameW methods in his class, but it's plain ugly. I see two approaches : either lengthen or shorten the name:) 1) add a prefix for all functions in the subsystem, f.e TI_ (for type info): TI_GetClassName() TI_GetBaseClass() TI_IsDerivedFromClass() etc 2) or put them into some IClass interface interface IClass { GetName(); GetBase(); IsDerivedFrom(); etc and return that interface from single method, so that GetClassName() becomes GetClass()->GetName()
580,270
580,303
Avoiding dynamic_cast/RTTI
I was recently working on a piece of C++ code for a side project (the cpp-markdown library, for the curious), and ran into a coding question that I'd like some opinions on. cpp-markdown has a base class called Token, which has a number of subclasses. Two of the main subclasses are Container (which holds collections of other Tokens) and TextHolder (used as a base class for Tokens that contain text, of course). Most of the processing is handled via virtual functions, but some of it was better handled in a single function. For that, I ended up using dynamic_cast to down-cast the pointer from a Token* to one of its subclasses, so I could call functions that are specific to the subclass and its child classes. There's no chance the casting would fail, because the code is able to tell when such a thing is needed via virtual functions (such as isUnmatchedOpenMarker). There are two other ways I could see to handle this: Create all of the functions that I want to call as virtual functions of Token, and just leave them with an empty body for every subclass except the one(s) that need to handle them, or... Create a virtual function in Token that would return the properly-typed pointer to this when it's called on certain subtypes, and a null pointer if called on anything else. Basically an extension of the virtual function system I'm already using there. The second method seems better than both the existing one and the first one, to me. But I'd like to know other experienced C++ developers' views on it. Or whether I'm worrying too much about trivialities. :-)
#1 pollutes the class namespace and vtable for objects that don't need it. Ok when you have a handful of methods that will generally be implemented, but plain ugly when only needed for a single derived class. #2 is just dynamic_cast<> in a polka-dot dress and lipstick. Doesn't make client code any simpler, and tangles up the entire hierarchy, requiring the base and each derived class to be semi-aware of every other derived class. Just use dynamic_cast<>. That's what it's there for.
580,342
580,597
Setting up a mock interface in C++
I'm currently trying to use a certain SDK that has me loading functions off a DLL that a vendor provides.. I have to pass arguments to these functions and the DLL does all the work.. Now, the DLL is supposed to be communicating with another device, while I just wait for the results. However, I don't have this device, so how do I set up a mock interface to emulate the device? To be clear, here's an example: myfuncpointer.Open(someparam,anotherparam,...); Now, because I don't have the device, the DLL can't actually perform the above function; it fails. How do I set up testing so that the DLL talks to a class that I designed rather than the device? Is there any way to redirect the DLL's call? How do I make a DummyDevice class to do this? Thanks.. P.S. If anything is not clear, please don't be too quick to downvote.. Comment as to what I need to explain and I'll try to clear it up.. Thanks. EDIT: What I DO have, however, is a spec sheet with all of the data structures used and the expected/legal values that it has to contain. So for example, if I call a function: myfuncpointer.getinfo(param,otherparam); where one of the params is a data structure that the DLL fills up with info (say, if an option is enabled) after querying the device.. I can do this param.option = true; after it has finished the getinfo call. Is this a good way to test the code? It seems very very dangerous to trick this DLL into thinking all the wrong things and seems to be really really hard to scale even just a bit..
Is emulated device access a stopgap solution for until you get hardware? If so, I recommend finding some other way to be productive: work on something else, write unit tests, etc. Is emulated device access a permanent requirement? If so, here are a few approaches you could take: If the other vendor's SDK has a "simulation" or "emulation" mode, use it. You might be surprised. You're probably not the only client that needs to be able to test/run their application without the other vendor's hardware installed. Take the other vendor's code out of the picture. Emulate only the functionality that your application needs, and base it on your program's requirements. Everything is under your control. a. Add an indirection layer. Use polymorphism to switch between two implementations: one that calls into the other vendor's DLL, and one that emulates its behavior. Having your code call into an abstract base class instead of directly calling into the other vendor's DLL also will make it easier to write unit tests for your code. b. Write a mock DLL (as Adam Rosenfield suggested). You need to match the function names and calling conventions exactly. As you upgrade to new versions of the other vendor's DLL, you will need to extend the mock DLL to support any new entrypoints that your application uses. If you need to choose which DLL to use at runtime, this may require converting your code to load the DLL dynamically (but it sounds like you might already be doing this, given that you said something about function pointers). You may be able to decide at install time whether to install the other vendor's DLL or the mock DLL. And if this is purely for testing purposes, you may be able to choose which DLL to use at compile time, and just build two versions of your application. Write a mock device driver (as others have suggested). If you have the spec for the interface between the other vendor's user mode DLL and their device driver, this may be doable. It will probably take longer than any of the other approaches, even if you're an experienced device driver developer, and especially if you don't have the source to the other vendor's DLL. UMDF (User Mode Driver Framework) might make this slightly easier or less time consuming. If the spec you mentioned does not describe the user/kernel interface, you will need to reverse engineer that interface. This is probably not going to be an effective use of your time compared with the other options, particularly if the driver interface is complex (e.g. it passes a lot of complex data structures to DeviceIoControl()). In both cases, you will need to revisit this every time you upgrade to a new version of the other vendor's SDK. The same exported DLL functions may require using new DeviceIoControl() codes and structures.
580,363
580,412
Posix Threads in c++
How to implement posix threads in linux c++.The smme program when saved as ".c and run using c compiler is ok. but in c++ it is giving error .. I think i made mistake when compiling is there any tag to be included like "-lpthread" for c++ Can someone pls send a valid code...? Actually this is my code int cooperbussman :: startlistenthread() { if(pthread_create(&m_thread,0,&packetreadertask,0)<0) { cout<<"Unable to create the thread Startlistenthread\n"; return -1; } return 1; and the error i am getting is cooperbussman.cpp: In member function âint cooperbussman::startlistenthread()â: cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â cooperbussman.cpp:76: error: initializing argument 3 of âint pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)â
Your packetreadertask function must be a function that takes a single void * as a parameter. This is the important error message: cooperbussman.cpp:76: error: invalid conversion from âvoid* (*)()â to âvoid* (*)(void*)â Your function is declared something like this: void *packetreadertask(); where it must be: void *packetreadertask(void *);
580,375
580,533
How to generate a compiler warning/error when object sliced
I want to know if it is possible to let compiler issue a warning/error for code as following: Note: 1. Yea, it is bad programming style and we should avoid such cases - but we are dealing with legacy code and hope compiler can help identify such cases for us.) 2. I prefer a compiler option (VC++) to disable or enable object slicing, if there is any. class Base{}; class Derived: public Base{}; void Func(Base) { } //void Func(Derived) //{ // //} //main Func(Derived()); Here if I comment out the second function, the first function would be called - and the compiler (both VC++ and Gcc) feels comfortable with that. Is it C++ standard? and can I ask compiler (VC++) to give me a warning when met such code? Thanks so much!!! Edit: Thanks all so much for your help! I can't find a compiler option to give a error/warning - I even posted this in MSDN forum for VC++ compiler consultant with no answer. So I am afraid neither gcc nor vc++ implemented this feature. So add constructor which take derived classes as paramter would be the best solution for now. Edit I have submit a feedbak to MS and hope they will fix it soon: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=421579 -Baiyan
If you can modify the base class you could do something like: class Base { public: // not implemented will cause a link error Base(const Derived &d); const Base &operator=(const Derived &rhs); }; Depending on your compiler that should get you the translation unit, and maybe the function where the slicing is happening.
580,448
580,513
What Visual Studio 2008 productivity features are missing from C++ Express edition?
I'm using Visual Studio C++ 2008 Express to learn a native API for a new project. What I'm wondering is: what productivity features present in the full version that you take for granted are missing from Visual Studio Express? I'm not referring to large "paid" features like MFC support - I'm thinking of small features (sometimes provided by Add Ins) like "Copy File to Output Dir" Also, it doesn't have to be specific to C++ edition - that's just the exact release I happen to be using. Note: I'm an experienced Java programmer and I most frequently use IntelliJ IDEA (disclaimer: that's just for reference - I'm not looking to compare VS vs. IDEA). EDIT: Revised to include Add Ins that enhance the experience.
If you plan to develop a C/C++ WIN32 GUI application then the major component that is missing is the resource editor (i.e. the GUI builder tool). The express version will still compile resource files, but you will have to create the resource files by hand or use a third party resource editor.
580,622
580,628
Dynamic array... copy constructor, destructor, overloaded assignment operator
I am studying for my midterm exam. There is going to be a question about setting up an array dynamically, and maybe doing a copy constructor, a destructor and overloading the assignment operator. Can you please verify if I am correct. Also I don't understand what overloading the assignment operator means. Can you help me out with this? class A { int* myArray; //basically I created a pointer called myArray, A() //are my copy constructors correct? A(), and A(int size)? { myArray = 0; } A(int size) { myArray = new int[size]; } ~A() // I think my destructor is correct { delete [] myArray; } Can you check my code please? Also how do I overload assignment operator? Thanks in advance.
The copy constructor is used for creation of object based on another's instance of the same type. You don't have such. You can define it using code like this: A(const A &other) { myArray = new int[other._size]; _size = other._size; memcpy(myArray, other.myArray, sizeof(int) * _size); } You should change your class, so it will store _size of array, you also need to change visibility of your constructors and destructor to public. The overloaded assignment operator should look like this: const A &operator=(const A &other) { if(this == &other) return *this; // handling of self assignment, thanks for your advice, arul. delete[] myArray; // freeing previously used memory myArray = new int[other._size]; _size = other._size; memcpy(myArray, other.myArray, sizeof(int) * _size); return *this; } You also can add a check of equality of array sizes in this assignment operator, so you will reuse your dynamic array without unnecessary reallocations of memory.
580,652
580,678
Fighting fragmentation in custom memory manager
I've written a c/c++ memory manager for heap allocations (overloaded new/delete and malloc/realloc/free, based on Doug Lea's malloc but designed to be wait free) and seem to be having some trouble with fragmentation. Are there any good resources out there that detail good strategies for avoiding fragmentation via the manager? Please note that I can't rearrange memory that has already been allocated (not using smart pointers with GUIDs) and re-writing the system to use pools instead of heap allocations is unfeasible. Thanks, Grant
You may want to get some inspiration from jemalloc (http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf) - this allocator is used in the new Firefox explicitly because of its anti-fragmentation capabilities.
580,922
580,935
Identifying primitive types in templates
I am looking for a way to identify primitives types in a template class definition. I mean, having this class : template<class T> class A{ void doWork(){ if(T isPrimitiveType()) doSomething(); else doSomethingElse(); } private: T *t; }; Is there is any way to "implement" isPrimitiveType().
UPDATE: Since C++11, use the is_fundamental template from the standard library: #include <type_traits> template<class T> void test() { if (std::is_fundamental<T>::value) { // ... } else { // ... } } // Generic: Not primitive template<class T> bool isPrimitiveType() { return false; } // Now, you have to create specializations for **all** primitive types template<> bool isPrimitiveType<int>() { return true; } // TODO: bool, double, char, .... // Usage: template<class T> void test() { if (isPrimitiveType<T>()) { std::cout << "Primitive" << std::endl; } else { std::cout << "Not primitive" << std::endl; } } In order to save the function call overhead, use structs: template<class T> struct IsPrimitiveType { enum { VALUE = 0 }; }; template<> struct IsPrimitiveType<int> { enum { VALUE = 1 }; }; // ... template<class T> void test() { if (IsPrimitiveType<T>::VALUE) { // ... } else { // ... } } As others have pointed out, you can save your time implementing that by yourself and use is_fundamental from the Boost Type Traits Library, which seems to do exactly the same.
580,985
589,303
VS2005 C++ broken vtables
I'm currently working on a quite big (and old, sigh) code base, recently upgraded to VS2005 (SP1). Me and my team are changing/updating/replacing modules in this code as we go but we have occasionally been running into problems where the vtables seems broken. I am no expert on vtables but these sure seems to be broken. The errors manifests itself with this error: Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention. Of course there can be plenty of other reasons for this error but when debugging (Debug build) I can actually verify that the vtables for the object I want to operate on look strange: The stack and heap that reference each vtable looks fine and the pointers to the vtables match perfectly to the map file. This indicates to me that this is not a memory overwriting bug or similar, since then it would affect the stack and heap rather than where the vtables are stored. (They are stored in a read only area right?) Anyway, all seems good so far. But when looking at the memory of the vtable I find that all values, if I interpret them as pointers, although they are in the same range (Eg. 0x00f203db 0x00f0f9be 0x00ecdda7 0x00f171e1) does not match any entry in the map file and many of them are not even aligned to 4 bytes. I don't know all the details of how VS2005 builds the vtables, but this looks wrong to me. If this is correct behavior, perhaps somebody can explain this to me? I guess my question boils down to what can cause this behavior? Is there any know bugs in the linker when having too complex class hierarchies for example? Has anybody seen anything similar before? Currently we are able to get around our crashes by moving functions from the affected class to inline (scary stuff!) but clearly this is not a feasible long term solution. Thanks for any insight! Update: I've been asked for more details about the project and of course I will supply this. First however, the question is not entirely related to the ESP value not being saved error. What I am most interested in is why I see the strange values in the vtable. That said, here is some additional info: The solution relies on several external and internal projects but these have not been changed in a long time, all uses the same calling convention. The code where it seems to break is all within the one pretty standard C++ "main" project of the solution. All code is built with the same compiler. The solution also doesn't use any dlls but links with plenty of static libraries: SHFolder.lib, python25.lib, dxguid.lib, d3d9.lib, d3dx9.lib, dinput8.lib, ddraw.lib, dxerr9.lib, ws2_32.lib, mss32.lib, Winmm.lib, vtuneapi.lib, vttriggers.lib, DbgHelp.lib, kernel32.lib, user32.lib, gdi32.lib, winspool.lib, comdlg32.lib, advapi32.lib, shell32.lib, ole32.lib, oleaut32.lib, uuid.lib, odbc32.lib, odbccp32.lib
I found the problem. Silly really but the class hierarchy that caused the problem had a virtual function called GetObject which conflicted with the windows #define with the same name. The header files included these windows header files in different order, which confused the linker. So, in fact the problem was corrupted vtables, but I didn't expect this to be reason! Well you learn something every day... However, big thanks to all that replied!
581,097
581,100
Can I use blocks to manage memory consumption in C++?
I'm trying to gain some memory saving in a C++ program and I want to know if I can use blocks as a scope for variables (as in Perl). Let's say I have a huge object that performs some computations and gives a result, does it makes sense to do: InputType input; ResultType result; { // Block of code MyHugeObject mho; result = mho.superHeavyProcessing(); } /* My other code ... */ Can I expect the object to be destroyed when exiting the block?
Yes, you can. The destructor will be called as soon as the variable falls out of scope and it should release the heap-allocated memory.
581,172
581,515
How to use IGlobalInterfaceTable to pass an interface pointer?
Without: MFC ATL Question: What are the steps involved, to use IGlobalInterfaceTable, when passing a particular interface pointer to several threads using CreateThread?
I think this page covers it rather well. Call RegisterInterfaceInGlobal to put your COM interface in the GIT, pass its cookie to your other threads, which can then call GetInterfaceFromGlobal using that cookie to get the original interface. Note that each thread has to call CoCreateInstance(CLSID_StdGlobalInterfaceTable... but don't worry, they all get an interface pointer to the same instance of the GIT.
581,204
581,369
How do I check if a user has local admin privileges in win32
How do I check if a user has local admin privileges in win32 from c++
Just found IsUserAnAdmin() in shlobj.h which does the job for me.
581,209
581,708
How to best write out a std::vector < std::string > container to a HDF5 dataset?
Given a vector of strings, what is the best way to write them out to a HDF5 dataset? At the moment I'm doing something like the following: const unsigned int MaxStrLength = 512; struct TempContainer { char string[MaxStrLength]; }; void writeVector (hid_t group, std::vector<std::string> const & v) { // // Firstly copy the contents of the vector into a temporary container std::vector<TempContainer> tc; for (std::vector<std::string>::const_iterator i = v.begin () , end = v.end () ; i != end ; ++i) { TempContainer t; strncpy (t.string, i->c_str (), MaxStrLength); tc.push_back (t); } // // Write the temporary container to a dataset hsize_t dims[] = { tc.size () } ; hid_t dataspace = H5Screate_simple(sizeof(dims)/sizeof(*dims) , dims , NULL); hid_t strtype = H5Tcopy (H5T_C_S1); H5Tset_size (strtype, MaxStrLength); hid_t datatype = H5Tcreate (H5T_COMPOUND, sizeof (TempConainer)); H5Tinsert (datatype , "string" , HOFFSET(TempContainer, string) , strtype); hid_t dataset = H5Dcreate1 (group , "files" , datatype , dataspace , H5P_DEFAULT); H5Dwrite (dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &tc[0] ); H5Dclose (dataset); H5Sclose (dataspace); H5Tclose (strtype); H5Tclose (datatype); } At a minimum, I would really like to change the above so that: It uses variable length strings I don't need to have a temporary container I have no restrictions over how I store the data so for example, it doesn't have to be a COMPOUND datatype if there is a better way to do this. EDIT: Just to narrow the problem down, I'm relatively familiar with playing with the data on the C++ side, it's the HDF5 side where I need most of the help. Thanks for your help.
[Many thanks to dirkgently for his help in answering this.] To write a variable length string in HDF5 use the following: // Create the datatype as follows hid_t datatype = H5Tcopy (H5T_C_S1); H5Tset_size (datatype, H5T_VARIABLE); // // Pass the string to be written to H5Dwrite // using the address of the pointer! const char * s = v.c_str (); H5Dwrite (dataset , datatype , H5S_ALL , H5S_ALL , H5P_DEFAULT , &s ); One solution for writing a container is to write each element individually. This can be achieved using hyperslabs. For example: class WriteString { public: WriteString (hid_t dataset, hid_t datatype , hid_t dataspace, hid_t memspace) : m_dataset (dataset), m_datatype (datatype) , m_dataspace (dataspace), m_memspace (memspace) , m_pos () {} private: hid_t m_dataset; hid_t m_datatype; hid_t m_dataspace; hid_t m_memspace; int m_pos; //... public: void operator ()(std::vector<std::string>::value_type const & v) { // Select the file position, 1 record at position 'pos' hsize_t count[] = { 1 } ; hsize_t offset[] = { m_pos++ } ; H5Sselect_hyperslab( m_dataspace , H5S_SELECT_SET , offset , NULL , count , NULL ); const char * s = v.c_str (); H5Dwrite (m_dataset , m_datatype , m_memspace , m_dataspace , H5P_DEFAULT , &s ); } }; // ... void writeVector (hid_t group, std::vector<std::string> const & v) { hsize_t dims[] = { m_files.size () } ; hid_t dataspace = H5Screate_simple(sizeof(dims)/sizeof(*dims) , dims, NULL); dims[0] = 1; hid_t memspace = H5Screate_simple(sizeof(dims)/sizeof(*dims) , dims, NULL); hid_t datatype = H5Tcopy (H5T_C_S1); H5Tset_size (datatype, H5T_VARIABLE); hid_t dataset = H5Dcreate1 (group, "files", datatype , dataspace, H5P_DEFAULT); // // Select the "memory" to be written out - just 1 record. hsize_t offset[] = { 0 } ; hsize_t count[] = { 1 } ; H5Sselect_hyperslab( memspace, H5S_SELECT_SET, offset , NULL, count, NULL ); std::for_each (v.begin () , v.end () , WriteStrings (dataset, datatype, dataspace, memspace)); H5Dclose (dataset); H5Sclose (dataspace); H5Sclose (memspace); H5Tclose (datatype); }
581,387
581,392
Valid use of typedef?
I have a char (ie. byte) buffer that I'm sending over the network. At some point in the future I might want to switch the buffer to a different type like unsigned char or short. I've been thinking about doing something like this: typedef char bufferElementType; And whenever I do anything with a buffer element I declare it as bufferElementType rather than char. That way I could switch to another type by changing this typedef (of course it wouldn't be that simple, but it would at least be easy to identify the places that need to be modified... there'll be a bufferElementType nearby). Is this a valid / good use of typedef? Is it not worth the trouble? Is it going to give me a headache at some point in the future? Is it going to make maintainance programmers hate me? I've read through When Should I Use Typedef In C++, but no one really covered this.
It is a great (and normal) usage. You have to be careful, though, that, for example, the type you select meet the same signed/unsigned criteria, or that they respond similarly to operators. Then it would be easier to change the type afterwards. Another option is to use templates to avoid fixing the type till the moment you're compiling. A class that is defined as: template <typename CharType> class Whatever { CharType aChar; ... }; is able to work with any char type you select, while it responds to all the operators in the same way.
581,426
581,446
Why is a C++ Vector called a Vector?
The question's pretty self-explanatory really. I know vaguely about vectors in maths, but I don't really see the link to C++ vectors.
Mathematical definition of a vector is a member of the set Sn, which is an ordered sequence of values in a specific set (S). This is what a C++ vector stores.
581,548
582,275
C++ Builder runtime error - cannot focus a disabled or invisible window
On main form I have TPageControl and on all of it's tabs I have corresponding Save buttons which are activated on Alt+S combination. Of course, depending on which tab is opened at the moment, the handler for corresponding Save button should be called; but I get "cannot focus a disabled or invisible window" runtime error if I try to save with Alt+S. And I've noticed that, the handler of a Save button from the tab which was active before the current tab, is called, but don't know why. I tried putting Save buttons in panels (it worked fine for some similar problems), but still the same thing happens. Cheers.
You could do it all with one button. In the OnClick handler, check which page is the current one, and call the saving function for that page.
581,595
581,639
Vectors, iterators and std::find
Is there any way to use different types of iterators in different vectors? Or, is there a function that returns the position of element in vector as an integer? std::vector<DWORD>::iterator it; // Iterator // monsterQueue is a <DWORD> vector it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object); // Check do we have the object in the queue if(it != bot.monsterQueue.end()) // If we do have it { bot.monsterDists.at(it) = mobDist; // monsterDists is <int> vector bot.monsterCoordX.at(it) = PosX; // monsterCoordX is <int> vector bot.monsterCoordY.at(it) = PosY; // monsterCoordY is <int> vector too } That's some sample code, does anyone have any pointers?
Try std::vector<DWORD>::iterator it; // Iterator // monsterQueue is a <DWORD> vector it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object); // Check do we have the object in the queue if(it != bot.monsterQueue.end()) // If we do have it { size_t idx = it - bot.monsterQueue.begin() bot.monsterDists.at(idx) = mobDist; // monsterDists is <int> vector bot.monsterCoordX.at(idx) = PosX; // monsterCoordX is <int> vector bot.monsterCoordY.at(idx) = PosY; // monsterCoordY is <int> vector too } Also probably it will be a better idea to create a struct with 4 members 'monster',monsterDist and coordinateX and coordinateY and store the struct objects in vector.
581,609
581,642
Looking for an open-source flatfile/xml database C++ library
I'm looking for a light-weight database library that I can compile into a C++ application. Does any such exist?
For pure XML embedded database you might want to peek at Oracle Berkeley DB XML.
581,773
581,789
Methods of sharing class instances between processes
I have written a C++ class that I need to share an instance of between at least two windows processes. What are the various ways to do this? Initially I looked into #pragma data_seg only to be disappointed when I realised that it will not work on classes or with anything that allocates on the heap. The instance of the class must be accessible via a dll because existing, complete applications already use this dll.
You can potentially use memory-mapped files to share data between processes. If you need to call functions on your object, you'd have to use COM or something similar, or you'd have to implement your own RPC protocol.
582,199
582,219
Assertion error in std:vector used in std::set_difference
I am trying to find the set difference of two vectors, so i do something like this: std::vector<sha1_hash> first_vec, second_vec, difference_vec; // populate first_vec and second_vec ... std::sort(first_vec.begin(),first_vec.end()); std::sort(second_vec.begin(),second_vec.end()); std::set_difference(first_vec.begin(),first_vec.end(), second_vec.begin(),second_vec.end(), difference_vec.begin()); When i run this in debug, i get the following run-time assertion failure (in 'vector'): _SCL_SECURE_VALIDATE_RANGE(_Myptr < ((_Myvec *)(this->_Getmycont()))->_Mylast); I am using VS 2008. Any ideas on what can trigger this?
Like most c++ algorithms, set_difference does not create new entries in the output vector where none existed before. You ned to create space in the output to hold the results. Edit: Or use an an insert iterator (following untested): back_insert_iterator< std::vector<sha1_hash> > bi( difference_vec ); std::set_difference(first_vec.begin(),first_vec.end(), second_vec.begin(),second_vec.end(), bi);
582,302
2,667,045
Are there optimized c++ compilers for template use?
C++ templates have been a blessing in my everyday work because of its power. But one cannot ignore the (very very very very long) compilation time that results from the heavy use of templates (hello meta-programming and Boost libraries). I have read and tried quite a lot of possibilities to manually reorganize and modify template code to make it compile as fast as possible. Now I am wondering if there are any c++ compilers that try and minimize the needed time to interpret template classes. I might be wrong, but i feel that the compilers i do know have only added template interpretation to their previous versions. My questions are : Is c++ template code so difficult to interpret that there is not much to optimize ? (i highly doubt that) Are there c++ compilers that truly optimize "c++ templates" interpretation ? Are there projects to develop a new generation of c++ compilers that would optimize this ? If you were to participate in such a project, what would your guidelines be ?
It seems that g++ 4.5 has made tremendous progress dealing with templates. Here are the two unavoidable changes. "When printing the name of a class template specialization, G++ will now omit any template arguments which come from default template arguments." That could be considered a subtle modification, but it will have an enormous impact on development with c++ templates (ever heard of unreadable error messages... ? No more !) "Compilation time for code that uses templates should now scale linearly with the number of instantiations rather than quadratically." This is going to severely undermine compilation-time arguments against the use of C++ templates. See on the gnu site for complete information Actually, i am already wondering whether there still are issues with c++ templates ! Mmm, yes, there are, but let's focus on the bright side for now !
582,331
582,456
Is there a way to instantiate objects from a string holding their class name?
I have a file: Base.h class Base; class DerivedA : public Base; class DerivedB : public Base; /*etc...*/ and another file: BaseFactory.h #include "Base.h" class BaseFactory { public: BaseFactory(const string &sClassName){msClassName = sClassName;}; Base * Create() { if(msClassName == "DerivedA") { return new DerivedA(); } else if(msClassName == "DerivedB") { return new DerivedB(); } else if(/*etc...*/) { /*etc...*/ } }; private: string msClassName; }; /*etc.*/ Is there a way to somehow convert this string to an actual type (class), so that BaseFactory wouldn't have to know all the possible Derived classes, and have if() for each one of them? Can I produce a class from this string? I think this can be done in C# through Reflection. Is there something similar in C++?
Nope, there is none, unless you do the mapping yourself. C++ has no mechanism to create objects whose types are determined at runtime. You can use a map to do that mapping yourself, though: template<typename T> Base * createInstance() { return new T; } typedef std::map<std::string, Base*(*)()> map_type; map_type map; map["DerivedA"] = &createInstance<DerivedA>; map["DerivedB"] = &createInstance<DerivedB>; And then you can do return map[some_string](); Getting a new instance. Another idea is to have the types register themself: // in base.hpp: template<typename T> Base * createT() { return new T; } struct BaseFactory { typedef std::map<std::string, Base*(*)()> map_type; static Base * createInstance(std::string const& s) { map_type::iterator it = getMap()->find(s); if(it == getMap()->end()) return 0; return it->second(); } protected: static map_type * getMap() { // never delete'ed. (exist until program termination) // because we can't guarantee correct destruction order if(!map) { map = new map_type; } return map; } private: static map_type * map; }; template<typename T> struct DerivedRegister : BaseFactory { DerivedRegister(std::string const& s) { getMap()->insert(std::make_pair(s, &createT<T>)); } }; // in derivedb.hpp class DerivedB { ...; private: static DerivedRegister<DerivedB> reg; }; // in derivedb.cpp: DerivedRegister<DerivedB> DerivedB::reg("DerivedB"); You could decide to create a macro for the registration #define REGISTER_DEC_TYPE(NAME) \ static DerivedRegister<NAME> reg #define REGISTER_DEF_TYPE(NAME) \ DerivedRegister<NAME> NAME::reg(#NAME) I'm sure there are better names for those two though. Another thing which probably makes sense to use here is shared_ptr. If you have a set of unrelated types that have no common base-class, you can give the function pointer a return type of boost::variant<A, B, C, D, ...> instead. Like if you have a class Foo, Bar and Baz, it looks like this: typedef boost::variant<Foo, Bar, Baz> variant_type; template<typename T> variant_type createInstance() { return variant_type(T()); } typedef std::map<std::string, variant_type (*)()> map_type; A boost::variant is like an union. It knows which type is stored in it by looking what object was used for initializing or assigning to it. Have a look at its documentation here. Finally, the use of a raw function pointer is also a bit oldish. Modern C++ code should be decoupled from specific functions / types. You may want to look into Boost.Function to look for a better way. It would look like this then (the map): typedef std::map<std::string, boost::function<variant_type()> > map_type; std::function will be available in the next version of C++ too, including std::shared_ptr.
582,878
582,886
Why is boost so heavily templated?
There are many places in boost where I see a templated class and can't help but think why the person who wrote it used templates. For example, the mutex class(es). All the mutex concepts are implemented as templates where one could simply create a few base classes or abstract classes with an interface that matches the concept. edit after answers: I thought about the cost of virtual functions but isn't it sometimes worth giving away very little performance penalty for better understanding? I mean sometimes (especially with boost) it's really hard to understand templated code and decrypt compiler errors as a result of misusing templates.
Templates can be highly optimized at compile time, without the need for virtual functions. A lot of template tricks can be thought of as compile-time polymorphism. Since you know at compile time which behaviours you want, why should you pay for a virtual function call everytime you use the class. As a bonus, a lot of templated code can be easily inlined to eliminate even the most basic function-call overhead. In addition, templates in C++ are extremely powerful and flexible - they have been shown to be a turing complete language in their own right. There are some things that are easy to do with templates that require much more work with runtime polymorphism.
582,879
611,360
Converting OpenGL Primitives to OpenGLES
I'm trying to convert the following code from OpenGL 1.5 spec. to the OpenGLES 1.1 spec (num_x and num_y are passed into the function by arguments) ::glBegin(GL_LINES); for (int i=-num_x; i<=num_x; i++) { glVertex3i(i, 0, -num_y); glVertex3i(i, 0, num_y); } for (int i=-num_y; i<=num_y; i++) { glVertex3i(-num_x, 0, i); glVertex3i( num_x, 0, i); } ::glEnd(); Here is my corresponding converted code: (ignore the inefficiency of my loops, I am trying to get the conversion to work properly first) I'm trying to build two things here: A float array of all the x,y,z coordinates needed to draw the grid An index array of all the verticies needed. Both arrays are then passed to OpenGL which renders them. An example of what the arrays should look like: GLshort indices[] = {3, 0, 1, 2, 3, 3, 4, 5, 3, 6, 7, 8, }; GLfloat vertexs[] = {3.0f, 0.0f, 0.0f, 6.0f, 0.0f, -0.5f , 0, 0, 0, 6.0f, 0.0f, 0.5f, 3.0f, 0.0f, 0.0f, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 6, 0}; int iNumOfVerticies = (num_x + num_y)*4*3; int iNumOfIndicies = (iNumOfVerticies/3)*4; GLshort* verticies = new short[iNumOfVerticies]; GLshort* indicies = new short[iNumOfIndicies]; int j = 0; for(int i=-num_x; j < iNumOfVerticies && i<=num_x; i++,j+=6) { verticies[j] = i; verticies[j+1] = 0; verticies[j+2] = -num_y; verticies[j+3] = i; verticies[j+4] = 0; verticies[j+5] = num_y; } for(int i=-num_y; j < iNumOfVerticies && i<=num_y;i++,j+=6) { verticies[j] = i; verticies[j+1] = 0; verticies[j+2] = -num_x; verticies[j+3] = i; verticies[j+4] = 0; verticies[j+5] = num_x; } I need to also build an array if indicies to pass on. I 'borrowed' the array structure from the iphone 'teapot' example. In each row, we have the number of indicies followed by the indicies referenced. int k = 0; for(j = 0; j < iNumOfIndicies; j++) { if (j%4==0) { indicies[j] = 3; } else { indicies[j] = k++; } } ::glEnableClientState(GL_VERTEX_ARRAY); ::glVertexPointer(3 ,GL_FLOAT, 0, verticies); for(int i = 0; i < iNumOfIndicies;i += indicies[i] + 1) { ::glDrawElements( GL_LINES, indicies[i], GL_UNSIGNED_SHORT, &indicies[i+1] ); } delete [] verticies; delete [] indicies; Please add code questions as comments, not answers
I can see several things wrong with your converted code: 1.- Using the wrong type for the variable verticies, it should be: GLfloat* verticies = new float[iNumOfVerticies]; 2.- Incorrectly filling verticies, second loop should be: for(int i=-num_y; j < iNumOfVerticies && i<=num_y;i++,j+=6) { verticies[j] = -num_x; verticies[j+1] = 0; verticies[j+2] = i; verticies[j+3] = num_x; verticies[j+4] = 0; verticies[j+5] = i; } 3.- Incorrect filling of indicies, I think you should delete the lines: if (j%4==0) { indicies[j] = 3; } else 4.- Incorrect use of glDrawElements, replace the loop by this single line: ::glDrawElements( GL_LINES, iNumOfIndicies, GL_UNSIGNED_SHORT, indicies);
583,003
583,019
overloading new/delete
I'm making a little memory leak finder in my program, but my way of overloading new and delete (and also new[] and delete[]) doesn't seem to do anything. void* operator new (unsigned int size, const char* filename, int line) { void* ptr = new void[size]; memleakfinder.AddTrack(ptr,size,filename,line); return ptr; } The way I overloaded new is shown in the code snippet above. I guess it's something with the operator returning void* but I do not know what to do about it.
void* ptr = new void[size]; Can't do that. Fix it. Never ever try to overload new/delete globally. Either have them in a base class and derive all your objects from this class or use a namespace or a template allocator parameter. Why, you may ask. Because in case your program is more than a single file and using STL or other libraries you are going to screw up. Here's a distilled version of new operator from VS2005 new.cpp: void * operator new(size_t size) _THROW1(_STD bad_alloc) { // try to allocate size bytes void *p; while ((p = malloc(size)) == 0) if (_callnewh(size) == 0) { // report no memory static const std::bad_alloc nomem; _RAISE(nomem); } return (p); }
583,056
583,082
ATL Collection of non-trivial objects
I would like to expose an ATL COM collection of CMainClass objects such that it can be accessed by a C#, VB, or C++ client. I don't have a problem setting up the collection itself, but I don't know how to allow the COM clients access to classes A, B, and C. Should I make A, B, & C COM objects with the ones containing a std::list<> each ATL collections in their own right? Is there an easier way to do this?!?! Thanks, PaulH class C { public: // get/set functions... protected: std::string str1_; std::list< std::string > list1_; }; class A { public: // get/set functions... protected: std::list< C > list1_; }; class B { public: // get/set functions... protected: std::string str1_; std::string str2_; }; class CMainClass { public: void GetA( A* a ) const; void SetA( const A& a ); void GetB( B* b ) const; void SetB( const B& b ); protected: A a_; B b_; };
Google for implementing IEnumVARIANT in ATL. Here are some promising links. http://msdn.microsoft.com/en-us/library/3stwxh95.aspx http://www.codeguru.com/cpp/com-tech/atl/misc/article.php/c29 Hope this helps. Responding to your comment: Yes. If you want to expose Automation Compatible interfaces, i.e. those that can be consumed by VB, C# and script languages, each object must be exposed as a COM interface. Also if you are going to store CComPtr<> in a stl list, make sure you use the CAdapt<> wrapper on them.
583,076
583,104
C/C++ changing the value of a const
I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to replicate it I'm not being able to put it to compile. The concept was that it is possible to change by accident the value of a const in C/C++ It was something like this: const int a = 3; // I promise I won't change a const int *ptr_to_a = &a; // I still promise I won't change a int *ptr; ptr = ptr_to_a; (*ptr) = 5; // I'm a liar; a is now 5 I wanted to show this to a friend but now I'm missing a step. Does anyone know what's missing for it to start compiling and working? ATM I'm getting invalid conversion from 'const int*' to 'int*' but when I read the article I tried and it worked great.
you need to cast away the constness: linux ~ $ cat constTest.c #include <stdio.h> void modA( int *x ) { *x = 7; } int main( void ) { const int a = 3; // I promisse i won't change a int *ptr; ptr = (int*)( &a ); printf( "A=%d\n", a ); *ptr = 5; // I'm a liar, a is now 5 printf( "A=%d\n", a ); *((int*)(&a)) = 6; printf( "A=%d\n", a ); modA( (int*)( &a )); printf( "A=%d\n", a ); return 0; } linux ~ $ gcc constTest.c -o constTest linux ~ $ ./constTest A=3 A=5 A=6 A=7 linux ~ $ g++ constTest.c -o constTest linux ~ $ ./constTest A=3 A=3 A=3 A=3 also the common answer doesn't work in g++ 4.1.2 linux ~ $ cat constTest2.cpp #include <iostream> using namespace std; int main( void ) { const int a = 3; // I promisse i won't change a int *ptr; ptr = const_cast<int*>( &a ); cout << "A=" << a << endl; *ptr = 5; // I'm a liar, a is now 5 cout << "A=" << a << endl; return 0; } linux ~ $ g++ constTest2.cpp -o constTest2 linux ~ $ ./constTest2 A=3 A=3 linux ~ $ btw.. this is never recommended... I found that g++ doesn't allow this to happen.. so that may be the issue you are experiencing.
583,255
583,271
Is it a good practice to place C++ definitions in header files?
My personal style with C++ has always to put class declarations in an include file, and definitions in a .cpp file, very much like stipulated in Loki's answer to C++ Header Files, Code Separation. Admittedly, part of the reason I like this style probably has to do with all the years I spent coding Modula-2 and Ada, both of which have a similar scheme with specification files and body files. I have a coworker, much more knowledgeable in C++ than I, who is insisting that all C++ declarations should, where possible, include the definitions right there in the header file. He's not saying this is a valid alternate style, or even a slightly better style, but rather this is the new universally-accepted style that everyone is now using for C++. I'm not as limber as I used to be, so I'm not really anxious to scrabble up onto this bandwagon of his until I see a few more people up there with him. So how common is this idiom really? Just to give some structure to the answers: Is it now The Way™, very common, somewhat common, uncommon, or bug-out crazy?
Your coworker is wrong, the common way is and always has been to put code in .cpp files (or whatever extension you like) and declarations in headers. There is occasionally some merit to putting code in the header, this can allow more clever inlining by the compiler. But at the same time, it can destroy your compile times since all code has to be processed every time it is included by the compiler. Finally, it is often annoying to have circular object relationships (sometimes desired) when all the code is the headers. Bottom line, you were right, he is wrong. EDIT: I have been thinking about your question. There is one case where what he says is true. templates. Many newer "modern" libraries such as boost make heavy use of templates and often are "header only." However, this should only be done when dealing with templates as it is the only way to do it when dealing with them. EDIT: Some people would like a little more clarification, here's some thoughts on the downsides to writing "header only" code: If you search around, you will see quite a lot of people trying to find a way to reduce compile times when dealing with boost. For example: How to reduce compilation times with Boost Asio, which is seeing a 14s compile of a single 1K file with boost included. 14s may not seem to be "exploding", but it is certainly a lot longer than typical and can add up quite quickly when dealing with a large project. Header only libraries do affect compile times in a quite measurable way. We just tolerate it because boost is so useful. Additionally, there are many things which cannot be done in headers only (even boost has libraries you need to link to for certain parts such as threads, filesystem, etc). A Primary example is that you cannot have simple global objects in header only libs (unless you resort to the abomination that is a singleton) as you will run into multiple definition errors. NOTE: C++17's inline variables will make this particular example doable in the future. As a final point, when using boost as an example of header only code, a huge detail often gets missed. Boost is library, not user level code. so it doesn't change that often. In user code, if you put everything in headers, every little change will cause you to have to recompile the entire project. That's a monumental waste of time (and is not the case for libraries that don't change from compile to compile). When you split things between header/source and better yet, use forward declarations to reduce includes, you can save hours of recompiling when added up across a day.
583,786
681,550
Why do I get an amibguity error when I compile from the command line, but not from the IDE?
I am trying to compile a rather large project with Borland C++ Builder 5.5. The project compiles in the IDE, but is much too slow. However, when I compile with the command line I get an ambiguity error that was not present in the IDE: Error E2015 Project.h 536: Ambiguity between 'TTreeNode' and 'Comctrls::TTreeNode' My command line arguments are as follows: d:\PROGRA~1\Borland\CBUILD~1\bin..\BIN\bcc32 -Od -Vx -Ve -X- -r- -a8 -5 -b- -d -k -vi -c -tW -tWM -w-par -I[really big list of include files] -nQ:\output [really big list of files to compile] This command is generated by make.exe.
I believe the problem lies in the fact the command line compiler and the IDE compiler are different. The command line appears to be more strict about ambiguity whereas the IDE flags it only as a warning. In light of this, I guess some projects simply can't be built with the command line tools even if they build in the IDE.
583,821
583,898
How do I return hundreds of values from a C++ function?
In C++, whenever a function creates many (hundreds or thousands of) values, I used to have the caller pass an array that my function then fills with the output values: void computeValues(int input, std::vector<int>& output); So, the function will fill the vector output with the values it computes. But this is not really good C++ style, as I'm realizing now. The following function signature is better because it doesn't commit to using a std::vector, but could use any container: void computeValues(int input, std::insert_iterator<int> outputInserter); Now, the caller can call with some inserter: std::vector<int> values; // or could use deque, list, map, ... computeValues(input, std::back_inserter(values)); Again, we don't commit to using std::vector specifically, which is nice, because the user might just need the values in a std::set etc. (Should I pass the iterator by value or by reference?) My question is: Is the insert_iterator the right or standard way to do it? Or is there something even better? EDIT: I edited the question to make it clear that I'm not talking about returning two or three values, but rather hundreds or thousands. (Imagine you have return all the files you find in a certain directory, or all the edges in a graph etc.)
Response to Edit: Well, if you need to return hundreds and thousands if values, a tuple of course would not be the way to go. Best pick the solution with the iterator then, but it's best not use any specific iterator type. If you use iterators, you should use them as generic as possible. In your function you have used an insert iterator like insert_iterator< vector<int> >. You lost any genericity. Do it like this: template<typename OutputIterator> void computeValues(int input, OutputIterator output) { ... } Whatever you give it, it will work now. But it will not work if you have different types in the return set. You can use a tuple then. Also available as std::tuple in the next C++ Standard: boost::tuple<int, bool, char> computeValues(int input) { .... } If the amount of values is variadic and the type of the values is from a fixed set, like (int, bool, char), you can look into a container of boost::variant. This however implies changes only on the call-side. You can keep the iterator style of above: std::vector< boost::variant<int, bool, char> > data; computeValues(42, std::back_inserter(data));
583,955
584,022
Connecting to an mssql server from a remote machine gives Login failed for user ''
I get this error when I try to connect to a remote SQL server using this connection string. Error: ODBC error: 28000118452[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user ''. The user is not associated with a trusted SQL Server connection. Connection string: "DRIVER={SQL Server};SERVER=testserver,1433;Trusted_Connection={Yes};" Note this same connection string works fine if I specify the local computer. My question: Why does the remote SQL server think my username is blank ''? I did a valid login using the WNetAddConnection Win32 API to the remote machine first. Edit: I get the same error when connecting from Management studio. But I thought my program would have a higher chance of working since I established a connection to the remote machine first. Edit2: Note I really need a solution that uses Windows authentication. I already have it working with SQL authentication.
Thoughts: 1.) are both machines in the same domain? I am thinking probably so because of your references to making a connection with WNet*... If not, Integrated Security will give you problems. Edit: I see that both machines are not in the same domain. To use Integrated Security, the domain that the SQL Server is in must trust the domain your local machine is in. Another Edit: Corroboration for the above statement. From link: This error message can appear if the user logging in is a domain account from a different, untrusted domain from the SQL Server’s domain. The next step for this is either to move the client machine into the same domain as the SQL Server and set it up to use a domain account, or to set up mutual trust between the domains. Setting up mutual trust is a complicated procedure and should be done with a great deal of care and due security considerations. 2.) Check to be sure the SPNs are set properly on the server. Look HERE for more guidance, but basically you do: setspn -L servername one of the SPNs needs to look like: MSSQLSvc/servername:1433 3.) One more Edit: If neither machine is in a domain, all you need to do is have a local userid/password that matches on both machines. For example, a user named brian on both machines, and both users passwords are 'letmein'.
583,978
584,109
Is it possible to get a valid token from a remote computer?
Is it possible to impersonate a u/p on a remote computer? Ideally I would like to call the ImpersonateLoggedOnUser with a token I would obtain from logging into a remote computer. I know I can make a valid connection using wnet functions, but just don't know about impersonation.
Brian: I'm not sure whether you can. At the very least, you may need some way to indicate which logged on user (fast user switching and terminal services means that there may be more than one logged on user). Raymond Chen blogged about this once, but there was no solution offered (I'm not sure if there is one, unless maybe you can assume that there will only be one, but given that Vista allows fast user switching on a domain, I'm not sure that you can make that assumption). For what it's worth, the blog entry is here: http://blogs.msdn.com/oldnewthing/archive/2006/08/22/712677.aspx
584,041
584,077
How do I build an import library (.lib) AND a DLL in Visual C++?
I want to have a single Visual Studio project that builds a DLL file and an import library (.lib) file. (An import library is a statically-linked library that takes care of loading that DLL file in other projects that use it). So I went to Visual Studio C++ 2008 Express Edition, created a New Project of type Class Library, and set the "Configuration Type" to be "Dyanamic Library (.dll)". But when I build the solution, the only relevant output file I see is a DLL file; I don't see any LIB file getting generated. I looked in the project directory and all subdirectories (Release and Debug). I believe that it is possible to build a LIB and a DLL file at the same time because on the MSDN it says "The linker creates the import library when the DLL is built." Also, another user of this website is creating LIB and DLL files at the same time using Visual C++. So how can I do it?
By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++. Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'. You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.
584,388
584,397
C++ Library for modifying a ZIP file in place
I'm looking for a way to add or remove files to/from an existing ZIP archive, or any other archive format for that matter as long as there are cross platform APIs, without having to rewrite a new zip file with new files added to it, or sans items deleted from it. With ZIP files, the catalog is placed at the end of the file so that, and some parts of the zip file will likely have to be rewritten each time. I'm just trying to avoid having to rewrite the whole thing every time. The archive files I'm looking at dealing with will be large, and speed is important. Is there any C++ library out there that does what I'm looking for?
Zipios++ provides direct access to files inside ZIP archives.
584,503
584,509
Different methods to use a class/struct - C++
struct Foo { void SayHello() { std::cout << "Hi, I am Foo"; } }; I have the above given struct. I have seen a usage like this in one of our code base. Foo foo; { foo.SayHello(); } IMO, It does same like Foo foo; foo.SayHello(); Or is there any advantage/difference for the first method? Any thoughts?
In that particular case, it looks quite strange and like a candidate for review. Can be useful in other cases: Foo foo; { ReturnValue v = foo.SayHello(); Send(v); } ... Where it would limit the scope of v. One common use is to make the objects in it destroy earlier. Classes that do special stuff in their constructor and destructor can then be used inside the braces: Foo foo; { MutexLocker locker(sendMutex); ReturnValue v = foo.SayHello(); Send(v); } ... The lock for the send-queue would be held while sending v in that example, and be released when the locker is destroyed at the closing brace.
584,544
586,051
Are there alternatives to polymorphism in C++?
The CRTP is suggested in this question about dynamic polymorphism. However, this pattern is allegedly only useful for static polymorphism. The design I am looking at seems to be hampered speedwise by virtual function calls, as hinted at here. A speedup of even 2.5x would be fantastic. The classes in question are simple and can be coded completely inline, however it is not known until runtime which classes will be used. Furthermore, they may be chained, in any order, heaping performance insult onto injury. Any suggestions (including how the CRTP can be used in this case) welcome. Edit: Googling turns up a mention of function templates. These look promising.
I agree with m-sharp that you're not going to avoid runtime polymorphism. If you value optimisation over elegance, try replacing say void invoke_trivial_on_all(const std::vector<Base*>& v) { for (int i=0;i<v.size();i++) v[i]->trivial_virtual_method(); } with something like void invoke_trivial_on_all(const std::vector<Base*>& v) { for (int i=0;i<v.size();i++) { if (v[i]->tag==FooTag) static_cast<Foo*>(v[i])->Foo::trivial_virtual_method(); else if (v[i]->tag==BarTag) static_cast<Bar*>(v[i])->Bar::trivial_virtual_method(); else... } } it's not pretty, certainly not OOP (more a reversion to what you might do in good old 'C') but if the virtual methods are trivial enough you should get a function with no calls (subject to good enough compiler & optimisation options). A variant using dynamic_cast or typeid might be slightly more elegant/safe but beware that those features have their own overhead which is probably comparable to a virtual call anyway. Where you'll most likely see an improvement from the above is if some classes methods are no-ops, and it saved you from calling them, or if the functions contain common loop-invariant code and the optimiser manages to hoist it out of the loop.
584,599
584,611
When is it appropriate to use C++ exceptions?
I'm trying to design a class that needs to dynamically allocate some memory.. I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me.. Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully? Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail.. EDIT: The consensus seems to be that running out of memory IS an exceptional case. Will see how to go about this.. Thanks.. :)
Assuming you are using new to allocate memory, and are not overriding the new operator, it will automatically throw the std::bad_alloc exception if it fails to allocate memory properly. I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me.. Running out of memory seems like a pretty exceptional case to me :) It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really. There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the bad_alloc exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :)
584,734
584,743
Gui toolkits, which should I use?
I am writing a fairly large and complex data analysis program and I have reached the point where I think it is about time to build a GUI for the program. So my question is: Which GUI toolkit should I use? I am completely new to coding and building GUIs and would appreciate any guidance that can be offered. It doesn't have to be the simplest tool kit in the world, I learn rather fast. However, it does need to be able to do the following things (some if not all of these are probably incredibly basic for any given toolkit but I thought that it would be good to throw all this out there just in case). It has to allow me to draw directly to the screen so that I can put graphs (spectra really), plots and things like them up for the user to see. I need to be able to collect position information on where they clicked on aforementioned spectra. I need to be able to display text and take text input from the user. It needs to be able to generate menus (you know File, Edit, etc). If it were to have some built in widget for generating tables that would be handy (though I can surmount a lack of that if I can draw directly to the screen). It needs to be able to pop up warnings, dialogue boxes, save and open boxes, etc. That is pretty much it, most of these seem pretty basic when I write them out but I don't want to get the GUI partly coded and then realize that I I need to rewrite it with a different toolkit. It should be noted that I have written this program in C++ and that I don't want to have to write the GUI part in C or something else so the toolkit needs to support C++. Additionally a cross platform toolkit would be preferable over a single platform toolkit. However if it must be a single platform toolkit then I would prefer it be for Linux. Finally, I would DRAMATICALLY prefer an open source toolkit to a closed source toolkit. Beyond that I cannot think of anything to add. Thank you in advance for your time and answers. Hmmm based on the answers I shall look at both Qt and wxWidgets and see which appeals to me more. I with I could accept multiple answers as accepted but I can't, and since I am looking at two things it would be unfair to only accept one of the answers, perhaps in a week or two then I have looked at the toolkits and figured out which I want to use.
For C++, in my opinion, Qt is the least frustrating and most fully featured toolkit. Its also fully cross platform. Note that Qt will be LGPL licensed some time in March 2009, when version 4.5 becomes available. Currently, its only offered in a GPL and commercial license version. Qt's GUI designer is good. It has lots of utility functions (scene graph library, translation support, built-in Javascript engine, built-in WebKit library). Via the MOC (a special pre-compiler) it also brings a few run-time binding capabilities and introspection to C++. For your technical application, you might find that Qwt (http://qwt.sourceforge.net/) provides what you need. It is built upon Qt. Qt can even be used "headless" if you want its utility support (such as networking, etc) without a GUI. The other cross platform C++ option is wxWidgets, which is usable but not really comparable to Qt. Its a much lower level toolkit, and isn't as easy to use or fully rounded. Gtkmm is another option, in the spirit of GTK+.
584,824
584,835
Guaranteed lifetime of temporary in C++?
Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here's an example class: class StringBuffer { public: StringBuffer(std::string & str) : m_str(str) { m_buffer.push_back(0); } ~StringBuffer() { m_str = &m_buffer[0]; } char * Size(int maxlength) { m_buffer.resize(maxlength + 1, 0); return &m_buffer[0]; } private: std::string & m_str; std::vector<char> m_buffer; }; And here's how you would use it: // this is from a crusty old API that can't be changed void GetString(char * str, int maxlength); std::string mystring; GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN); When will the destructor for the temporary StringBuffer object get called? Is it: Before the call to GetString? After GetString returns? Compiler dependent? I know that C++ guarantees that a local temporary variable will be valid as long as there's a reference to it - does this apply to parent objects when there's a reference to a member variable? Thanks.
The destructor for that sort of temporaries is called at the end of the full-expression. That's the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice. It's in fact what makes expression templates work: They can keep hold references to that sort of temporaries in an expression like e = a + b * c / d Because every temporary will last until the expression x = y Is evaluated completely. It's quite concisely described in 12.2 Temporary objects in the Standard.
584,825
585,298
dSYM Directories While Compiling C++ Code in MacOS
Why compiling C++ in Mac always create *.dSYM directories? Is there a way to disable that?
It's because your Xcode project is set up to build debug symbols with an external dSYM file. This is actually very handy for release builds, as it means that you can strip debug symbols from your app, and when a user sends a crashdump to you, you can use the original dSYM file to generate a proper stacktrace for debugging. Anyways, you don't need to disable debug symbol generation in your project. Instead, just change the debug symbol type to DWARF (instead of "DWARF with dSYM File"). You can also use Stabs, but that's the old format. Edit: Ah, I see you meant from the command line, not from Xcode. I'm not sitting in front of my mac atm, but I see from the gcc4 manpage than you can specify -gstabs to use the Stabs format.
585,257
585,274
Is there a better way to reverse an array of bytes in memory?
typedef unsigned char Byte; ... void ReverseBytes( void *start, int size ) { Byte *buffer = (Byte *)(start); for( int i = 0; i < size / 2; i++ ) { std::swap( buffer[i], buffer[size - i - 1] ); } } What this method does right now is it reverses bytes in memory. What I would like to know is, is there a better way to get the same effect? The whole "size / 2" part seems like a bad thing, but I'm not sure. EDIT: I just realized how bad the title I put for this question was, so I [hopefully] fixed it.
The standard library has a std::reverse function: #include <algorithm> void ReverseBytes( void *start, int size ) { char *istart = start, *iend = istart + size; std::reverse(istart, iend); }
585,351
585,360
running msbuild without having VS installed
I'm trying to run msbuild on a solution that has some C++ code in it. I have the SDK installed but not Visual Studio. I get the following error: error MSB3411: Could not load the Visual C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5, or 2) install Microsoft Visual Studio 2008. I have vcbuild.exe under C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcpackages How can make MSBuild find it?
It might be as simple as vcbuild.exe not being in the path. IIRC, at least the visual studio installer doesn't automatically add the command line tools to the system or user path and you have to run vcvars32.bat to set them first before you can kick off the build.
585,913
585,932
C++ member function virtual override and overload at the same time
If I have a code like this: struct A { virtual void f(int) {} virtual void f(void*) {} }; struct B : public A { void f(int) {} }; struct C : public B { void f(void*) {} }; int main() { C c; c.f(1); return 0; } I get an error that says that I am trying to do an invalid conversion from int to void*. Why can't compiler figure out that he has to call B::f, since both functions are declared as virtual? After reading jalf's answer I went and reduced it even further. This one does not work as well. Not very intuitive. struct A { virtual void f(int) {} }; struct B : public A { void f(void*) {} }; int main() { B b; b.f(1); return 0; }
The short answer is "because that's how overload resolution works in C++". The compiler searches for functions F inside the C class, and if it finds any, it stops the search, and tries to pick a candidate among those. It only looks inside base classes if no matching functions were found in the derived class. However, you can explicitly introduce the base class functions into the derived class' namespace: struct C : public B { void f(void*) {} using B::f; // Add B's f function to C's namespace, allowing it to participate in overload resolution };
586,009
595,677
Inheritance issues with template classes
I'm having issues with a very strange error in some code I wrote. The basic idea behind the code can be trivialised in the following example: template <class f, class g> class Ptr; template <class a, class b, class c = Ptr<a,b> > class Base { public: Base(){}; }; template <class d, class e> class Derived : public Base <d,e> { public: Derived(){}; }; template <class f, class g> class Ptr { public: Ptr(){}; Ptr(Base<f,g,Ptr<f,g> >* a){}; }; typedef Derived<double,double> DDerived; int main() { Base<int,int> b = Base<int,int>(); Derived<double,double> d = Derived<double,double>(); DDerived dd = DDerived(); Ptr<double,double> p(&dd); return 1; } The basic idea is that pointers are replaced by the Ptr class (This will eventually be used in an MPI setting so standard pointers are effectively useless). The pointers are designed to 'point' at the base class, and so can point at any inherited class (as demonstrated in the example). Can anyone think of any reason this might not work in a non-trivial case (But a case where the object architecture remains identical). The error that is occurring in the main case is as follows: void function() { vector nVector(1); // cut down for simplicity nVector[0].SetId(1); // To ensure the node is instantiated correctly Ptr temp(&nVector[1]); }; This code produces the (slightly extended version of the) error when compiled with MPICXX: no matching function for call to Ptr&lt;double, double>::Ptr(Derived&lt;double, double>*) candidates are . . . (Some removed for simplicity's sake) Ptr&lt;f, g>::Ptr(Base&lt;f, g, Ptr&lt;f, g> >*) [with f = double, g = double] Cheers, Ed EDITED (Detailing the error a little better, added info on the compiler)
Unfortunately, I was being slightly stupid and had forgotten to put my Ptr class in the same namespace as the Base and Derived classes. That, I guess, would be why it wasn't working ! =]
586,410
586,439
Table layout using std::cout
How do I format my output in C++ streams to print fixed width left-aligned tables? Something like printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345); poducing 12345.123 12345.123
Include the standard header <iomanip> and go crazy. Specifically, the setw manipulator sets the output width. setfill sets the filling character.
586,609
586,670
Using SSE instructions
I have a loop written in C++ which is executed for each element of a big integer array. Inside the loop, I mask some bits of the integer and then find the min and max values. I heard that if I use SSE instructions for these operations it will run much faster compared to a normal loop written using bitwise AND , and if-else conditions. My question is should I go for these SSE instructions? Also, what happens if my code runs on a different processor? Will it still work or these instructions are processor specific?
SSE instructions are processor specific. You can look up which processor supports which SSE version on wikipedia. If SSE code will be faster or not depends on many factors: The first is of course whether the problem is memory-bound or CPU-bound. If the memory bus is the bottleneck SSE will not help much. Try simplifying your integer calculations, if that makes the code faster, it's probably CPU-bound, and you have a good chance of speeding it up. Be aware that writing SIMD-code is a lot harder than writing C++-code, and that the resulting code is much harder to change. Always keep the C++ code up to date, you'll want it as a comment and to check the correctness of your assembler code. Think about using a library like the IPP, that implements common low-level SIMD operations optimized for various processors.
586,727
586,837
What approach works best for quickly reading files off of optical drives?
When reading files off of a hard drive, mmap is generally regarded as a good way to quickly get data into memory. When working with optical drives, accesses take more time and you have a higher latency to worry about. What approach/abstraction do you use to hide/eliminate as much latency and/or overall load time of the optical drive as possible?
There's no real abstraction you can employ. Optical drives have very specific characteristics that must be optimized for to get the best performance. Some tips: The biggest killer on optical drives is seek time. Where possible make sure all the files you are reading are sequential on disc and as closely packed as possible. If you must seek then seek in one direction and as infrequently as possible. Asynchronous reading can also massively improve performance. If you need to load and process files A,B & C then before processing A you should start reading file B, and while processing B you should be reading file C and so on. Generally the more data you can read in one go the better, e.g avoid lots of little reads(). You will only get the theoretical throughput of a disc while reading large amounts of data. Some OS's /drivers will minimize the penalty of reading lots of little files by caching sectors, some will not. Doing lots of exists(filename) checking can also be detrimental on some filesystems / OSs where only parts of the TOC are cached. In our applications we usually pack files into one or more "lumped" files and have them ordered sequentially based on their access order. Some files (and directories) are compressed and read in their entirety before being decompressed in memory. This can be a win if you have a directory that contains a multitude of small files (e.g XML or scripts). Basically lots of benchmarking and tweaking :)
586,734
586,831
Pass an element from C type string array to a COM object as BSTR? (in C++)
I am writing a C++ DLL that is called by an external program. 1.) I take an array of strings (as char *var) as an argument from this program. 2.) I want to iterate through this array and call a COM function on each element of the string array. The COM function must take a BSTR: DLL_EXPORT(void) runUnitModel(char *rateMaterialTypeNames) { HRESULT hr = CoInitialize(NULL); // Create the interface pointer. IUnitModelPtr pIUnit(__uuidof(BlastFurnaceUnitModel)); pIUnit->initialiseUnitModel(); int i; for(i=0; i < sizeOfPortRatesArray; i++) pIUnit->createPort(SysAllocString(BSTR((const char *)rateMaterialTypeNames[i]))); I think its the SysAllocString(BSTR((const char *)rateMaterialTypeNames[i])) bit that is giving me problems. I get an access violation when the programs runs. Is this the right way to access the value of the rateMaterialTypeName at i? Note I am expecting something like "IronOre" as the value at i, not a single character.
If you're using Microsofts ATL, you can use the CComBSTR class. It will accept a char* and create a BSTR from it, also, you don't need to worry about deleting the BSTR, all that happens in the dtor for CComBSTR. Also, see Matthew Xaviers answer, it doesn't look like you're passing your array of strings into that function properly. Hope this helps
587,070
587,116
C++ constructor syntax
Simple question: are the following statements equivalent? or is the second one doing more implicit things behind the scenes (if so, what?) myClass x(3); myClass x = myClass(3); Thanks!
They are not completely identical. The first is called "direct initialization" while the second is called "copy initialization". Now, the Standard makes up two rules. The first is for direct initialization and for copy initialization where the initializer is of the type of the initialized object. The second rule is for copy initialization in other cases. So, from that point of view both are termed in one - the first - rule. In the case where you have copy initialization with the same type, the compiler is allowed to elide a copy, so it can construct the temporary you create directly into the initialized object. So you can end up very well with the same code generated. But the copy constructor, even if the copy is elided (optimized out), must still be available. I.e if you have a private copy constructor, that code is invalid if the code in which it appears has no access to it. The second is called copy-initialization, because if the type of the initializer is of a different type, a temporary object is created in trying to implicitly convert the right side to the left side: myclass c = 3; The compiler creates a temporary object of the type of myclass then when there is a constructor that takes an int. Then it initializes the object with that temporary. Also in this case, the temporary created can be created directly in the initialized object. You can follow these steps by printing messages in constructors / destructors of your class and using the option -fno-elide-constructors for GCC. It does not try to elide copies then. On a side-note, that code above has nothing to do with an assignment operator. In both cases, what happens is an initialization.
587,128
587,139
What exactly is va_end for? Is it always necessary to call it?
va_end - Macro to reset arg_ptr. After accessing a variable argument list, the arg_ptr pointer is usually reset with va_end(). I understand that it is required if you want to re-iterate the list, but is it really needed if you aren't going to? Is it just good practice, like the rule "always have a default: in your switch"?
va_end is used to do cleanup. You don't want to smash the stack, do you? From man va_start: va_end() Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function. After the call va_end(ap) the variable ap is undefined. Multiple traversals of the list, each bracketed by va_start() and va_end() are possible. va_end() may be a macro or a function. Note the presence of the word must. The stack could become corrupted because you don't know what va_start() is doing. The va_* macros are meant to be treated as black boxes. Every compiler on every platform can do whatever it wants there. It may do nothing, or it may do a lot. Some ABIs pass the first few args in registers, and the remainder on the stack. A va_arg() there may be more complicated. You can look up how a given implementation does varargs, which may be interesting, but in writing portable code you should treat them as opaque operations.