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...
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. ...
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 tim...
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...
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, a...
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 unbuff...
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" << ...
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_Close...
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 ...
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 i...
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: ...
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...
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...
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 ...
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...
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 can...
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 stil...
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...
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 he...
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};...
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...
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++ ...
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 revie...
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 bun...
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 ...
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 ...
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 allevi...
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(); St...
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 perform...
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 ...
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...
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...
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) { ...
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...
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...
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 aga...
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 ...
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 */, wind...
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 th...
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 the...
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 ch...
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 sh...
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 whil...
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 He...
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 ...
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 WS...
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 inter...
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 Yo...
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, byt...
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 g...
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(...
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 CP...
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 whe...
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 (con...
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...
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 sectio...
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 ...
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[]...
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-----------------------------7...
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 tim...
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 fu...
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 f...
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 4...
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 ...
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 ...
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 (pSingl...
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 ...
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> s...
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> #incl...
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 rece...
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); CMe...
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 f...
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...
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"); retur...
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 answe...
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 c...
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 v...
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 ...
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 F...
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 corr...
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 de...
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 ...
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 succe...
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 ...
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 y...
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 el...
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()...
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 ...
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 differ...
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, i...
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 rul...
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 ...
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:...
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 tim...
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...
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. Th...
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 th...
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 -> Inpu...
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 handleReques...
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...
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 re...
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 de...
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 es...
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 :...
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 b...
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 e...
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. ...
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 s...
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 generat...
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...
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 k...
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...
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 wh...
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 ther...
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 understandi...
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 = AfxBegi...
__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 fastc...
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 ...
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:...
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...
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...
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 answe...
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...
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&); } ...
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 ...
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...
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...
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 ...
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, pe...
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 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 handl...
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-...
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 que...
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 ...
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 ...
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 ...
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...
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::readSlideInfoHea...
"__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...
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 nice...
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 ad...
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 wou...
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 s...
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_f...
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...
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 thi...