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
155,378
155,397
How to alter a float by its smallest increment (or close to it)?
I have a double value f and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original. It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original.
Check your math.h file. If you're lucky you have the nextafter and nextafterf functions defined. They do exactly what you want in a portable and platform independent way and are part of the C99 standard. Another way to do it (could be a fallback solution) is to decompose your float into the mantissa and exponent part. Incrementing is easy: Just add one to the mantissa. If you get an overflow you have to handle this by incrementing your exponent. Decrementing works the same way. EDIT: As pointed out in the comments it is sufficient to just increment the float in it's binary representation. The mantissa-overflow will increment the exponent, and that's exactly what we want. That's in a nutshell the same thing that nextafter does. This won't be completely portable though. You would have to deal with endianess and the fact that not all machines do have IEEE floats (ok - the last reason is more academic). Also handling NAN's and infinites can be a bit tricky. You cannot simply increment them as they are by definition not numbers.
155,930
155,946
Launch web page from my application in Linux
I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build. Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running. For windows I use: ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); For Linux I currently use: pid_t pid; char *args[2]; char *prog=0; char firefox[]={"/usr/bin/firefox"}; if(strstri(filename,".html")) prog=firefox; if(prog) { args[0]=(char *)filename; args[1]=0; pid=fork(); if(!pid) execvp(prog,args); }
If you're writing this for modern distros, you can use xdg-open: $ xdg-open http://google.com/ If you're on an older version you'll have to use a desktop-specific command like gnome-open or exo-open.
156,257
156,420
AI Applications in C++: How costly are virtual functions? What are the possible optimizations?
In an AI application I am writing in C++, there is not much numerical computation there are lot of structures for which run-time polymorphism is needed very often, several polymorphic structures interact during computation In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. Update: Also see the following related forums: Performance Penalty for Interface, Several Levels of Base Classes
Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately: classptr -> [vtable:4][classdata:x] vtable -> [first:4][second:4][third:4][fourth:4][...] first -> [code:x] second -> [code:x] ... The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache. This example from msdn shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically. CONST SEGMENT ??_7A@@6B@ DD FLAT:?func1@A@@UAEXXZ DD FLAT:?func2@A@@UAEXXZ DD FLAT:?func3@A@@UAEXXZ CONST ENDS The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the example from msdn: ; A* pa; ; pa->func3(); mov eax, DWORD PTR _pa$[ebp] mov edx, DWORD PTR [eax] mov ecx, DWORD PTR _pa$[ebp] call DWORD PTR [edx+8] In this example ebp, the stack frame base pointer, has the variable A* pa at zero offset. The register eax is loaded with the value at location [ebp], so it has the A*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents "this" it now holds the A*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable. If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small.
156,278
156,321
Does setbuf() affect cout?
Yet again, my teacher was unable to answer my question. I knew who may be able to... So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put setbuf( stdout , NULL ); at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly. My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? Thanks in advance!
By default, iostreams and stdio are synchronised. Reference. This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise std::endl or std::flush (from <ostream>), which may help you. e.g., std::cout << "Hello, world!" << std::endl; or std::cout << "Hello, world!\n" << std::flush; Both of these do the same thing. (std::endl = print endline, then flush.)
156,373
156,382
Using .reset() to free a boost::shared_ptr with sole ownership
I'm storing an object (TTF_Font) in a shared_ptr that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr is also provided a "freeing" functor. // Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr<TTF_Font> screenFont; screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); If, later, I need to explicitly free this object is it correct to do this: screenFont.reset(); And then let screenFont (the actual shared_ptr object) be destroyed naturally?
shared_ptr<>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed. So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen. To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed.
156,438
156,458
What Does It Mean For a C++ Function To Be Inline?
See title: what does it mean for a C++ function to be inline?
The function is placed in the code, rather than being called, similar to using macros (conceptually). This can improve speed (no function call), but causes code bloat (if the function is used 100 times, you now have 100 copies). You should note this does not force the compiler to make the function inline, and it will ignore you if it thinks its a bad idea. Similarly the compiler may decide to make normal functions inline for you. This also allows you to place the entire function in a header file, rather than implementing it in a cpp file (which you can't anyways, since then you get an unresolved external if it was declared inline, unless of course only that cpp file used it).
156,936
157,098
How can I expose iterators without exposing the container used?
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help. I would like to expose an iterator for a class like this: template <class T> class MyContainer { public: // Here is the problem: // typedef for MyIterator without exposing std::vector publicly? MyIterator Begin() { return mHiddenContainerImpl.begin(); } MyIterator End() { return mHiddenContainerImpl.end(); } private: std::vector<T> mHiddenContainerImpl; }; Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container...
You may find the following article interesting as it addresses exactly the problem you have posted: On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It
157,211
157,228
Open-source fractal maps
I'm interested in creating a game that uses fractal maps for more realistic geography. However, the only fractal map programs I have found are Windows-only, for example Fractal Mapper. Needless to say, they are also not open-sourced. Are there any open-sourced fractal map creators available, preferably in Python or C/C++? Ideally I would like something that can be "plugged into" a program, rather then being standalone.
Fracplanet may be of use.
158,585
158,614
How do you add a timed delay to a C++ program?
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at? I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.
In Win32: #include<windows.h> Sleep(milliseconds); In Unix: #include<unistd.h> unsigned int microsecond = 1000000; usleep(3 * microsecond);//sleeps for 3 second sleep() only takes a number of seconds which is often too long.
158,628
158,669
Marshal C++ "string" class in C# P/Invoke
I have a function in a native DLL defined as follows: #include <string> void SetPath(string path); I tried to put this in Microsoft's P/Invoke Interop Assistant, but it chokes on the "string" class (which I think is from MFC?). I have tried marshaling it as a variety of different types (C# String, char[], byte[]) but every time I either get a NotSupportedException or a Native Assembly Exception (depending on what marshaling I tried). As anyone ever done Native/Managed Interop where the native string class is used? Is there any way to Marshal this? Am I going to have to write my own Marshaler?
Looks like you're trying to use the C++ standard library string class. I doubt that will be easy to Marshal. Better to stick with a char * and Marshal as StringBuilder. That's what I usually do. You'll have to add a wrapper that generates the C++ string for you.
159,006
159,018
Max and min values in a C++ enum
Is there a way to find the maximum and minimum defined values of an enum in c++?
No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example, enum MyPretendEnum { Apples, Oranges, Pears, Bananas, First = Apples, Last = Bananas }; There do not need to be named values for every value between First and Last.
159,034
159,073
Are C++ enums signed or unsigned?
Are C++ enums signed or unsigned? And by extension is it safe to validate an input by checking that it is <= your max value, and leave out >= your min value (assuming you started at 0 and incremented by 1)?
You shouldn't rely on any specific representation. Read the following link. Also, the standard says that it is implementation-defined which integral type is used as the underlying type for an enum, except that it shall not be larger than int, unless some value cannot fit into int or an unsigned int. In short: you cannot rely on an enum being either signed or unsigned.
159,103
159,109
Is it possible to use a C++ .lib file from within a C# program?
Is it possible to use a C++ .lib file from within a C# program?
No. You can only use a full .dll from a C# program.
159,298
162,265
How do you compile static pthread-win32 lib for x64?
It looks like some work has been done to make pthread-win32 work with x64, but there are no build instructions. I have tried simly building with the Visual Studio x64 Cross Tools Command Prompt, but when I try to link to the lib from an x64 application, it can't see any of the function exports. It seems like it is still compiling the lib as x86 or something. I've even tried adding /MACHINE to the makefile in the appropriate places, but it doesn't help. Has anyone gotten this to work?
Until it's officially released, it looks like you have to check out the CVS head to get version 2.9 of the library. Version 2.9 has all the x64 patches, but you will still have problems if you try to compile the static library from the command line. The only workaround I know of is to use the DLLs instead of statically linking the LIB.
159,339
159,385
C++ compile-time expression as an array size
I'm not sure if the term's actually "Array Addition". I'm trying to understand what does the following line do: int var[2 + 1] = {2, 1}; How is that different from int var[3]? I've been using Java for several years, so I'd appreciate if explained using Java-friendly words. Edit: Thousands of thanks to everyone who helped me out, Occam's Razor applies here.
It's not different. C++ allows expressions (even non-constant expressions) in the subscripts of array declarations (with some limitations; anything other than the initial subscript on a multi-dimensional array must be constant). int var[]; // illegal int var[] = {2,1}; // automatically sized to 2 int var[3] = {2,1}; // equivalent to {2,1,0}: anything not specified is zero int var[3]; // however, with no initializer, nothing is initialized to zero Perhaps the code you are reading writes 2 + 1 instead of 3 as a reminder that a trailing 0 is intentional.
159,442
159,462
What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?
This seems like a pretty softball question, but I always have a hard time looking up this function because there seem there are so many variations regarding the referencing of char and tchar.
MultiByteToWideChar but also see "A few of the gotchas of MultiByteToWideChar".
159,983
160,003
How can I create a temporary file for writing in C++ on a Linux platform?
In C++, on Linux, how can I write a function to return a temporary filename that I can then open for writing? The filename should be as unique as possible, so that another process using the same function won't get the same name.
Use one of the standard library "mktemp" functions: mktemp/mkstemp/mkstemps/mkdtemp. Edit: plain mktemp can be insecure - mkstemp is preferred.
160,147
160,164
Catching exceptions from a constructor's initializer list
Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so: class A { public: A(const B& b): mB(b) { }; private: B mB; }; Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?
Have a read of http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/) Edit: After more digging, these are called "Function try blocks". I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :) To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be: C::C() try : init1(), ..., initn() { // Constructor } catch(...) { // Handle exception }
160,379
160,397
Improving the quality of code?
So, in reading this site, it seems that the shop in which I work does a lot of things wrong and some things right. How can I improve the code that I work with from my colleagues? The only thing I can think of is to lead by example - start using Boost, etc. Any other thoughts?
You probably have to look more closely at what it is your shop does wrong and what they do right. What can you actually change there? What can you change about your own practices that will improve your skills or that of your team? It can be difficult to realize change in an entrenched shop. Try proposing code reviews (on your code first), which could lead to discussion. For tangible items, I'd look at Scott Meyers' Effective C++, etc. Develop your skillset and you will either help improve others around you or move on to a shop that will. Also, look at the Gang of Four's Design Patterns book.
160,793
161,120
Is there build farm for checking open source apps against different OS'es?
I have an Open Source app and I have it working on Windows, Linux and Macintosh ( it's in C++ and built with gcc ). I've only tested it on a few different flavors of Linux so I don't know if it compiles and runs on all different Linux versions. Is there a place where I can upload my code and have it tested across a bunch of different systems like other Linux flavors and things like, Solaris, FreeBSD and other operating systems? What would be great is if I can have it directly connect to my svn repository and grab the latest code and then email me back any compile errors generated and what the OS was that it had a problem with. I would be happy to just know it compiles as it is a GUI based app so I wouldn't expect it to actually be ran and tested.
There are a few options but there don't appear to be many (any?) free services like this, which isn't surprising considering the amount of effort and resources it requires. Sourceforge used to operate a compile farm like what you describe but it shut down a year or so ago. You might look into some of the following. If you're inclined to pay for a service or roll your own, then some of these links may be useful. If you're just looking for a free open source compile/build farm that covers multiple platforms it looks like you're pretty much out of luck. OpenSuse Build Service Mentioned by Ted first, worth repeating - only for Linux currently but does support a number of distros. GCC Compile Farm Mainly focused on testing builds for GCC but does also host a few other projects such as coLinux, BTG BitTorrent client, ClamAV, and others. May be something you can take advantage of, though I don't see what OSes are in the compile farm (contains at least Linux and Solaris based on the page notes). BuildLocker BuildLocker is a Web-based continuous integration solution for Java and .NET projects. BuildLocker is a virtual dedicated build machine that helps teams find bugs earlier in the development cycle, saving time and money. BuildLocker manages scheduled automated builds of source code in your ProjectLocker Source Control repository. Just check in the source code, and scheduled builds validate the integrity of the code. BuildLocker can even run automated tests, and can alert you anytime a test fails. CruiseControl CruiseControl is a framework for a continuous build process. It includes, but is not limited to, plugins for email notification, Ant, and various source control tools. A web interface is provided to view the details of the current and previous builds. Interesting side note, CruiseControl is actually used by StackOverflow's dev team for automated build testing as well, according to the podcast. Hudson Hudson monitors executions of repeated jobs, such as building a software project or jobs run by cron. RunCodeRun Mentioned in the other linked question, only supports Ruby projects and is in private beta currently. However, if your project is in Ruby, it might be worth keeping an eye on RunCodeRun. CI Feature Matrix There are many Continuous Integration systems available. This page is an attempt to keep an unbiased comparison of as many as possible of them.
160,973
160,978
Visual Studio 2005 locks up when attaching to process
I have a simple C++ DLL that implements a few custom actions for a WiX installer. Debugging the custom actions is usually simple: put up a temporary dialog box at the beginning of the action, and attach to the process when the dialog box appears. But today, whenever I attach to the process, I get the "Microsoft Visual Studio is Busy" bubble appearing at the bottom of the screen. I cannot figure out where this is coming from. Any ideas?
After hours of trying to figure this out, I realized that the problem was that I had debugging symbols enabled in Tools->Options->Debugging->Symbols. The latency in looking up symbols was leading to the apparent lockup. Clearing the "Search the above locations only when symbols are loaded manually" seems to have alleviated the problem.
160,974
161,039
How to typedef a pointer to method which returns a pointer the method?
Basically I have the following class: class StateMachine { ... StateMethod stateA(); StateMethod stateB(); ... }; The methods stateA() and stateB() should be able return pointers to stateA() and stateB(). How to typedef the StateMethod?
GotW #57 says to use a proxy class with an implicit conversion for this very purpose. struct StateMethod; typedef StateMethod (StateMachine:: *FuncPtr)(); struct StateMethod { StateMethod( FuncPtr pp ) : p( pp ) { } operator FuncPtr() { return p; } FuncPtr p; }; class StateMachine { StateMethod stateA(); StateMethod stateB(); }; int main() { StateMachine *fsm = new StateMachine(); FuncPtr a = fsm->stateA(); // natural usage syntax return 0; } StateMethod StateMachine::stateA { return stateA; // natural return syntax } StateMethod StateMachine::stateB { return stateB; } This solution has three main strengths: It solves the problem as required. Better still, it's type-safe and portable. Its machinery is transparent: You get natural syntax for the caller/user, and natural syntax for the function's own "return stateA;" statement. It probably has zero overhead: On modern compilers, the proxy class, with its storage and functions, should inline and optimize away to nothing.
161,053
161,061
Which is faster: Stack allocation or Heap allocation
This question may sound fairly elementary, but this is a debate I had with another developer I work with. I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same performance wise. I was always under the impression that growing the stack was constant time, and heap allocation's performance depended on the current complexity of the heap for both allocation (finding a hole of the proper size) and de-allocating (collapsing holes to reduce fragmentation, as many standard library implementations take time to do this during deletes if I am not mistaken). This strikes me as something that would probably be very compiler dependent. For this project in particular I am using a Metrowerks compiler for the PPC architecture. Insight on this combination would be most helpful, but in general, for GCC, and MSVC++, what is the case? Is heap allocation not as high performing as stack allocation? Is there no difference? Or are the differences so minute it becomes pointless micro-optimization.
Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches. Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.
161,166
161,239
Is it safe to increase an iterator inside when using it as an argument?
Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?) Anyways I want to write: myIter = mySet.erase(myIter); But GCC doesn't like it... So Is it safe to write this instead? mySet.erase(myIter++); Edit: And yes I'm checking against mySet.end();
There is no problem with mySet.erase(myIter++); The order of operation is well-defined: myIter is copied into myTempIter, myIter is incremented, and myTempIter is then given to the erase method. For Greg and Mark: no, there is no way operator++ can perform operations after the call to erase. By definition, erase() is called after operator++ has returned.
161,490
162,503
Referenced structure not 'sticking'
I am currently porting a lot of code from an MFC-based application to a DLL for client branding purposes. I've come across an unusual problem. This bit of code is the same in both systems: // ... CCommsProperties props; pController->GetProperties( props ); if (props.handshake != HANDSHAKE_RTS_CTS) { props.handshake = HANDSHAKE_RTS_CTS; pController->RefreshCommProperties( props ); } // ... in another file: void CControllerSI::RefreshCommProperties ( const CCommsProperties& props ) { // ... code ... } CommProperties is a wrapper for the comm settings, serialization of etc. and pController is of type ControllerSI which itself is a layer between the actual Comms and the Application. On the original MFC version the setting of handshake to RTS-CTS sticks but when running as the DLL version it resets itself to 0 as soon as the function is entered. The code is contained entirely in the DLL section of the code, so there are no boundaries. The main differences between the original and the new modules is the variables that call the various dialogs have been removed and the removed #includes I've lost an afternoon to this and I don't really want to lose any more...
After Saratv posting, I decided to ditch what I had done and restart it from working source again. This time however it works...I guess I will never know why passing a structure caused it to change.
161,540
162,170
Where is GDB documentation specific to the Cell Linux environment?
Where can documentation be found for the features of GDB, and the debugging process, specific to debugging of Cell Linux programs mixing PPU and SPU code?
Documents at the IBM developerWorks site for Cell can be found here: Cell @developerWorks You sound like you'd want the Programmer's Guide, which goes through debugging Cell applications. Edit to add sample topics: Chapter 3. Debugging Cell BE applications ... Debugging PPE code Debugging SPE code ... Debugging in the Cell BE environment Debugging multithreaded code Debugging architecture Switching architectures within a single thread ... Using the combined debugger ...
161,672
161,684
C++ class initialisation containing class variable initialization
I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets? DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent ) : QGraphicsScene( screenRect, parent ), myParent( parent ), slideUndoImageCurrentIndex(-1), nextGroupID(0), m_undoInProgress(false), m_deleteItemOnNextUndo(0) line(0), path(0) { /* Setup default brush for background */ scDetail->bgBrush.setStyle(Qt::SolidPattern); scDetail->bgBrush.setColor(Qt::white); setBackgroundBrush(scDetail->bgBrush); }
It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors. You can't accidentally assign a value twice in the initialiser list. The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars). Reference types and const members must be initialised in the initialiser list, because you can't assign to a reference or to a const member.
161,790
162,372
initialize a const array in a class initializer in C++
I have the following class in C++: class a { const int b[2]; // other stuff follows // and here's the constructor a(void); } The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const? This doesn't work: a::a(void) : b([2,3]) { // other initialization stuff } Edit: The case in point is when I can have different values for b for different instances, but the values are known to be constant for the lifetime of the instance.
Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead. int* a = new int[N]; // fill a class C { const std::vector<int> v; public: C():v(a, a+N) {} };
162,309
2,801,958
How to launch a Windows process as 64-bit from 32-bit code?
To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick: ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE); This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to registry reflection. So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "*" suffix in the Task Manager)?
try this (from a 32bit process): > %WINDIR%\sysnative\reg.exe query ... (found that here).
162,480
162,504
'const int' vs. 'int const' as function parameters in C++ and C
Consider: int testfunc1 (const int a) { return a; } int testfunc2 (int const a) { return a; } Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.
const T and T const are identical. With pointer types it becomes more complicated: const char* is a pointer to a constant char char const* is a pointer to a constant char char* const is a constant pointer to a (mutable) char In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee) const is to use a suffix-const. This is why many people prefer to always put const to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners).
163,058
551,215
How can I detect if I'm compiling for a 64bits architecture in C++
In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture. I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?
Why are you choosing one block over the other? If your decision is based on the size of a pointer, use sizeof(void*) == 8. If your decision is based on the size of an integer, use sizeof(int) == 8. My point is that the name of the architecture itself should rarely make any difference. You check only what you need to check, for the purposes of what you are going to do. Your question does not cover very clearly what your purpose of the check is. What you are asking is akin to trying to determine if DirectX is installed by querying the version of Windows. You have more portable and generic tools at your disposal.
163,365
163,417
How do I make a C++ macro behave like a function?
Let's say that for some reason you need to write a macro: MACRO(X,Y). (Let's assume there's a good reason you can't use an inline function.) You want this macro to emulate a call to a function with no return value. Example 1: This should work as expected. if (x > y) MACRO(x, y); do_something(); Example 2: This should not result in a compiler error. if (x > y) MACRO(x, y); else MACRO(y - x, x - y); Example 3: This should not compile. do_something(); MACRO(x, y) do_something(); The naïve way to write the macro is like this: #define MACRO(X,Y) \ cout << "1st arg is:" << (X) << endl; \ cout << "2nd arg is:" << (Y) << endl; \ cout << "Sum is:" << ((X)+(Y)) << endl; This is a very bad solution which fails all three examples, and I shouldn't need to explain why. Ignore what the macro actually does, that's not the point. Now, the way I most often see macros written is to enclose them in curly braces, like this: #define MACRO(X,Y) \ { \ cout << "1st arg is:" << (X) << endl; \ cout << "2nd arg is:" << (Y) << endl; \ cout << "Sum is:" << ((X)+(Y)) << endl; \ } This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon. Is there a way to write a macro so that it pass all three examples? Note: I am submitting my own answer as part of the accepted way of sharing a tip, but if anyone has a better solution feel free to post it here, it may get more votes than my method. :)
Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once. If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator: #define MACRO(X,Y) \ ( \ (cout << "1st arg is:" << (X) << endl), \ (cout << "2nd arg is:" << (Y) << endl), \ (cout << "3rd arg is:" << ((X) + (Y)) << endl), \ (void)0 \ ) The (void)0 causes the statement to evaluate to one of void type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that MACRO(a++, b++) will increment a and b twice.
163,432
163,466
Garbage with pointers in a class, C++
I am using Borland Builder C++. I have a memory leak and I know it must be because of this class I created, but I am not sure how to fix it. Please look at my code-- any ideas would be greatly appreciated! Here's the .h file: #ifndef HeaderH #define HeaderH #include <vcl.h> #include <string> using std::string; class Header { public: //File Header char FileTitle[31]; char OriginatorName[16]; //Image Header char ImageDateTime[15]; char ImageCordsRep[2]; char ImageGeoLocation[61]; NitfHeader(double latitude, double longitude, double altitude, double heading); ~NitfHeader(); void SetHeader(char * date, char * time, double location[4][2]); private: void ConvertToDegMinSec (double angle, AnsiString & s, bool IsLongitude); AnsiString ImageDate; AnsiString ImageTime; AnsiString Latitude_d; AnsiString Longitude_d; double Latitude; double Longitude; double Heading; double Altitude; }; And here is some of the .cpp file: void Header::SetHeader(char * date, char * time, double location[4][2]){ //File Header strcpy(FileTitle,"Cannon Powershot A640"); strcpy(OperatorName,"Camera Operator"); //Image Header //Image Date and Time ImageDate = AnsiString(date); ImageTime = AnsiString(time); AnsiString secstr = AnsiString(ImageTime.SubString(7,2)); AnsiString rounder = AnsiString(ImageDate.SubString(10,1)); int seconds = secstr.ToInt(); //Round off seconds - will this be necessary with format hh:mm:ss in text file? if (rounder.ToInt() > 4) { seconds++; } AnsiString dateTime = ImageDate.SubString(7,4)+ ImageDate.SubString(4,2) + ImageDate.SubString(1,2) + ImageTime.SubString(1,2) + ImageTime.SubString(4,2) + AnsiString(seconds); strcpy(ImageDateTime,dateTime.c_str()); //Image Coordinates Representation strcpy(ImageCordsRep,"G"); //Image Geographic Location AnsiString lat; AnsiString lon; AnsiString locationlat_d; AnsiString locationlon_d; AnsiString corner; for (int i = 0; i < 4; i++){ ConvertToDegMinSec(location[i][0],lat,false); ConvertToDegMinSec(location[i][1],lon,true); if(location[i][0] < 0){ locationlat_d = 'S'; ConvertToDegMinSec(-location[i][0],lat,false); }else if(location[i][0] > 0){ locationlat_d = 'N'; }else locationlat_d = ' '; if(location[i][1] < 0){ locationlon_d = 'W'; ConvertToDegMinSec(-location[i][1],lon,true); }else if(location[i][1] > 0){ locationlon_d = 'E'; }else locationlon_d = ' '; corner += lat + locationlat_d + lon + locationlon_d; } strcpy(ImageGeoLocation,corner.c_str()); } Now when I use the class in main, basically I just create a pointer: Header * header = new Header; header->SetHeader(t[5],t[6],corners->location); char * imageLocation = header->ImageGeoLocation; //do something with imageLocation delete header; Where corners->location is a string from another class, and t[5] and t[6] are both strings. The problem is that imageLocation doesn't contain what is expected, and often just garbage. I have read a lot about memory leaks and pointers, but I am still very new to programming and some of it is quite confusing. Any suggestions would be fabulous!!
I'm afraid there are a number of issues here. For starters char ImageCordsRep[1]; doesn't work ... a string is always null terminated, so when you do strcpy(ImageCordsRep,"G"); you are overflowing the buffer. It would also be good practice to terminate all those string buffers with a null in your constructor, so they are always valid strings. Even better would be to use a string class instead of the char arrays, or at least use 'strncpy' to prevent buffer overruns if the incoming strings are larger than you expect.
163,487
163,963
Generate a WSDL without a webserver
I would like to generate a WSDL file from a c++ atl webservice without using a web server. I would like to generate it as part of the visual studio build or as a post build event. I found a program (CmdHelper) that does this for .NET assemblies but it doesn't seem to work for what I need. Any ideas?
The Microsoft SOAP Toolkit comes with a WSDL generator, which will generate a WSDL file from a COM component. We use that where I work, and it seems to do the job. We haven't tried to integrate it into our build process - we've always run the tool by hand when we need to update the WSDL, and we check the generated WSDL into version control. I see that Microsoft has deprecated this product, so there may be newer alternatives out there, but it works fine for us.
163,962
163,985
Switching from std::string to std::wstring for embedded applications?
Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.). For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line interface (CLI). What complications / headaches / surprises should I expect? What, for example, if I use a third-party library which still uses std::string? Since support for international strings isn't that strong of a requirement for the type of embedded systems that I work on, I would only do it if it isn't going to cause major headaches.
Note that many communications protocols require 8-bit characters (or 7-bit characters, or other varieties), so you will often need to translate between your internal wchar_t/wstring data and external encodings. UTF-8 encoding is useful when you need to have an 8-bit representation of Unicode characters. (See How Do You Write Code That Is Safe for UTF-8? for some more info.) But note that you may need to support other encodings. More and more third-party libraries are supporting Unicode, but there are still plenty that don't. I can't really tell you whether it is worth the headaches. It depends on what your requirements are. If you are starting from scratch, then it will be easier to start with std::wstring than converting from std::string to std::wstring later.
164,002
164,012
Why is fread reaching the EOF early?
I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file. The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached. C is not my native language so I suspect I've got a dumb beginner mistake somewhere. Code is as follows: const size_t headerLen = 54; FILE * stream; errno_t ferrno = fopen_s( &stream, filename.c_str(), "r" ); if(ferrno!=0) { return -1; } fseek( stream, 0L, SEEK_END ); size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to read size_t bytesRead = 0; BYTE* localBuffer = new BYTE[bytesTotal]; fseek(stream,headerLen,SEEK_SET); while(!feof(stream) && !ferror(stream)) { size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream); bytesRead+=result; } Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-) This reference talks about it in the second paragraph, second sentence (though not in their table). MSDN doesn't discuss the binary flag until halfway down the page. OpenGroup mentions the existance of the "b" tag, but states that it "shall have no effect".
perhaps it's a binary mode issue. Try opening the file with "r+b" as the mode. EDIT: as noted in a comment "rb" is likely a better match to your original intent since "r+b" will open it for read/write and "rb" is read-only.
164,022
164,092
Reading some integers then a line of text in C++
I'm reading input in a C++ program. First some integers, then a string. When I try reading the string with getline(cin,stringname);, it doesn't read the line that the user types: instead, I get an empty line, from when the user pressed Enter after typing the integers. cin>>track.day; //Int cin>>track.seriesday; //Int getline(cin,track.comment); //String How can I clear the cin (cin.clear() doesn't work) so that the string won't fill itself with the "enter" key? It's a normal input receiving, nothing special at the top of the code, I had a problem like this but I forgot the solution I need to clear the cin someway so the string won't get filled with "enter" key.
I think that your cin of the ints is not reading the new line before the sentence. cin skips leading whitespace and stops reading a number when it encounters a non-digit, including whitespace. So: std::cin >> num1; std::cin >> num2; std::cin.ignore(INT_MAX, '\n'); // ignore the new line which follows num2 std::getline(std::cin, sentence); might work for you
164,026
164,035
On Win32 how do you move a thread to another CPU core?
I'd like to make sure that a thread is moved to a specific CPU core and can never be moved from it by the scheduler. There's a SetThreadAffinityMask() call but there's no GetThreadAffinityMask(). The reason I need this is because high resolution timers will get messed up if the scheduler moves that thread to another CPU.
You should probably just use SetThreadAffinityMask and trust that it is working. MSDN
164,039
190,709
Docking a CControlBar derived window
How can I dock a CControlBar derived window to the middle of a splitter window (CSplitterWnd)? I would like the bar to be repositioned whenever the splitter is moved. To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.
Alf, In case of VS, there's no splitter used: The resource view is a resizable ControlBar (It looks and feels like a splitter but it isn't a CSplitterWnd). The rest is a child frame (either tabbed or MDI. Go to Tools/Options/Environment/General and choose Multiple Documents to convince yourself). The ruler is part (controlbar?) of the child frame. In your case, I think you don't want a 3 panes splitter. You need a 2 pane splitter and the control bar should be part of your view (it wouldn't be a CControlBar per se). Unless you use MDI in which case you can make it a true ControlBar in your child frame. HTH
164,102
164,130
In c++, why does the compiler choose the non-const function when the const would work also?
For example, suppose I have a class: class Foo { public: std::string& Name() { m_maybe_modified = true; return m_name; } const std::string& Name() const { return m_name; } protected: std::string m_name; bool m_maybe_modified; }; And somewhere else in the code, I have something like this: Foo *a; // Do stuff... std::string name = a->Name(); // <-- chooses the non-const version Does anyone know why the compiler would choose the non-const version in this case? This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.
Two answers spring to mind: The non-const version is a closer match. If it called the const overload for the non-const case, then under what circumstances would it ever call the non-const overload? You can get it to use the other overload by casting a to a const Foo *. Edit: From C++ Annotations Earlier, in section 2.5.11 the concept of function overloading was introduced. There it noted that member functions may be overloaded merely by their const attribute. In those cases, the compiler will use the member function matching most closely the const-qualification of the object:
164,168
164,274
How do you construct a std::string with an embedded null?
If I want to construct a std::string with a line like: std::string my_string("a\0b"); Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?
Since C++14 we have been able to create literal std::string #include <iostream> #include <string> int main() { using namespace std::string_literals; std::string s = "pl-\0-op"s; // <- Notice the "s" at the end // This is a std::string literal not // a C-String literal. std::cout << s << "\n"; } Before C++14 The problem is the std::string constructor that takes a const char* assumes the input is a C-string. C-strings are \0 terminated and thus parsing stops when it reaches the \0 character. To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length: std::string x("pq\0rs"); // Two characters because input assumed to be C-String std::string x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters. Note: C++ std::string is NOT \0-terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method c_str(). Also check out Doug T's answer below about using a vector<char>. Also check out RiaD for a C++14 solution.
164,284
167,269
How do I transfer a file using wininet that is readable by a php script?
I would like to transfer a text file to a webserver using wininet as if the file was being transferred using a web form that posts the file to the server. Based on answers I've received I've tried the following code: static TCHAR hdrs[] = "Content-Type: multipart/form-data\nContent-Length: 25"; static TCHAR frmdata[] = "file=filename.txt\ncontent"; HINTERNET hSession = InternetOpen("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); HINTERNET hConnect = InternetConnect(hSession, "example.com", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1); HINTERNET hRequest = HttpOpenRequest(hConnect, "POST", "test.php", NULL, NULL, NULL, 0, 1); HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));"); The test.php script is being run, but it doesn't appear to be getting the correct data. Could anyone give me any additional help or somewhere to look? Thanks.
Changing the form data and headers that I had above to the following solved the problem: static TCHAR frmdata[] = "-----------------------------7d82751e2bc0858\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"file.txt\"\nContent-Type: text/plain\n\nfile contents here\n-----------------------------7d82751e2bc0858--"; static TCHAR hdrs[] = "Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858";
164,305
168,157
C++ types using CodeSynthesis XSD Tree Mapping
I'm using CodeSynthesis XSD C++/Tree Mapping utility to convert an existing xsd into c++ code we can populate the values in. This was we always make sure we follow the schema. After doing the conversion, I'm trying to get it to work so I can test it. Problem is, I'm not used to doing this in c++ and it's my first time with this tool. I start with a class called ABSTRACTNETWORKMODEL with types versno_type and fromtime_type typedef'd inside. Here is the constructor I am trying to use as well as the typedefs ABSTRACTNETWORKMODEL(const versno_type&, const fromtime_type&); typedef ::xml_schema::double_ versno_type; typedef ::xml_schema::time fromtime_type; all these are in the ABSTRACTNETWORKMODEL class and the definitions for double_ and time are: typedef ::xsd::cxx::tree::time<char, simple_type> time; typedef double double_; where the definition for time is a class with multiple constructors: template<typename C, typename B> class time: public B, public time_zone { public: time(unsigned short hours, unsigned short minutes, double seconds); ... } I know I'm not correctly creating a new ABSTRACTNETWORKMODEL but I don't know what I need to do this. Here is all I'm trying to do at this point: ::xml_schema::time t(); ABSTRACTNETWORKMODEL anm(1234, t); This, of course, throws an error about converting the second parameter, but can somebody tell me what it is that is incorrect? Or at least point me down the right path, as one of the things I'm trying to do right now is learn more c++.
I've been bitten by this before. If the line: ::xml_schema::time t(); is exactly as it appears in your code (that is, with the parens) then the problem is that you didn't actually instantiate an object like you think. To instantiate an object you would use ::xml_schema::time t; The first line, instead, declares a function t() that takes no arguments and returns an object of type ::xml_schema::time. Since there is no body, the compiler thinks you will define the function later. It is perfectly legal C++, and it's something that people do a lot (say, in header files) so the compiler accepts it, does not issue a warning because it has no way of knowing that's not what you meant, and does something you weren't expecting. And when you pass that function to the ABSTRACTNETWORKMODEL constructor you get an error because you can't pass a function as an argument (you can pass a pointer to the function, and you can call the function, passing the resulting temporary): ::xml_schema::time t(); ABSTRACTNETWORKMODEL anm(1234, t()); // calls t(), gets a temporary of type ::xml_schema::time, and passes the temporary to the constructor So the reason "the instantiation of time didn't cause an error" is that a time object was never instantiated. The time class doesn't have a default constructor either, and attempting to instantiate t with the correct syntax would have thrown the error you were expecting. For the record, the parenthesis are required in some cases. For instance, when instantiating a temporary object and manipulating that temporary in the same line: int hours = time().get_hours(); // assuming that there is now a default constructor Because dropping the first set of parenthesis will result in an error: int hours = time.set_time("12:00:00am"); // error: there is a time class, but no object named "time" Believe me, I really like C++, but the syntax can get really difficult to keep straight some times.
164,356
1,281,627
Can I use the STL if I cannot afford the slow performance when exceptions are thrown?
For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown?
It's not clearly written in the previous answers, so: Exceptions happen in C++ Using the STL or not won't remove the RAII code that will free the objects's resources you allocated. For example: void doSomething() { MyString str ; doSomethingElse() ; } In the code above, the compiler will generate the code to free the MyString resources (i.e. will call the MyString destructor), no matter what happens in the meantime including if if an exception is thrown by doSomethingElse or if you do a "return" before the end of the function scope. If you have a problem with that, then either you should revise your mindset, or try C. Exceptions are supposed to be exceptional Usually, when an exception occurs (and only when), you'll have a performance hit. But then, the exception should only sent when: You have an exceptional event to handle (i.e. some kind of error) In very exceptional cases (i.e. a "massive return" from multiple function call in the stack, like when doing a complicated search, or unwinding the stack prior a thread graceful interruption) The keyword here is "exceptional", which is good because we are discussing "exception" (see the pattern?). In your case, if you have an exception thrown, chances are good something so bad happened your program would have crashed anyway without exception. In this case, your problem is not dealing with the performance hit. It is to deal with a graceful handling of the error, or, at worse, graceful termination of your program (including a "Sorry" messagebox, saving unsaved data into a temporary file for later recovery, etc.). This means (unless in very exceptional cases), don't use exceptions as "return data". Throw exceptions when something very bad happens. Catch an exception only if you know what to do with that. Avoid try/catching (unless you know how to handle the exception). What about the STL ? Now that we know that: You still want to use C++ Your aim is not to throw thousand exceptions each and every seconds just for the fun of it We should discuss STL: STL will (if possible) usually verify if you're doing something wrong with it. And if you do, it will throw an exception. Still, in C++, you usually won't pay for something you won't use. An example of that is the access to a vector data. If you know you won't go out of bounds, then you should use the operator []. If you know you won't verify the bounds, then you should use the method at(). Example A: typedef std::vector<std::string> Vector ; void outputAllData(const Vector & aString) { for(Vector::size_type i = 0, iMax = aString.size() ; i != iMax ; ++i) { std::cout << i << " : " << aString[i] << std::endl ; } } Example B: typedef std::vector<std::string> Vector ; void outputSomeData(const Vector & aString, Vector::size_type iIndex) { std::cout << iIndex << " : " << aString.at(iIndex) << std::endl ; } The example A "trust" the programmer, and no time will be lost in verification (and thus, less chance of an exception thrown at that time if there is an error anyway... Which usually means the error/exception/crash will usually happen after, which won't help debugging and will let more data be corrupted). The example B asks the vector to verify the index is correct, and throw an exception if not. The choice is yours.
164,372
164,399
Structured exception handling with a multi-threaded server
This article gives a good overview on why structured exception handling is bad. Is there a way to get the robustness of stopping your server from crashing, while getting past the problems mentioned in the article? I have a server software that runs about 400 connected users concurrently. But if there is a crash all 400 users are affected. We added structured exception handling and enjoyed the results for a while, but eventually had to remove it because of some crashes causing the whole server to hang (which is worse than just having it crash and restart itself). So we have this: With SEH: only 1 user of the 400 get a problem for most crashes Without SEH: If any user gets a crash, all 400 are affected. But sometimes with SEH: Server hangs, all 400 are affected and future users that try to connect.
Break your program up into worker processes and a single server process. The server process will handle initial requests and then hand them off the the worker processes. If a worker process crashes, only the users on that worker are affected. Don't use SEH for general exception handling - as you have found out, it can and will leave you wide open to deadlocks, and you can still crash anyway.
164,496
164,640
How can I create a thread-safe singleton pattern in Windows?
I've been reading about thread-safe singleton patterns here: http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29 And it says at the bottom that the only safe way is to use pthread_once - which isn't available on Windows. Is that the only way of guaranteeing thread safe initialisation? I've read this thread on SO: Thread safe lazy construction of a singleton in C++ And seems to hint at an atomic OS level swap and compare function, which I assume on Windows is: http://msdn.microsoft.com/en-us/library/ms683568.aspx Can this do what I want? Edit: I would like lazy initialisation and for there to only ever be one instance of the class. Someone on another site mentioned using a global inside a namespace (and he described a singleton as an anti-pattern) - how can it be an "anti-pattern"? Accepted Answer: I've accepted Josh's answer as I'm using Visual Studio 2008 - NB: For future readers, if you aren't using this compiler (or 2005) - Don't use the accepted answer!! Edit: The code works fine except the return statement - I get an error: error C2440: 'return' : cannot convert from 'volatile Singleton *' to 'Singleton *'. Should I modify the return value to be volatile Singleton *? Edit: Apparently const_cast<> will remove the volatile qualifier. Thanks again to Josh.
If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since "volatile variables behave as fences". This is the most efficient way to implement a lazy-initialized singleton. From MSDN Magazine: Singleton* GetSingleton() { volatile static Singleton* pSingleton = 0; if (pSingleton == NULL) { EnterCriticalSection(&cs); if (pSingleton == NULL) { try { pSingleton = new Singleton(); } catch (...) { // Something went wrong. } } LeaveCriticalSection(&cs); } return const_cast<Singleton*>(pSingleton); } Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer. DO NOT use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible. You'll have to declare and initialize the CRITICAL SECTION elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important.
165,101
165,153
"invalid use of incomplete type" error with partial template specialization
The following code: template <typename S, typename T> struct foo { void bar(); }; template <typename T> void foo <int, T>::bar() { } gives me the error invalid use of incomplete type 'struct foo<int, T>' declaration of 'struct foo<int, T>' (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument: template <typename S> struct foo { void bar(); }; template <> void foo <int>::bar() { } then it compiles correctly.
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. template <typename U = T> struct Nested) would work. Or else you can try deriving from another template that partially specializes (works if you use the this->member notation, otherwise you will encounter compiler errors).
165,188
165,203
printf + uint_64 on Solaris 9?
I have some c(++) code that uses sprintf to convert a uint_64 to a string. This needs to be portable to both linux and Solaris. On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code: #include <stdio.h> #include <sys/types.h> #ifdef SunOS typedef uint64_t u_int64_t; #endif int main(int argc, char **argv) { u_int64_t val = 123456789123L; #ifdef SunOS printf("%lu\n", val); #else printf("%ju\n", val); #endif } On linux, the output is as expected; on Solaris 9 (don't ask), it's "28" What can I use?
If you have have inttypes.h available you can use the macros it provides: printf( "%" PRIu64 "\n", val); Not pretty (I seem to be saying that a lot recently), but it works.
165,386
165,391
Improve compiling speed in VS project using C++ Boost Libraries
I have just started using Boost 1.36. These libraries would be very useful in reducing the amount of code needed in the unmanaged C++ software project that I am working on. However when I tried to used these libraries my compile times increased ten fold. This would pretty much offset the productivity gains I would receive by using the library. I am using a 3GHz Intel Dual Core with 2GB of RAM and VS 2003. There is a snippet of the code that I added. #include "boost/numeric/ublas/matrix.hpp" #include "boost/numeric/ublas/vector.hpp" #include "boost/numeric/ublas/matrix_proxy.hpp" typedef ublas::bounded_matrix <long double,NUM_OF_COLUMNS,NUM_OF_CATEGORIES,ublas::row_major> Matrix; typedef ublas::bounded_vector <long double,NUM_OF_COLUMNS> Vector; void Print(const Matrix& amount) { Vector total; total.clear(); for (int category = 0; category < NUM_OF_CATEGORIES; category++) { PrintLine(ublas::row(amount, category)); total += ublas::row(amount, category); } PrintLine(total); } Is the problem with VS 2003? I know that VS 2008 is faster but upgrading is going to be a hard sell. Is it just that Boost is optimized for fast run times not fast compile times? Am I just using the Boost Library in a sub-optimal manner? Or am I just using the wrong tool for the job?
Have you tried using precompiled headers? That is including the boost headers in StdAfx.h or whatever header file you use for precompiled headers?
165,551
167,045
How to tell if text on the windows clipboard is ISO 8859 or UTF-8 in C++?
I would like to know if there is an easy way to detect if the text on the clipboard is in ISO 8859 or UTF-8 ? Here is my current code: COleDataObject obj; if (obj.AttachClipboard()) { if (obj.IsDataAvailable(CF_TEXT)) { HGLOBAL hmem = obj.GetGlobalData(CF_TEXT); CMemFile sf((BYTE*) ::GlobalLock(hmem),(UINT) ::GlobalSize(hmem)); CString buffer; LPSTR str = buffer.GetBufferSetLength((int)::GlobalSize(hmem)); sf.Read(str,(UINT) ::GlobalSize(hmem)); ::GlobalUnlock(hmem); //this is my string class s->SetEncoding(ENCODING_8BIT); s->SetString(buffer); } } }
Check out the definition of CF_LOCALE at this Microsoft page. It tells you the locale of the text in the clipboard. Better yet, if you use CF_UNICODETEXT instead, Windows will convert to UTF-16 for you.
165,637
165,737
How do I create a custom slot in qt4 designer?
Whenever I use the signal/slot editor dialog box, I have to choose from the existing list of slots. So the question is how do I create a custom named slot?
Unfortunately this is not possible in Qt4. In Qt3 you could create custom slots which where then implemented in the ui.h file. However, Qt4 does not use this file so custom slots are not supported. There is some discussion of this issue over on QtForum
165,699
165,853
how do I specify the source code directory in VS when looking at the call stack of a memory dump?
I am analyzing a .dmp file that was created and I have a call stack which gives me a lot of info. But I'd like to double click on the call stack and have it bring me to the source code. I can right click on the call stack and select symbol settings.. where I can put the location to the PDB. But there is no option for the source code directory.
The source code directory is unfortunately hard coded into the pdb's however if you know the folders required you can use windows concept of symbolic links, junctions. I use the tool Junction Link Magic
165,723
165,743
Do programmers of other languages, besides C++, use, know or understand RAII?
I've noticed RAII has been getting lots of attention on Stackoverflow, but in my circles (mostly C++) RAII is so obvious its like asking what's a class or a destructor. So I'm really curious if that's because I'm surrounded daily, by hard-core C++ programmers, and RAII just isn't that well known in general (including C++), or if all this questioning on Stackoverflow is due to the fact that I'm now in contact with programmers that didn't grow up with C++, and in other languages people just don't use/know about RAII?
For people who are commenting in this thread about RAII (resource acquisition is initialisation), here's a motivational example. class StdioFile { FILE* file_; std::string mode_; static FILE* fcheck(FILE* stream) { if (!stream) throw std::runtime_error("Cannot open file"); return stream; } FILE* fdup() const { int dupfd(dup(fileno(file_))); if (dupfd == -1) throw std::runtime_error("Cannot dup file descriptor"); return fdopen(dupfd, mode_.c_str()); } public: StdioFile(char const* name, char const* mode) : file_(fcheck(fopen(name, mode))), mode_(mode) { } StdioFile(StdioFile const& rhs) : file_(fcheck(rhs.fdup())), mode_(rhs.mode_) { } ~StdioFile() { fclose(file_); } StdioFile& operator=(StdioFile const& rhs) { FILE* dupstr = fcheck(rhs.fdup()); if (fclose(file_) == EOF) { fclose(dupstr); // XXX ignore failed close throw std::runtime_error("Cannot close stream"); } file_ = dupstr; return *this; } int read(std::vector<char>& buffer) { int result(fread(&buffer[0], 1, buffer.size(), file_)); if (ferror(file_)) throw std::runtime_error(strerror(errno)); return result; } int write(std::vector<char> const& buffer) { int result(fwrite(&buffer[0], 1, buffer.size(), file_)); if (ferror(file_)) throw std::runtime_error(strerror(errno)); return result; } }; int main(int argc, char** argv) { StdioFile file(argv[1], "r"); std::vector<char> buffer(1024); while (int hasRead = file.read(buffer)) { // process hasRead bytes, then shift them off the buffer } } Here, when a StdioFile instance is created, the resource (a file stream, in this case) is acquired; when it's destroyed, the resource is released. There is no try or finally block required; if the reading causes an exception, fclose is called automatically, because it's in the destructor. The destructor is guaranteed to be called when the function leaves main, whether normally or by exception. In this case, the file stream is cleaned up. The world is safe once again. :-D
165,984
166,651
Moving between dialog controls in Windows Mobile without the tab key
I have a windows mobile 5.0 app, written in C++ MFC, with lots of dialogs. One of the devices I'm currently targetting does not have a tab key, so I would like to use another key to move between controls. This is fine for buttons but not edit controls or combo boxes. I have looked at a similar question but the answer does not really suit. I've tried overriding the CDialog::OnKeyDown to no avail, and would rather not have to override the keystroke functionality for every control in every dialog. My thoughts so far are to write new classes replacing CEdit and CComboBox, but as always am just checking if there is an easier way, such as temporarily re-programming another key.
I don't know MFC that good, but maybe you could pull it off by subclassing window procedures of all those controls with a single class, which would only handle cases of pressing cursor keys and pass the rest of events to the original procedures. You would have to provide your own mechanism of moving to an appropriate control, depending on which cursor key was pressed but it may be worth the usability gains. If that worked, you could enumerate all dialog controls and subclass them automatically. Windows Mobile 6 allows switching between dialog controls using cursors by default - it's a new, more "smartphoney" way of moving around the UI and it's incredibly convenient.
166,033
166,039
What do ‘value semantics’ and ‘pointer semantics’ mean?
What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?
Java is using implicit pointer semantics for Object types and value semantics for primitives. Value semantics means that you deal directly with values and that you pass copies around. The point here is that when you have a value, you can trust it won't change behind your back. With pointer semantics, you don't have a value, you have an 'address'. Someone else could alter what is there, you can't know. Pointer Semantics in C++ : void foo(Bar * b) ... ... b->bar() ... You need an * to ask for pointer semantics and -> to call methods on the pointee. Implicit Pointer Semantics in Java : void foo(Bar b) ... ... b.bar() ... Since you don't have the choice of using value semantics, the * isn't needed nor the distinction between -> and ., hence the implicit.
166,083
166,087
#define TRACE(...) doesn't work in C++
I have the following preprocessor divective: #ifndef NDEBUG #define TRACE printf #else #define TRACE(...) #endif and example of usage is: TRACE("TRACE: some parameter = %i\n", param); In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following: warning: invalid character in macro parameter name error: badly punctuated parameter list in `#define' and points these warning and error to the 'TRACE(...)' directive. How to write this in C++ correctly?
You could do: inline void TRACE(...) {}
166,113
166,118
Function returning the return of another function
If I want to call Bar() instead of Foo(), does Bar() return me a copy (additional overhead) of what Foo() returns, or it returns the same object which Foo() places on the temporary stack? vector<int> Foo(){ vector<int> result; result.push_back(1); return result; } vector<int> Bar(){ return Foo(); }
Both may happen. However, most compiler will not do copy as soon as you optimize. Your code indicate there should be a copy. However, the compiler is allowed to remove any copy that do not change the semantic and the program. Note: This is why you should NEVER have a copy constructor that does anything but copying correctly as you can never be sure if a copy will be actually done or not.
166,125
166,225
C++: Multithreading and refcounted object
I'm currently trying to pass a mono threaded program to multithread. This software do heavy usage of "refCounted" objects, which lead to some issues in multithread. I'm looking for some design pattern or something that might solve my problem. The main problem is object deletion between thread, normally deletion only decrement the reference counting, and when refcount is equal to zero, then the object is deleted. This work well in monothread program, and allow some great performance improvement with copy of big object. However, in multithread, two threads might want to delete the same object concurrently, as the object is protected by a mutex, only one thread delete the object and block the other one. But when it releases the mutex, then the other thread continue its execution with invalid (freed object), which lead to memory corruption. Here is an example with this class RefCountedObject class RefCountedObject { public: RefCountedObject() : _refCount( new U32(1) ) {} RefCountedObject( const RefCountedObject& obj ) : _refCount( obj._refCount ) { ACE_Guard< ACE_Mutex > guard( _refCountMutex ); ++(*_refCount); } ~RefCountedObject() { Destroy(); } RefCountedObject& operator=( const RefCountedObject& obj ) { if( this != &obj ) { Destroy(); ACE_Guard< ACE_Mutex > guard( _refCountMutex ); _refCount = obj._refCount; ++(*_refCount); } return *this; } private: void Destroy() { ACE_Guard< ACE_Mutex > guard( _refCountMutex ); // thread2 are waiting here --(*_refCount); // This cause a free memory write by the thread2 if( 0 == *_refCount ) delete _refCount; } private: mutable U32* _refCount; mutable ACE_Mutex _refCountMutex; // BAD: this mutex only protect the refCount pointer, not the refCount itself }; Suppose that two threads want to delete the same RefCountedObject, both are in ~RefCountedObject and call Destroy(), the first thread has locked the mutex and the other one is waiting. After the deletion of the object by the first thread, the second will continue its execution and cause a free memory write. Anyone has experience with a similar problem and found a solution ? Thanks all for your help, I realize my mistake: The mutex is only protecting refCount pointer, not the refCount itself! I've created a RefCount class which is mutex protected. The mutex is now shared between all refCounted object. Now all works fine.
If the count is part of the object then you have an inherent problem if one thread can be trying to increase the reference count whilst another is trying to remove the last reference. There needs to be an extra value on the ref count for each globally accessible pointer to the object, so you can always safely increase the ref count if you've got a pointer. One option would be to use boost::shared_ptr (see the docs). You can use the free functions atomic_load, atomic_store, atomic_exchange and atomic_compare_exchange (which are conspicuously absent from the docs) to ensure suitable protection when accessing global pointers to shared objects. Once your thread has got a shared_ptr referring to a particular object you can use the normal non-atomic functions to access it. Another option is to use Joe Seigh's atomic ref-counted pointer from his atomic_ptr_plus project
166,356
166,572
What are some best practices for OpenGL coding (esp. w.r.t. object orientation)?
This semester, I took a course in computer graphics at my University. At the moment, we're starting to get into some of the more advanced stuff like heightmaps, averaging normals, tesselation etc. I come from an object-oriented background, so I'm trying to put everything we do into reusable classes. I've had good success creating a camera class, since it depends mostly on the one call to gluLookAt(), which is pretty much independent of the rest of the OpenGL state machine. However, I'm having some trouble with other aspects. Using objects to represent primitives hasn't really been a success for me. This is because the actual render calls depend on so many external things, like the currently bound texture etc. If you suddenly want to change from a surface normal to a vertex normal for a particular class it causes a severe headache. I'm starting to wonder whether OO principles are applicable in OpenGL coding. At the very least, I think that I should make my classes less granular. What is the stack overflow community's views on this? What are your best practices for OpenGL coding?
The most practical approach seems to be to ignore most of OpenGL functionality that is not directly applicable (or is slow, or not hardware accelerated, or is a no longer a good match for the hardware). OOP or not, to render some scene those are various types and entities that you usually have: Geometry (meshes). Most often this is an array of vertices and array of indices (i.e. three indices per triangle, aka "triangle list"). A vertex can be in some arbitrary format (e.g. only a float3 position; a float3 position + float3 normal; a float3 position + float3 normal + float2 texcoord; and so on and so on). So to define a piece of geometry you need: define it's vertex format (could be a bitmask, an enum from a list of formats; ...), have array of vertices, with their components interleaved ("interleaved arrays") have array of triangles. If you're in OOP land, you could call this class a Mesh. Materials - things that define how some piece of geometry is rendered. In a simplest case, this could be a color of the object, for example. Or whether lighting should be applied. Or whether the object should be alpha-blended. Or a texture (or a list of textures) to use. Or a vertex/fragment shader to use. And so on, the possibilities are endless. Start by putting things that you need into materials. In OOP land that class could be called (surprise!) a Material. Scene - you have pieces of geometry, a collection of materials, time to define what is in the scene. In a simple case, each object in the scene could be defined by: - What geometry it uses (pointer to Mesh), - How it should be rendered (pointer to Material), - Where it is located. This could be a 4x4 transformation matrix, or a 4x3 transformation matrix, or a vector (position), quaternion (orientation) and another vector (scale). Let's call this a Node in OOP land. Camera. Well, a camera is nothing more than "where it is placed" (again, a 4x4 or 4x3 matrix, or a position and orientation), plus some projection parameters (field of view, aspect ratio, ...). So basically that's it! You have a scene which is a bunch of Nodes which reference Meshes and Materials, and you have a Camera that defines where a viewer is. Now, where to put actual OpenGL calls is a design question only. I'd say, don't put OpenGL calls into Node or Mesh or Material classes. Instead, make something like OpenGLRenderer that can traverse the scene and issue all calls. Or, even better, make something that traverses the scene independent of OpenGL, and put lower level calls into OpenGL dependent class. So yes, all of the above is pretty much platform independent. Going this way, you'll find that glRotate, glTranslate, gluLookAt and friends are quite useless. You have all the matrices already, just pass them to OpenGL. This is how most of real actual code in real games/applications work anyway. Of course the above can be complicated by more complex requirements. Particularly, Materials can be quite complex. Meshes usually need to support lots of different vertex formats (e.g. packed normals for efficiency). Scene Nodes might need to be organized in a hierarchy (this one can be easy - just add parent/children pointers to the node). Skinned meshes and animations in general add complexity. And so on. But the main idea is simple: there is Geometry, there are Materials, there are objects in the scene. Then some small piece of code is able to render them. In OpenGL case, setting up meshes would most likely create/activate/modify VBO objects. Before any node is rendered, matrices would need to be set. And setting up Material would touch most of remaining OpenGL state (blending, texturing, lighting, combiners, shaders, ...).
166,474
177,923
msbuild: set a specific preprocessor #define in the command line
In a C++ file, I have a code like this: #if ACTIVATE # pragma message( "Activated" ) #else # pragma message( "Not Activated") #endif I want to set this ACTIVE define to 1 with the msbuild command line. It tried this but it doesn't work: msbuild /p:DefineConstants="ACTIVATE=1" Any idea?
The answer is : YOU CANNOT
166,542
166,581
Using boost in embedded system with memory limitation
We are using c++ to develop an application that runs in Windows CE 4 on an embedded system. One of our constraint is that all the memory used by the application shall be allocated during startup only. We wrote a lot of containers and algorithms that are using only preallocated memory instead of allocating new one. Do you think it is possible for us to use the boost libraries instead of our own containers in these conditions? Any comments and/or advice are welcomed! Thanks a lot, Nic
You could write your own allocator for the container, which allocates from a fixed size static buffer. Depending on the usage patterns of the container the allocator could be as simple as incrementing a pointer (e.g. when you only insert stuff into the container once at app startup, and don't continuously add/remove elements.)
166,617
166,699
"CURLE_OUT_OF_MEMORY" error when posting via https
I am attempting to write an application that uses libCurl to post soap requests to a secure web service. This Windows application is built against libCurl version 7.19.0 which, in turn, is built against openssl-0.9.8i. The pertinent curl related code follows: FILE *input_file = fopen(current->post_file_name.c_str(), "rb"); FILE *output_file = fopen(current->results_file_name.c_str(), "wb"); if(input_file && output_file) { struct curl_slist *header_opts = 0; CURLcode rcd; header_opts = curl_slist_append(header_opts, "Content-Type: application/soap+xml; charset=utf8"); curl_easy_reset(curl_handle); curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, output_file); curl_easy_setopt(curl_handle, CURLOPT_READDATA, input_file); curl_easy_setopt(curl_handle, CURLOPT_URL, fs_service_url); curl_easy_setopt(curl_handle, CURLOPT_POST, 1); curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, header_opts); rcd = curl_easy_perform(curl_handle); if(rcd != 0) { current->curl_result = rcd; current->curl_error = curl_easy_strerror(rcd); } curl_slist_free_all(header_opts); } When I attempt to execute the URL, curl returns an CURLE_OUT_OF_MEMORY error which appears to be related to a failure to allocate an SSL context. Has anyone else encountered this problem before?
After further investigation, I found that this error was due to a failure to initialise the openSSL library by calling SSL_library_init().
166,641
166,903
Is using size() for the 2nd expression in a for construct always bad?
In the following example should I expect that values.size() will be called every time around the loop? In which case it might make sense to introduce a temporary vectorSize variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change. double sumVector(const std::vector<double>& values) { double sum = 0.0; for (size_t ii = 0; ii < values.size(); ++ii) { sum += values.at(ii); } } Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.
Here's one way to do it that makes it explicit - size() is called only once. for (size_t ii = 0, count = values.size(); ii < count; ++ii) Edit: I've been asked to actually answer the question, so here's my best shot. A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize. Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt. P.S. I wrote this before I read Benoit's answer carefully, I believe we're in complete agreement.
167,427
167,730
Creating a ruler bar in MFC
What's the best way to go about creating a vertical and horizontal ruler bars in an SDI app? Would you make it part of the frame or the view? Derive it from CControlBar, or is there a better method? The vertical ruler must also be docked to a pane and not the frame. To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.
I would not use control bars. I have no good reason other then (IMOHO) are difficult to get to do what you want - if what you want if something other than a docking toolbar. I would just draw them directly on the View window using GDI calls. I guess I might think about making each ruler its own window, and draw the rulers on their own window. I would then create these two CWnd derived classes in the view and position as child windows. This is good if you want to interact with the mouse on these rulers (easier to sort out what messages are for the rulers).
167,735
167,764
Fast pseudo random number generator for procedural content
I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is Perlin Noise, but it generates too "smooth" data - for similar inputs it tends to produce similar results. The declaration of the generator should look something like: int RandomNumber1(int seed); Or: int RandomNumber3(int seedX, int seedY, int seedZ); I think having good RandomNumber1 should be enough, as it is possible to implement RandomNumber3 by hashing its inputs and passing the result into the RandomNumber1, but I wrote the 2nd prototype in case some implementation could use the independent inputs. The intended use for this generator is to use it for procedural content generator, like generating a forest by placing trees in a grid and determining a random tree species and random spatial offsets for each location. The generator needs to be very efficient (below 500 CPU cycles), because the procedural content is created in huge quantities in real time during rendering.
Seems like you're asking for a hash-function rather than a PRNG. Googling 'fast hash function' yields several promising-looking results. For example: uint32_t hash( uint32_t a) a = (a ^ 61) ^ (a >> 16); a = a + (a << 3); a = a ^ (a >> 4); a = a * 0x27d4eb2d; a = a ^ (a >> 15); return a; } Edit: Yep, some hash functions definitely look more suitable than others. For your purposes, it should be sufficient to eyeball thefunction and check that a single-bit change in the input will propagate to lots of output bits.
167,743
170,908
Quickest way to implement a C++ Win32 Splash Screen
What's a simple way to implement a c++ Win32 program to... - display an 800x600x24 uncompressed bitmap image - in a window without borders (the only thing visible is the image) - that closes after ten seconds - and doesn't use MFC
You can: Create a dialog in your resource file Have it contain a Picture control Set the picture control type to Bitmap Create/import your bitmap in the resource file and set that bitmap ID to the picture control in your dialog Create the window by using CreateDialogParam Handle the WM_INITDIALOG in order to set a timer for 10 seconds (use SetTimer) Handle WM_TIMER to catch your timer event and to destroy the window (use DestroyWindow)
167,862
168,033
How can I "unuse" a namespace?
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having... using namespace xyzzy ...statements in them, which impact on my code when I least want or expect it. Is there a way I can somehow cancel/override a previous "using" statement to avoid this. Maybe... unusing namespace xyzzy;
Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this... namespace codegear { #include "codegear_header.h" } // namespace codegear ...then the effects of any using directives within that header are neutralized. That might be problematic in some cases. That's why every C++ style guide strongly recommends not putting a "using namespace" directive in a header file.
168,232
168,331
Unresolved External Symbol Errors switching from build library to exe or dll
I am building an application as a library, but to make sure I can get the output that I'd like, I switched it over to produce an exe. As soon as I did, I got several errors about unresolved external symbols. At first I thought that I didn't have a path set to the 3rd party library that I was referencing, so I added the folder to my path variable and even added it to my include, references, and source files, just to make sure I had all the paths. I still get the error: error LNK2019: unresolved external symbol "__declspec(dllimport) public: static void __cdecl xercesc_2_8::XMLPlatformUtils::Initialize(char const * const,char const * const,class xercesc_2_8::PanicHandler * const,class xercesc_2_8::MemoryManager * const,bool)" (__imp_?Initialize@XMLPlatformUtils@xercesc_2_8@@SAXQBD0QAVPanicHandler@2@QAVMemoryManager@2@_N@Z) referenced in function "void __cdecl xsd::cxx::xml::initialize(void)" (?initialize@xml@cxx@xsd@@YAXXZ) The reason that I'm asking it here is because in Visual Studio, when I built it as a library, I didn't get these errors, but as a dll and exe, I do. Anybody have any thoughts?
Building a library, the linker doesn't need to resolve imported symbols. That happens only when it starts linking object files and libraries together. That's why you only started seeing the error when building an executable. Indeed, in VC2008 (and 2005, if I remember well), use the project properties -> Linker -> Input -> Additional dependencies. The libraries you need are to be separated by spaces (odd, hey?) Good Luck!
168,249
168,271
How do I use an arbitrary string as a lock in C++?
Let's say I have a multithreaded C++ program that handles requests in the form of a function call to handleRequest(string key). Each call to handleRequest occurs in a separate thread, and there are an arbitrarily large number of possible values for key. I want the following behavior: Simultaneous calls to handleRequest(key) are serialized when they have the same value for key. Global serialization is minimized. The body of handleRequest might look like this: void handleRequest(string key) { KeyLock lock(key); // Handle the request. } Question: How would I implement KeyLock to get the required behavior? A naive implementation might start off like this: KeyLock::KeyLock(string key) { global_lock->Lock(); internal_lock_ = global_key_map[key]; if (internal_lock_ == NULL) { internal_lock_ = new Lock(); global_key_map[key] = internal_lock_; } global_lock->Unlock(); internal_lock_->Lock(); } KeyLock::~KeyLock() { internal_lock_->Unlock(); // Remove internal_lock_ from global_key_map iff no other threads are waiting for it. } ...but that requires a global lock at the beginning and end of each request, and the creation of a separate Lock object for each request. If contention is high between calls to handleRequest, that might not be a problem, but it could impose a lot of overhead if contention is low.
You could do something similar to what you have in your question, but instead of a single global_key_map have several (probably in an array or vector) - which one is used is determined by some simple hash function on the string. That way instead of a single global lock, you spread that out over several independent ones. This is a pattern that is often used in memory allocators (I don't know if the pattern has a name - it should). When a request comes in, something determines which pool the allocation will come from (usually the size of the request, but other parameters can factor in as well), then only that pool needs to be locked. If an allocation request comes in from another thread that will use a different pool, there's no lock contention.
168,298
168,355
Will Learning C++ Help for Building Fast/No-Additional-Requirements Desktop Applications?
Will learning C++ help me build native applications with good speed? Will it help me as a programmer, and what are the other benefits? The reason why I want to learn C++ is because I'm disappointed with the UI performances of applications built on top of JVM and .NET. They feel slow, and start slow too. Of course, a really bad programmer can create a slower and sluggish application using C++ too, but I'm not considering that case. One of my favorite Windows utility application is Launchy. And in the Readme.pdf file, the author of the program wrote this: 0.6 This is the first C++ release. As I became frustrated with C#’s large .NET framework requirements and users lack of desire to install it, I decided to switch back to the faster language. I totally agree with the author of Launchy about the .NET framework requirement or even a JRE requirement for desktop applications. Let alone the specific version of them. And some of the best and my favorite desktop applications don't need .NET or Java to run. They just run after installing. Are they mostly built using C++? Is C++ the only option for good and fast GUI based applications? And, I'm also very interested in hearing the other benefits of learning C++.
If you want to build Windows applications that will run without frameworks such as .NET or virtual machines/interpreters, then your only really viable choices are going to be Visual Basic or C/C++ I've written some small Windows apps before in C++ code, and there is definitely a benefit in terms of speed and ease of deployment, at the expense of difficulty going up for development. C++ can be very fast, natively compiles, has many modern language features, and wide support. The trade off is that it's likely that you'll need to write more code in certain situations, or seek out libraries like Boost that provide the functionality you're after. As a programmer, working in C++ and especially in C is good experience for helping you understand something just a tad closer to the machine than say, .NET, Java or a scripting language like VBScript, Python, Perl etc. It won't necessarily make you a better programmer, but if you are open to learning new lessons from it you may find that it helps you gain a new perspective on software. After all, most of the frameworks and systems you depend on are written in pure C, so it will never hurt you to understand the foundations. C++ is a different animal from straight C, but if you develop in C++ for Windows you'll likely find yourself working in a mix of C and C++ to work with Windows APIs, so it will have a trickle-down effect.
168,408
168,509
C++ alternatives to void* pointers (that isn't templates)
It looks like I had a fundamental misunderstanding about C++ :< I like the polymorphic container solution. Thank you SO, for bringing that to my attention :) So, we have a need to create a relatively generic container type object. It also happens to encapsulate some business related logic. However, we need to store essentially arbitrary data in this container - everything from primitive data types to complex classes. Thus, one would immediately jump to the idea of a template class and be done with it. However, I have noticed C++ polymorphism and templates do not play well together. Being that there is some complex logic that we are going to have to work, I would rather just stick with either templates OR polymorphism, and not try to fight C++ by making it do both. Finally, given that I want to do one or the other, I would prefer polymorphism. I find it much easier to represent constraints like "this container contains Comparable types" - a la java. Bringing me to the topic of question: At the most abstract, I imagine that I could have a "Container" pure virtual interface that has something akin to "push(void* data) and pop(void* data)" (for the record, I am not actually trying to implement a stack). However, I don't really like void* at the top level, not to mention the signature is going to change every time I want to add a constraint to the type of data a concrete container can work with. Summarizing: We have relatively complex containers that have various ways to retrieve elements. We want to be able to vary the constraints on the elements that can go into the containers. Elements should work with multiple kinds of containers (so long as they meet the constraints of that particular container). Edit: I should also mention that the containers themselves need to be polymorphic. That is my primary reason for not wanting to use templated C++. So - should I drop my love for Java type interfaces and go with templates? Should I use void* and statically cast everything? Or should I go with an empty class definition "Element" that declares nothing and use that as my top level class in the "Element" hierarchy? One of the reasons why I love stack overflow is that many of the responses provide some interesting insight on other approaches that I hadn't not have even considered. So thank you in advance for your insights and comments.
Can you not have a root Container class that contains elements: template <typename T> class Container { public: // You'll likely want to use shared_ptr<T> instead. virtual void push(T *element) = 0; virtual T *pop() = 0; virtual void InvokeSomeMethodOnAllItems() = 0; }; template <typename T> class List : public Container<T> { iterator begin(); iterator end(); public: virtual void push(T *element) {...} virtual T* pop() { ... } virtual void InvokeSomeMethodOnAllItems() { for(iterator currItem = begin(); currItem != end(); ++currItem) { T* item = *currItem; item->SomeMethod(); } } }; These containers can then be passed around polymorphically: class Item { public: virtual void SomeMethod() = 0; }; class ConcreteItem { public: virtual void SomeMethod() { // Do something } }; void AddItemToContainer(Container<Item> &container, Item *item) { container.push(item); } ... List<Item> listInstance; AddItemToContainer(listInstance, new ConcreteItem()); listInstance.InvokeSomeMethodOnAllItems(); This gives you the Container interface in a type-safe generic way. If you want to add constraints to the type of elements that can be contained, you can do something like this: class Item { public: virtual void SomeMethod() = 0; typedef int CanBeContainedInList; }; template <typename T> class List : public Container<T> { typedef typename T::CanBeContainedInList ListGuard; // ... as before };
168,938
175,358
How do I include IBM XLC template *.c files in the make dependency file?
For the XLC compiler, templated code goes in a *.c file. Then when your program is compiled that uses the template functions, the compiler finds the template definisions in the .c file and instantiates them. The problem is that these .c files are not by default included when doing an xlC -qmakedepend to generate the build dependencies. So if you change one of those .c files, you won't automatically build everything that depends on it. Has anyone found a good solution to this problem?
In short, the answer is to migrate off using the XLC's tempinc utility. The tempinc utility requires you to set up your files with the template declarations in your header (.h or .hpp) file and your implementations in a .c file (this extension is mandatory). As the compiler finds template instantiations, it will put explicit instantiations in a another source file in your tempinc directory, forcing code to be generated for them. The compiler knows to find the template definitions declered in foo.h in foo.c. The problem I specified is that the dependency builders don't know about this, and thus can't include your .c files in the dependencies. With Version 6.0 IBM recommends using a the -qtemplateregistry setting rather than -qtempinc. Then, you can use a typical template set up of including the template definitions in your header file, which will then be visible to the dependency finder, or putting them in a separate file which you #include from your header file, and will also be found using the dependency finder. If you are migrating from using -qtempinc, you can conditionally #include your template implementation file from your declaration file with code like below: // end of foo.h #ifndef __TEMPINC__ #include "foo.c" #endif Thus your code will build and link if you ever decide to go back to using the -qtempic setting.
168,979
169,454
Static and dynamic library linking
In C++, static library A is linked into dynamic libraries B and C. If a class, Foo, is used in A which is defined in B, will C link if it doesn't use Foo? I thought the answer was yes, but I am now running into a problem with xlc_r7 where library C says Foo is an undefined symbol, which it is as far as C is concerned. My problem with that is Library C isn't using the class referencing it. This links in Win32 (VC6) and OpenVMS. Is this a linker discrepancy or a PBCAK? New info: B depends on C, but not visa-versa. I'm not using /OPT:REF to link on Windows and it links without issue.
When you statically link, two modules become one. So when you compile C and link A into it, its as if you had copied all the source code of A into the source code of C, then compiled the combined source. So C.dll includes A, which has a dependency on B via Foo. You'll need to link C to B's link library in order to satisfy that dependency. Note that according to your info, this will create a circular dependency between B and C.
169,058
171,134
Memory leak detection while running unit tests
I've got a Win32 C++ app with a suite of unit tests. After the unit tests have finished running, I'd like a human-readable report on any unfreed memory to be automatically generated. Ideally, the report will have a stack with files & line number info for each unfreed allocation. It would be nice to have them generated in a consistent order to make it easy to diff it from one run to the next. (Basically, I would like the results of valgrind --leak-check=full, but on windows). I've had success with UMDH getting this kind of info from running processes, but that tool only seems to work if you attach to an existing process. I want this to happen automatically every time I run my unit tests. Is there a tool that can do this? If so, how do I use it? Thanks!
I played around with the CRT Debug Heap functions Mike B pointed out, but ultimately I wasn't satisfied just getting the address of the leaked memory. Getting the stacks like UMDH provides makes debugging so much faster. So, in my main() function now I launch UMDH using CreateProcess before and after I run the tests to take heap snapshots. I also wrote a trivial batch file that runs my test harness and then diffs the heap snapshots. So, I launch the batch file and get my test results and a text file with the full stacks of any unfreed allocations all in one shot. UMDH picks up a lot of false positives, so perhaps some hybrid of the CrtDebug stuff and what I'm doing now would be a better solution. But for right now I'm happy with what I've got. Now if I just had a way to detect if I was not closing any handles...
169,194
170,972
How to communicate with an Arduino over its serial interface in C++ on Linux?
I have an RFID reader connected to an Arduino board. I'd like to connect to it over its serial interface, and whenever the RFID reader omits a signal ( when it has read an (RF)ID ), I'd like to retrieve it in my C++ program. I already have the code for simply printing the RFID to serial from the Arduino. What I don't know, is how to read it from C++ in Linux ? I have looked at libserial, which looks straightforward. However, how can I have the C++ program react to a signal and then read the RFID, instead of listening continously? Is this necessary? EDIT: In most examples I have read, the (c++) program sends input, and recieves output. I just want to listen and recieve output from the Arduino.
I found the Boost::Asio library, which reads from serial interfaces asynchronously. Boost::Asio Documentation
169,404
169,439
C++ template destructors for both primitive and complex data types
In a related question I asked about creating a generic container. Using polymorphic templates seems like the right way to go. However, I can't for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of T (along with its dimensions), allocated at some other point. I would like to be able to do something like MyContainer<float> blah(); ... delete blah; and MyContainer<ComplexObjectType*> complexBlah(); ... delete complexBlah;` Can I do something like this? Can I do it without smart pointers? Again, thanks for your input.
I'd recommend if you want to store pointers to complex types, that you use your container as: MyContainer<shared_ptr<SomeComplexType> >, and for primitive types just use MyContainer<float>. The shared_ptr should take care of deleting the complex type appropriately when it is destructed. And nothing fancy will happen when the primitive type is destructed. You don't need much of a destructor if you use your container this way. How do you hold your items in the container? Do you use an STL container, or an array on the heap? An STL container would take care of deleting itself. If you delete the array, this would cause the destructor for each element to be executed, and if each element is a shared_ptr, the shared_ptr destructor will delete the pointer it itself is holding.
170,036
170,057
Decent profiler for Windows?
Does windows have any decent sampling (eg. non-instrumenting) profilers available? Preferably something akin to Shark on MacOS, although i am willing to accept that i am going to have to pay for such a profiler on windows. I've tried the profiler in VS Team Suite and was not overly impressed, and was wondering if there were any other good ones. [Edit: Erk, i forgot to say this is for C/C++, rather than .NET -- sorry for any confusion]
Intel VTune is good and is non-instrumenting. We evaluated a whole bunch of profilers for Windows, and this was the best for working with driver code (though it does unmanaged user level code as well). A particular strength is that it reads all the Intel processor performance counters, so you can get a good understanding of why your code is running slowly, and it was useful for putting prefetch instructions into our code and sorting out data layout to work well with the cache lines, and the way cache lines get invalidated in multi core systems. It is commercial, and I have to say it isn't the easiest UI in the world.
170,380
170,391
Why do thread functions need to be declared as '__cdecl'?
Sample code that shows how to create threads using MFC declares the thread function as both static and __cdecl. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism? For example (MFC): static __cdecl UINT MyFunc(LPVOID pParam) { ... } CWinThread* pThread = AfxBeginThread(MyFunc, ...); Whereas Boost: static void func() { ... } boost::thread t; t.create(&func); (the code samples might not be 100% correct as I am nowhere near an IDE). What is the point of __cdecl? How does it help when creating threads?
__cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default. The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fastcall) and who pops arguments off the stack (caller or callee). In the case of Boost. I believe it uses template specialization to figure out the appropriate function type and calling convention.
170,909
170,929
Making a Nonblocking socket for WinSocks and *nix
In C/C++, how would I turn a blocking socket into a non blocking socket in both WinSocks and *nix; so that select() would work correctly. You can use the pre-processor for the platform specific code.
On linux: fcntl(fd, F_SETFL, O_NONBLOCK); Windows: u_long on = 1; ioctlsocket(fd, FIONBIO, &on);
171,213
171,220
How to block running two instances of the same program?
I need to make sure that user can run only one instance of my program at a time. Which means, that I have to check programatically, whether the same program is already running, and quit in such case. The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it. The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work. In case of, say, power outage, the lock file remains in place and the program can't be started again. To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process. If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file. This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low. But it still doesn't feel right (there is a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either. So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and *nix alike. If it cannot be done platform-independently, Linux/Unix is a priority for me.
There are several methods you can use to accomplish only allowing one instance of your application: Method 1: Global synchronization object or memory It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running. For example in windows you could do: #define APPLICATION_INSTANCE_MUTEX_NAME "{BA49C45E-B29A-4359-A07C-51B65B5571AD}" //Make sure at most one instance of the tool is running HANDLE hMutexOneInstance(::CreateMutex( NULL, TRUE, APPLICATION_INSTANCE_MUTEX_NAME)); bool bAlreadyRunning((::GetLastError() == ERROR_ALREADY_EXISTS)); if (hMutexOneInstance == NULL || bAlreadyRunning) { if(hMutexOneInstance) { ::ReleaseMutex(hMutexOneInstance); ::CloseHandle(hMutexOneInstance); } throw std::exception("The application is already running"); } Method 2: Locking a file, second program can't open the file, so it's open You could also exclusively open a file by locking it on application open. If the file is already exclusively opened, and your application cannot receive a file handle, then that means the program is already running. On windows you'd simply not specify sharing flags FILE_SHARE_WRITE on the file you're opening with CreateFile API. On linux you'd use flock. Method 3: Search for process name: You could enumerate the active processes and search for one with your process name.
171,435
171,449
Portability of #warning preprocessor directive
I know that the #warning directive is not standard C/C++, but several compilers support it, including gcc/g++. But for those that don't support it, will they silently ignore it or will it result in a compile failure? In other words, can I safely use it in my project without breaking the build for compilers that don't support it?
It is likely that if a compiler doesn't support #warning, then it will issue an error. Unlike #pragma, there is no recommendation that the preprocessor ignore directives it doesn't understand. Having said that, I've used compilers on various different (reasonably common) platforms and they have all supported #warning.
171,755
171,817
Visitor Pattern + Open/Closed Principle
Is it possible to implement the Visitor Pattern respecting the Open/Closed Principle, but still be able to add new visitable classes? The Open/Closed Principle states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". struct ConcreteVisitable1; struct ConcreteVisitable2; struct AbstractVisitor { virtual void visit(ConcreteVisitable1& concrete1) = 0; virtual void visit(ConcreteVisitable2& concrete2) = 0; }; struct AbstractVisitable { virtual void accept(AbstractVisitor& visitor) = 0; }; struct ConcreteVisitable1 : AbstractVisitable { virtual void accept(AbstractVisitor& visitor) { visitor.visit(*this); } }; struct ConcreteVisitable2 : AbstractVisitable { virtual void accept(AbstractVisitor& visitor) { visitor.visit(*this); } }; You can implement any number of classes which derives from AbstractVisitor: It is open for extension. You cannot add a new visitable class as the classes derived from AbstractVisitor will not compile: It closed for modification. The AbstractVisitor class tree respects the Open/Closed Principle. The AbstractVisitable class tree does not respect the Open/Closed Principle, as it cannot be extended. Is there any other solution than to extend the AbstractVisitor and AbstractVisitable as below? struct ConcreteVisitable3; struct AbstractVisitor2 : AbstractVisitor { virtual void visit(ConcreteVisitable3& concrete3) = 0; }; struct AbstractVisitable2 : AbstractVisitable { virtual void accept(AbstractVisitor2& visitor) = 0; }; struct ConcreteVisitable3 : AbstractVisitable2 { virtual void accept(AbstractVisitor2& visitor) { visitor.visit(*this); } };
In C++, Acyclic Visitor (pdf) gets you what you want.
171,816
172,001
VC9 and VC8 lib compatibility
(The original question was asked there : http://www.ogre3d.org/phpBB2/viewtopic.php?t=44832 ) Someone asked : "While I would like to build everything in vs2008 (VC9), the PhysX SDK is built with vs2005 (VC8). Would this cause any problems, using all vc9 compiled libs and used in combination with this vc8 lib?" I answered that the day before i tried to use a .lib file (and a .dll) generated with VC8 and include it in a vc9 compiled exe, the compiler couldn't open the .lib file. Now, other answered they did this with no problems.... I can't find the information about lib compatibility between vc9 and vc8. so... Help?
The lib format is COFF (http://msdn.microsoft.com/en-us/library/7ykb2k5f(VS.71).aspx), also COFF is used in the PE format. Thus I would expect that most if not all libraries built with vc8 to be linkable with vc9. However I found a thread on msdn where MS seems not to guarantee that the libs compiled with VC8 will link nicely with VC9. http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/8042a534-aa8b-4f99-81ee-e5ff39ae6e69/) Taking into account this 2 bits of info I would conclude: Although MS does not guarantee the complete 100% compatibility I would expect that in most cases linking a vc8 lib with vc9 to work. Hope this helps. P.S. You write "the compiler couldn't open the .lib file.". The linker is the one that tries to open the libraries to be linked, not the compiler.
171,862
171,869
Namespaces and Operator Overloading in C++
When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace: namespace Lib { class A { }; A operator+(const A&, const A&); } // namespace Lib or the global namespace namespace Lib { class A { }; } // namespace Lib Lib::A operator+(const Lib::A&, const Lib::A&); From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better?
You should define them in the library namespace. The compiler will find them anyway through argument dependant lookup. No need to pollute the global namespace.
172,199
172,273
good resource for socket errors?
Where can I find a list of all types of bsd style socket errors?
In the documentation? For instance, for connect(), see: % man connect ... ECONNREFUSED No-one listening on the remote address. EISCONN The socket is already connected. ENETUNREACH Network is unreachable.
172,262
172,274
C++ #include and #import difference
What is the difference between #include and #import in C++?
#import is a Microsoft-specific thing, apparently for COM or .NET stuff only. #include is a standard C/C++ preprocessor statement, used for including header (or occasionally other source code) files in your source code file.
172,587
172,592
What is the difference between g++ and gcc?
What is the difference between g++ and gcc? Which one of them should be used for general c++ development?
gcc and g++ are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler). Even though they automatically determine which backends (cc1 cc1plus ...) to call depending on the file-type, unless overridden with -x language, they have some differences. The probably most important difference in their defaults is which libraries they link against automatically. According to GCC's online documentation link options and how g++ is invoked, g++ is equivalent to gcc -xc++ -lstdc++ -shared-libgcc (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v option (it displays the backend toolchain commands being run).
172,653
177,621
Design Tab Control with Visual Studio 2008 (without SP1)
Is there any way (maybe directly editing resource files) to configure a Tab Control (add/remove tabs and their captions and contents) at design time with Visual Studio 2008 without SP1 (I heard that SP1 has such feature)? P.S.: I use c++ with wtl
I don't think it's possible. The dialog script does not support the Tab control directly, instead, it inserts a generic "CONTROL" statement in which the control "SysTabControl32" is inserted. You need to assign the pages in code. The new feature in VS 2008 SP1 has to do with the WPF controls, but since you mention that you work with WTL I assume you work with win32 dialog resources. Dave
172,854
172,995
How do you specify that an exception should be expected using Boost.Test?
I have a Boost unit test case which causes the object under test to throw an exception (that's the test, to cause an exception). How do I specify in the test to expect that particular exception. I can specify that the test should have a certain number of failures by using BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES but that seems rather unspecific. I want to be able to say at a specific point in the test that an exception should be thrown and that it should not be counted as a failure.
Doesn't this work? BOOST_CHECK_THROW (expression, an_exception_type); That should cause the test to pass if the expression throws the given exception type or fail otherwise. If you need a different severity than 'CHECK', you could also use BOOST_WARN_THROW() or BOOST_REQUIRE_THROW() instead. See the documentation
172,863
172,878
What are the greatest benefits of LLVM?
Does anyone have experience with LLVM, llvm-gcc, or Clang? The whole idea behind llvm seems very intriguing to me and I'm interested in seeing how it performs. I just don't want to dump a whole lot of time into trying the tools out if the tools are not ready for production. If you have experience with the tools, what do you think of them? What major limitations have you encountered? What are the greatest benefits? Many thanks!
I've had an initial play around with LLVM and working through this tutorial left me very very excited about it's potential; the idea that I can use it to build a JIT into an app with relative ease has me stoked. I haven't gone deep enough to be able to offer any kind of useful opinion on it's limitations, stability, performance and suchlike. I understand that it's good on all counts but that's purely hearsay.
173,366
176,380
How do you free a wrapped C++ object when associated Javascript object is garbage collected in V8?
V8's documentation explains how to create a Javascript object that wraps a C++ object. The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?
The trick is to create a Persistent handle (second bullet point from the linked-to API reference: "Persistent handles are not held on a stack and are deleted only when you specifically remove them. ... Use a persistent handle when you need to keep a reference to an object for more than one function call, or when handle lifetimes do not correspond to C++ scopes."), and call MakeWeak() on it, passing a callback function that will do the necessary cleanup ("A persistent handle can be made weak, using Persistent::MakeWeak, to trigger a callback from the garbage collector when the only references to an object are from weak persistent handles." -- that is, when all "regular" handles have gone out of scope and when the garbage collector is about to delete the object). The Persistent::MakeWeak method signature is: void MakeWeak(void* parameters, WeakReferenceCallback callback); Where WeakReferenceCallback is defined as a pointer-to-function taking two parameters: typedef void (*WeakReferenceCallback)(Persistent<Object> object, void* parameter); These are found in the v8.h header file distributed with V8 as the public API. You would want the function you pass to MakeWeak to clean up the Persistent<Object> object parameter that will get passed to it when it's called as a callback. The void* parameter parameter can be ignored (or the void* parameter can point to a C++ structure that holds the objects that need cleaning up): void CleanupV8Point(Persistent<Object> object, void*) { // do whatever cleanup on object that you're looking for object.destroyCppObjects(); } Parameter<ObjectTemplate> my_obj(ObjectTemplate::New()); // when the Javascript part of my_obj is about to be collected // we'll have V8 call CleanupV8Point(my_obj) my_obj.MakeWeak(NULL, &CleanupV8Point);
173,374
173,385
How do you deal with large dependencies in Boost?
Boost is a very large library with many inter-dependencies -- which also takes a long time to compile (which for me slows down our CruiseControl response time). The only parts of boost I use are boost::regex and boost::format. Is there an easy way to extract only the parts of boost necessary for a particular boost sub-library to make compilations faster? EDIT: To answer the question about why we're re-building boost... Parsing the boost header files still takes a long time. I suspect if we could extract only what we need, parsing would happen faster too. Our CruiseControl setup builds everything from scratch. This also makes it easier if we update the version of boost we're using. But I will investigate to see if we can change our build process to see if our build machine can build boost when changes occur and commit those changes to SVN. (My company has a policy that everything that goes out the door must be built on the "build machine".)
First, you can use the bcp tool (can be found in the tools subfolder) to extract the headers and files you are using. This won't help with compile times, though. Second, you don't have to rebuild Boost every time. Just pre-build the lib files once and at every version change, and copy the "stage" folder at build time.
173,618
173,630
Is there a portable equivalent to DebugBreak()/__debugbreak?
In MSVC, DebugBreak() or __debugbreak cause a debugger to break. On x86 it is equivalent to writing "_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the XCode question about that, but it doesn't seem portable enough. Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG_BREAK or something into the code.
What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform. Something like: #ifdef _MSC_VER #define DEBUG_BREAK __debugbreak() #else ... #endif This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use DEBUG_BREAK in your code.
173,681
173,686
String literals inside functions: automatic variables or allocated in heap?
Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually? I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough? I've compiled and ran it, it worked fine but I'm having a strange crash in my actual program where I'm assigning string literals to fields of the class like this and I suspect the case I mentioned above. #include <iostream> using namespace std; class MemoryLeak { private: char *s; public: MemoryLeak() {} void store() { s = "Storing a string"; // ONE } char *retrieve() { return s; } }; int main() { MemoryLeak *obj = new MemoryLeak(); obj->store(); cout << obj->retrieve() << endl; // TWO delete obj; return 0; } Should I be declaring the variable "s" as a char array instead of a pointer? I'm planning to use std::string, but I'm just curious about this. Any pointers or help is, as always, much appreciated :) Thanks.
String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.
173,770
508,968
What ways are there of drawing 3D trees using Java and OpenGL?
I know how to draw basic objects using JOGL or LWJGL to connect to OpenGL. What I would like is something that can generate some kind of geometry for trees, similar to what SpeedTree is famous for. Obviously I don't expect the same quality as SpeedTree. I want the trees to not look repetitive. Speed is not a concern, I do not expect to need more than 100 trees on screen at one time. Are there free tree-drawing libraries available in Java? Or sample code or demos? Is there anything in other languages which I could port or learn from?
http://arbaro.sourceforge.net/ http://www.propro.ru/go/Wshop/povtree/povtree.html Non java: http://www.aust-manufaktur.de/austt.html
173,821
173,828
How to get the function name while in a function for debug strings?
I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me? At the moment I am doing: SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in) { qDebug("lynxThreeFile::readSlideInfoHeader"); } but what I want is something generic: SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in) { qDebug(this.className() + "::" + this.functionName()); }
"__FUNCTION__" is supported by both MSVC and GCC and should give you the information you need.
173,870
176,879
Why can't c++ ifstreams read from devices?
I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone really find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why? const char* path = "/dev/disk3"; char b; // this works FILE* f= fopen(path, "rb"); int i = fread(&b, 1, 1, f); // returns 1, success! // this does not work ifstream cf(path, ios::binary); cf.read(&b, 1); bool good = cf.good(); // returns false, failure.
The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read 1023 bytes ahead, which fails with "Invalid argument". Interestingly, this ifstream is implemented on top of a FILE*. However, FILE* left to its own devices was reading ahead using a nicer, rounder number of bytes. Thanks to dtrace for vital clues. I guess we'll never know if the folk who thought they knew answer but didn't want to say were right.
173,930
173,947
Incorporating shareware restrictions in C++ software
I wish to implement my software on a shareware basis, so that the user is given a maximum trial period of (say) 30 days with which to try out the software. On purchase I intend the user to be given a randomly-generated key, which when entered enables the software again. I've never been down this route before, so any advice or feedback or pointers to 'standard' ways of how this is done would be much appreciated. I do not anticipate users cheating by changing the system date or anything like that, though this is probably worth considering. Apologies if this topic has appeared before.
With regards to a random-generated key, how will you verify a key is legit or if a key is bogus if it is actually random? Have a look at the article "Implementing a Partial Serial Number Verification System" as it is quite good and is easy to implement in any language. With regards to time trials, as basic solution would be to compare your main executable files creation time to the current system time and act on the difference. This assumes your installer sets the files creation time to the time of install as opposed to preserving the time you compiled it! :)
173,995
174,571
(re)initialise a vector to a certain length with initial values
As a function argument I get a vector<double>& vec (an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes. This will work vec.clear(); vec.resize( n, 0.0 ); And this will work as well: vec.resize( n ); vec.assign( n, 0.0 ); Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this?
std::vector<double>(n).swap(vec); After this, vec is guaranteed to have size and capacity n, with all values 0.0. Perhaps the more idiomatic way since C++11 is vec.assign(n, 0.); vec.shrink_to_fit(); with the second line optional. In the case where vec starts off with more than n elements, whether to call shrink_to_fit is a trade-off between holding onto more memory than is required vs performing a re-allocation.
174,349
174,397
Forcing single-argument constructors to be explicit in C++?
By default, in C++, a single-argument constructor can be used as an implicit conversion operator. This can be suppressed by marking the constructor as explicit. I'd prefer to make "explicit" be the default, so that the compiler cannot silently use these constructors for conversion. Is there a way to do this in standard C++? Failing that, is there a pragma (or similar) that'll work in Microsoft C++ to do this? What about g++ (we don't use it, but it might be useful information)?
Nope, you have to do it all by hand. It's a pain, but you certainly should get in the habit of making single argument constructors explicit. I can't imagine the pain you would have if you did find a solution and then had to port the code to another platform. You should usually shy away from compiler extensions like this because it will make the code less portable.