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
224,204
224,215
Why use infinite loops?
Another poster asked about preferred syntax for infinite loops. A follow-up question: Why do you use infinite loops in your code? I typically see a construct like this: for (;;) { int scoped_variable = getSomeValue(); if (scoped_variable == some_value) { break; } } Which lets you get around not being able to...
A loop like: while (true) { // do something if (something else) break; // do more } lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while). If you've got a complex condition, you might also want to use this style to make the code clearer.
224,225
224,372
Create an Application without a Window
How would you program a C/C++ application that could run without opening a window or console?
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different. This causes the compiler to create an entry in the executable file format (PE for...
224,234
224,259
Is there a way to check if an istream was opened in binary mode?
I'm using an istream which could be stringstream, ifstream or a user-defined stream type and I need to know if, in the case of an ifstream, it was not opened in binary mode (so I can throw an exception). I have tried the following method: if ((_is.flags() & ios::binary) == 0) throw exception(...) but no exception ...
flags() returns ios_base::fmtflags which is formatting flags, whereas binary is an ios_base::openmode flag. I'm not sure if there is a way to find these out once the stream is already open. I was thinking that maybe there was a virtual member of the streambuf class that could help, but there doesn't really seem to be.
224,397
224,420
Why do people use __ (double underscore) so much in C++
I was taking a look through some open-source C++ code and I noticed a lot of double underscores used within in the code, mainly at the start of variable names. return __CYGWIN__; Just wondering: Is there a reason for this, or is it just some people's code styles? I would think that it makes it hard to read.
From Programming in C++, Rules and Recommendations : The use of two underscores (`__') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard. Underscores (`_') are often used in names of library functions (such as "_main" and "_exit"). In order to avoid collisions, do not begin an...
224,421
224,442
Constant value in conditional expression
In a coding style question about infinite loops, some people mentioned they prefer the for(;;) style because the while(true) style gives warning messages on MSVC about a conditional expression being constant. This surprised me greatly, since the use of constant values in conditional expressions is a useful way of avoid...
A warning doesn't automatically mean that code is bad, just suspicious-looking. Personally I start from a position of enabling all the warnings I can, then turn off any that prove more annoying than useful. That one that fires anytime you cast anything to a bool is usually the first to go.
224,500
224,521
How does "Edit and continue" work in Visual Studio?
I have always found this to be a very useful feature in Visual Studio. For those who don't know about it, it allows you to edit code while you are debugging a running process, re-compile the code while the binary is still running and continue using the application seamlessly with the new code, without the need to rest...
My understanding is that when the app is compiled with support for Edit and Continue enabled, the compiler leaves extra room around the functions in the binary image to allow for adding additional code. Then the debugger can compile a new version of the function, replace the existing version (using the padding space as...
224,704
231,060
boost lambda or phoenix problem: using std::for_each to operate on each element of a container
I ran into a problem while cleaning up some old code. This is the function: uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output ) { output.resize(chunks.size()); for(chunk_vec_t::iterator it = chunks.begin(); it < chunks.end(); ++it) { uint32_t success = (*it)->get_conne...
After a bit of work I came up with this solution: std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) ); It required that I change get_connectivity_data to return std::vector instead of taking one by reference, and it also required that I change the elemen...
224,777
224,802
Thread local storage with __declspec(thread) fails in C++/CLI
I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration: __declspec(thread) int lastId = 0; However, at the first access of the variable, I get a NullReferenceException. To be more precise, the d...
It seems that __declspec(thread) isn't supported by CLR. Take in mind that .net threads aren't necesarily native threads, but can be also fibers, so standard API's for threads don't work on them. If you have a managed class, then you should use managed threading API's for thread local storage. There are a lot of articl...
224,966
224,977
What is the difference between private and protected members of C++ classes?
What is the difference between private and protected members in C++ classes? I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected. What's the difference and which should I use?
Private members are only accessible within the class defining them. Protected members are accessible in the class that defines them and in classes that inherit from that class. Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes. Edit 2: Us...
225,283
225,763
Best XML serialization library for a MFC C++ app
I have an application, written in C++ using MFC and Stingray libraries. The application works with a wide variety of large data types, which are all currently serialized based on MFC Document/View serialize derived functionality. I have also added options for XML serialization based on the Stingray libraries, which i...
The Boost Serialization library supports XML. This library basically consists in: Start from the principles of MFC serialization and take all the good things it provides. Solve every single issue of MFC serialization! Among the improvements compared to MFC is support for XML. Note that you don't necessarily control t...
225,362
225,435
Convert a number to a string with specified length in C++
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492'). In other words, I need to add correct amount of leading zeros to the number. int n = 999; strin...
or using the stringstreams: #include <sstream> #include <iomanip> std::stringstream ss; ss << std::setw(10) << std::setfill('0') << i; std::string s = ss.str(); I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other ...
225,480
225,658
Embed image in code, without using resource section or external images
I'm looking for a way to embed an image in a library (Windows-only). I don't want to go the 'traditional' way of putting it in the resources (because of special circumstances that make it not so convenient to mess around with the resource handle. Ideally, there would be something like xpm files: a 'text' representation...
Google for a bin2c utility (something like http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c). It takes a file's binary representation and spits out a C source file that includes an array of bytes initialized to that data. Just link the file in and you have your image sitting in a chunk of memory. Using this kind of t...
226,064
226,104
True color CImageList
How do I load a true color image into a CImageList? Right now I have mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255)); Where IDB_IMGLIST_BGTASK is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the reso...
Needs 4 lines of code, but this works: CBitmap bm; bm.LoadBitmap(IDB_IMGLIST_BGTASK); mImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4); mImageList.Add(&bm, RGB(255,0,255));
226,144
226,251
Overload a C++ function according to the return value
We all know that you can overload a function according to the parameters: int mul(int i, int j) { return i*j; } std::string mul(char c, int n) { return std::string(n, c); } Can you overload a function according to the return value? Define a function that returns different things according to how the return value is u...
class mul { public: mul(int p1, int p2) { param1 = p1; param2 = p2; } operator int () { return param1 * param2; } operator std::string () { return std::string(param2, param1 + '0'); } private: int param1; int param2; }; Not that I would use ...
226,377
226,566
Operating System compile time
This is just a general question - I was sitting and waiting for a bit of software to compile (we use Incredibuild here but can still take 10/15 mins) and it got me wondering, does anyone know how long it took to compile Windows XP or Vista? I did some googling but didn't really find any useful information
OP is asking about Windows: "There are no other software projects like this," Lucovsky said, "but the one thing that's remained constant [over the years] is how long it takes to build [Windows]. No matter which generation of the product, it takes 12 hours to compile and link the system." Even with the increase in proc...
226,402
226,733
Make Eclipse treat .h file as C++?
All of our C++ headers use a .h extension. Eclipse thinks these are C headers and flags them with lots of syntax errors on things like classes and namespaces. I've tried to change the file type association from: Preferences > C/C++ > File types but it's "locked". Interestingly, "*.h" is associated with both C and C++ ...
Try creating a new project and specify your source area as the location. However, be sure you select C++ project (I usually use the makefile option). This is all you should have to do in order to make the parser recognize C++ syntax.
226,577
226,674
Strange program hang, what does this mean in debug?
Strange program hang, what does this mean in debug? After attaching windbg I found the following: (1714.258): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=015b5c74 ebx=178a13e0 ecx=dddddddd edx=009a8c...
The problem First chance exceptions means that the debugger is giving you, the person who is using the debugger, the first chance to debug the exception, before it throws it back at the program to handle the issue. In this case the exception is "Access violation". This means that your program is trying to read / write...
226,939
274,246
Code Synthesis doesn't seem to generate a "valid" xml tree
I've been working with code synthesis xsd to generate an xml tree to ensure constinency of the xml output to the original xsd. After initial testing, everything looked ok but when I tried entering invalid values (correct type, but outside the defined range), the values were allowed. Although the xml is well formed and ...
The tool may not do the sort of checking you want when creating the document. If your document is small, you may just want to generate the XML,then re-parse it with XSD checking on and let that be your checking.
227,001
227,014
Best method to determine changed data in C++
I need to write a tool in C++ to determine the changed bits in a file compared against another file for replication. What would be the best method of accomplishing this? I don't have a specific OS or library in mind, I'm open to suggestions. My primary goal is reducing the amount of network traffic involved in replic...
Look at rsync - it splits the file into blocks, calculates a checksum for each block, and transmits only the checksum to determine if there are any changesto the destination before transmitting the block data only if necessary.
227,762
12,829,806
Looking for 16-bit x86 compiler
I am working on an embedded systems project and have run into an issue of the compiler being programatically embedded in the Paradigm C++ IDE. I would like to be able to automate building. The processor is the AMD186ES. I am not working with the OS - just baremetal stuff. I need to generate real-mode 16-bit 8086 machin...
I am currently using gnu as (part of binutils and the assembler used for gcc) and I have successfully been assembling 16bit assembly code with the following: as <file> ld --oformat binary -Ttext 0x0 -e start <file> with my assembly files starting out with: .code16 .globl start .text start: since its plain binary omit...
228,005
228,039
Alternative to itoa() for converting integer to string C++?
I was wondering if there was an alternative to itoa() for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
In C++11 you can use std::to_string: #include <string> std::string s = std::to_string(5); If you're working with prior to C++11, you could use C++ streams: #include <sstream> int i = 5; std::string s; std::stringstream out; out << i; s = out.str(); Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-...
228,036
228,065
C++ template instantiation of function template parameters
I have the following problem using template instantiation [*]. file foo.h class Foo { public: template <typename F> void func(F f) private: int member_; }; file foo.cc template <typename F> Foo::func(F f) { f(member_); } file caller.cc Foo::func(boost::bind(&Bar::bar_func, bar_instance, _1)); Whil...
The answer to this is compiler dependent. Some versions of the Sun C++ compiler would handle this automatically by building a cache of template function implementations that would be shared across separate translation units. If you're using Visual C++, and any other compiler that can't do this, you may as well put the...
228,304
601,719
Is there any C++ lib to read thumbnails from thumb.db in Windows Folder?
I want to read all thumbnails from a folder with images in Windows XP. But if I read image file to get thumbnail, it seems a bit slow, so I wish I can first read the windows image thumbnail cache:thumb.db. Is there any lib in c++ or c to read thumbnails from thumb.db.
You might find this useful: ThumbsDBLib in C++ http://www.windameister.org/blog/index.php/thumbslib-in-cpp
228,404
228,546
Extending an existing class like a namespace (C++)?
I'm writing in second-person just because its easy, for you. You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code. So you could derive a new class from it with your one new method and put tha...
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up a...
228,617
228,625
How do I clear the console in BOTH Windows and Linux using C++
I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two ...
Short answer: you can't. Longer answer: Use a curses library (ncurses on Unix, pdcurses on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that behave like console windows). M...
228,620
228,722
Garbage Collection in C++ -- why?
I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right? My only experience with garbage collection wa...
I keep hearing people complaining that C++ doesn't have garbage collection. I am so sorry for them. Seriously. C++ has RAII, and I always complain to find no RAII (or a castrated RAII) in Garbage Collected languages. What advantages could garbage collection offer an experienced C++ developer? Another tool. Matt J wrote...
228,675
228,733
How to select and highlight a window in another application?
I would like to send some keystrokes from a C++ program into another window. For that reason I would like to have the user select the target window similar to how it is done in the Spy++ utility that comes with Visual Studio (drag a crosshair cursor over target window and have target window highlighted by a frame). How...
Here's how it's usually done: Capture the mouse using SetCapture. This will cause all mouse messages to be routed toward your app's window. Handle the WM_MOUSEMOVE message. In your handler code, grab the window underneath the mouse using WindowFromPoint. That will get you the HWND of the window the mouse is currently ...
228,881
228,899
How can I specify that library X must be linked statically?
I have a piece of software which is linked against several libraries. They all exists in a dynamic (.so) and a static (.a) version. By default, when using g++ it chooses the dynamic version of the libraries and that's fine with me. However, one of them absolutely needs to be linked statically. I thought about using -s...
g++ -o foo (foo-objects) -Wl,-Bstatic -lmustbestatic -Wl,-Bdynamic -lother-lib
228,908
228,914
Is list::size() really O(n)?
Recently, I noticed some people mentioning that std::list::size() has a linear complexity. According to some sources, this is in fact implementation dependent as the standard doesn't say what the complexity has to be. The comment in this blog entry says: Actually, it depends on which STL you are using. Microsoft Vis...
Pre-C++11 answer You are correct that the standard does not state what the complexity of list::size() must be - however, it does recommend that it "should have constant complexity" (Note A in Table 65). Here's an interesting article by Howard Hinnant that explains why some people think list::size() should have O(N) com...
229,069
229,121
Dead code detection in legacy C/C++ project
How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that?
You could use a code coverage analysis tool for this and look for unused spots in your code. A popular tool for the gcc toolchain is gcov, together with the graphical frontend lcov (http://ltp.sourceforge.net/coverage/lcov.php). If you use gcc, you can compile with gcov support, which is enabled by the '--coverage' fla...
229,664
230,222
Native VC++ using external (not project) dll reference how to specify path to dll
I have a native VC++ project that uses a dll (which is not in a project). Now, I must to put the dll in one the "Search Path Used by Windows to Locate a DLL" link but I don't want the dll to sit in the exectuable or current or windows or system directory. So my only option according to that is adding the path to the %...
Summing up all the techniques I have found: If you use a managed project as the startup project (which is actually my case) use Enviroment class string temp = "myFullDirectoryPathToDll"; string temp2 =Environment.GetEnvironmentVariable("PATH") + ";" + temp; Environment.SetEnvironmentVariable("PATH", temp2); this, an...
229,671
229,704
C for loop implemented differently than other languages?
I read the following in a review of Knuth's "The Art of Computer Programming": "The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behav...
Consider this: for i:=0 to 100 do { ... } In this case, we could replace the final value, 100, by a function call: for i:=0 to final_value() do { ... } ... and the final_value-function would be called only once. In C, however: for (int i=0; i<final_value(); ++i) // ... ... the final_value-function would be called fo...
229,924
230,878
Difference between files written in binary and text mode
What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C. unsigned char buffer[256]; for (int i = 0; i < 256; i++) buffer[i]=i; int size = 1; int count = 256; Binary mode: FILE *fp_binary = fopen(filename, "wb"); fwrite(buffer, size, c...
I believe that most platforms will ignore the "t" option or the "text-mode" option when dealing with streams. On windows, however, this is not the case. If you take a look at the description of the fopen() function at: MSDN, you will see that specifying the "t" option will have the following effect: line feeds ('\n'...
230,687
230,729
Counterpart of PHP's isset() in C/C++
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not. Can we build similar feature for C/C++ (some kind of symbol table lookup)?
I'm a C++ guy, but I remember in PHP isset is used to check if a variable contains a value when passed in through a get/post request (I'm sure there are other uses, but that's a common one I believe). You don't really have dynamic typing in C++. So you can't suddenly use a variable name that you haven't previously expl...
230,715
231,117
Mixed Mode Library and CRT Dependencies - HELP
Alright, after doing a ton of research and trying almost every managed CPP Redist I can find as well as trying to copy my DLLs locally to the executing directory of the app I cannot figure out what dependencies i'm missing for this mixed mode library. Basically I have a large C# application and I'm trying to use a mixe...
Did you deploy the CRT libraries on the target machine? Long shot: since you have a dependency on 32-bit code, you should set Target Platform in the Build property tab to x86. EDIT: trouble-shoot side-by-side resolving problems with the Sxstrace.exe utility, available on Vista.
230,790
230,806
Can initialization list in constructors be used in template classes?
I find that most books concerning C++ templates don't tell anything about whether it's possible or not to use initialization list in constructor of a template class. For example, I have code like this: template <class T> class Stack { T* data; std::size_t count; std::size_t capacity; enum {INIT = 5}; pu...
Yes. Did the compiler tell you otherwise?
231,128
231,200
C++ Error Handling -- Good Sources of Example Code?
Just about every piece of example code everywhere omits error handling (because it "confuses the issue" that the example code is addressing). My programming knowledge comes primarily from books and web sites, and you seldom see any error handling in use at all there, let alone good stuff. Where are some places to see g...
Herb Sutter's and Andrei Alexandrescu's book C++ Coding Standards comes with a whole chapter on Error Handling and Exceptions including Assert liberally to document internal assumptions and invariants Establish a rational error handling policy, and follow it strictly Distinguish between errors and non-errors Design an...
231,146
231,173
std::string erase last character fails?
I'm trying to change user input in wildcard form ("*word*") to a regular expression format. To that end, I'm using the code below to strip off the '*' at the beginning and end of the input so that I can add the regular expression characters on either end: string::iterator iter_begin = expressionBuilder.begin(); str...
Try erasing them in the opposite order: expressionBuilder.erase(iter_end); expressionBuilder.erase(iter_begin); After erasing the first *, iter_end refers to one character past the end of the string in your example. The STL documentation indicates that iterators are invalidated by erase(), so technically my example is...
231,198
231,319
Correct way to use custom functor with std::generate_n() algorithm?
The following code compiles correctly under VC++ 8 on XPSP3, but running it causes a runtime error. My header looks like: #include <stdexcept> #include <iterator> #include <list> template<typename T> class test_generator { public: typedef T result_type; //constructor test_generator() { s...
The test_generator constructor initialises the value iterator to reference the first element in the tests list (which is a member of test_generator). When you call std::generate_n, a copy of the test is made (because the object is passed by value). In the copied object, the value iterator refers to the tests list in th...
231,220
231,244
Window Handle and window dimension
The MFC application that i created is dialog based. Just one dialog thats all. How do I get the window handle to this window, while the application is performing the InitDialog. I need to find out its dimension as well. GetForegroundWindow not necessarily gives you the handle to this window that is loading up
Check the m_hWnd member of your dialog object. GetClientRect() should work to give you the size of client (interior) of the dialog. GetWindowRect() will give you the total size including window borders, but the position will be off.
231,318
231,392
A Strategy against Policy and a Policy against Strategy
When I first discovered the Strategy pattern, I was amazed of the seemingly endless possibilities it offered to me and my programs. I could better encapsulate my models' behaviour and even exchange this behaviour on the fly. But the strategy could also be used to to provide traits and payload to the containing object -...
Policies are largely set at compile time, while strategies are set at runtime. Further, policies are generally a C++ concept, and apply only to a minority of other languages(for example D), while strategy pattern is available to many (most?) object oriented languages, and languages that treat functions as first class ...
231,381
231,398
Is this prime generator inefficient C++?
Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower? I am trying to submit this to SPOJ and it tells me that my time limit exceeded... #include <iostream> #include <sstream> using namespace std; int main()...
This is one step (skipping even numbers) above the naive algorithm. I would suggest the Sieve Of Eratosthenes as a more efficient algorithm. From the above link: The complexity of the algorithm is O((nlogn)(loglogn)) with a memory requirement of O(n). The segmented version of the sieve of Eratosthenes, with ...
231,491
231,495
how-to initialize 'const std::vector<T>' like a c array
Is there an elegant way to create and initialize a const std::vector<const T> like const T a[] = { ... } to a fixed (and small) number of values? I need to call a function frequently which expects a vector<T>, but these values will never change in my case. In principle I thought of something like namespace { const st...
For C++11: vector<int> luggage_combo = { 1, 2, 3, 4, 5 }; Original answer: You would either have to wait for C++0x or use something like Boost.Assign to do that. e.g.: #include <boost/assign/std/vector.hpp> using namespace boost::assign; // bring 'operator+=()' into scope vector<int> v; v += 1,2,3,4,5;
231,547
234,108
Tracing which process that has opened a particular file
From kernel mode in Windows I'm able to intercept and monitor virtually all actions performed on a particular disk. When a file is opened for any purpose I get an event. Now I want to trace which application that opened it. I think this should be possible but don't know how. I'm using the standard file management funct...
Just use Win32 N.API to get the pid from the File handle. It's a FAQ for 15 years...
231,746
231,809
How do I Monitor Text File Changes with C++? Difficulty: No .NET
Use case: 3rd party application wants to programatically monitor a text file being generated by another program. Text file contains data you want to analyze as it's being updated. I'm finding a lot of answers to this question wrapped around FileSystemWatcher but let's say you are writing an application for a Windows ma...
You can monitor a directory with FindFirstChangeNotification works on any windows. It's efficent if you know where the file is - otherwise you can use the virtual driver/Filemon described below to check for changes anywhere on the system. Example code here
231,868
239,654
C++ two or more data types in declaration
I'm getting a strange error from g++ 3.3 in the following code: #include <bitset> #include <string> using namespace std; template <int N, int M> bitset<N> slice_bitset(const bitset<M> &original, size_t start) { string str = original.to_string<char, char_traits<char>, allocator<char> >(); string newstr = str.s...
The selected answer from CAdaker solves the problem, but does not explain why it solves the problem. When a function template is being parsed, lookup does not take place in dependent types. As a result, constructs such as the following can be parsed: template <typename T> class B; template <typename T> void foo (B<T>...
231,885
231,921
Violation reading location in std::map operator[]
I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence freq...
Given an address of "4", Likely the "this" pointer is null or the iterator is bad. You should be able to see this in the debugger. If this is null, then the problem isn't in that function but who ever is calling that function. If the iterator is bad, then it's the race condition you alluded to. Most iterators can't...
232,030
232,045
C++ Parent class calling a child virtual function
I want a pure virtual parent class to call a child implementation of a function like so: class parent { public: void Read() { //read stuff } virtual void Process() = 0; parent() { Read(); Process(); } } class child : public parent { public: virtual void Process() { //process...
Title of the following article says it all: Never Call Virtual Functions during Construction or Destruction.
232,161
232,176
Debugging Multi-Project (C++) Solutions in Visual Studio 2005
I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As ...
What you need is in the Tools menu: Attach to Process. This gives you a list of running processes and allows you to attach your debugger to those processes. For local debugging, Transport and Qualifier should keep their default values. The Attach To value just above the list determines which type of debugging you'll be...
232,926
232,959
How to make consistent dll binaries across VS versions?
For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't change...
First, dont pass anything other than plain old data accross DLL boundries. i.e. structs are fine. classes are not. Second, make sure that ownership is not transferred - i.e. any structs passed accross the dll boundry are never deallocated outside the dll. So, if you dll exports a X* GetX() function, there is a correspo...
233,035
233,143
What are underscored symbols in a VB DLL?
I have a C++ app in VS2005 and import a VB DLL. IntelliSense shows me all the symbols in the DLL as expected but it also shows all (or nearly all) of them again with an underscore prefix (no @s in them though). Why is this? What are the differences between the underscored items and the normal items?
Assuming you're talking VB6, the leading underscore version _Klass is the Vb-generated default interface for the class Klass. This site has a nice explanation: http://www.15seconds.com/issue/040721.htm
233,127
32,428,427
How can I propagate exceptions between threads?
We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread. The result is that the caller can use the function naively, and intern...
C++11 introduced the exception_ptr type that allows to transport exceptions between threads: #include<iostream> #include<thread> #include<exception> #include<stdexcept> static std::exception_ptr teptr = nullptr; void f() { try { std::this_thread::sleep_for(std::chrono::seconds(1)); throw std::...
233,258
233,313
Is there an acceptable limit for memory leaks?
I've just started experimenting with SDL in C++, and I thought checking for memory leaks regularly may be a good habit to form early on. With this in mind, I've been running my 'Hello world' programs through Valgrind to catch any leaks, and although I've removed everything except the most basic SDL_Init() and SDL_Quit...
Be careful that Valgrind isn't picking up false positives in its measurements. Many naive implementations of memory analyzers flag lost memory as a leak when it isn't really. Maybe have a read of some of the papers in the external links section of the Wikipedia article on Purify. I know that the documentation that come...
233,328
233,339
How do I print the full value of a long string in gdb?
I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?
set print elements 0 From the GDB manual: set print elements number-of-elements Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of...
233,446
233,456
Monitor battery charge with Win32 API
I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.
For Vista and up you can use RegisterPowerSettingNotification For earlier functions see the Power Management Functions in this section of the MSDN page "Power Management Functions: Windows Server 2003 and Earlier" You can see example code of the Vista method on codeproject.
233,911
235,713
ie useragent wxWidgets
Im currently using ie as an active x com thing on wxWidgets and was wanting to know if there is any easy way to change the user agent that will always work. Atm im changing the header but this only works when i manually load the link (i.e. call setUrl)
The only way that will "always work," so far as I've been able to find, is changing the user-agent string in the registry. That will, of course, affect every web browser instance running on that machine. You might also try a Google search on DISPID_AMBIENT_USERAGENT. From this Microsoft page: MSHTML will also ask for ...
234,012
234,420
How can I set the flag FILE_FLAG_BACKUP_SEMANTICS for an fstream object?
How can I set the flag FILE_FLAG_BACKUP_SEMANTICS for an fstream object? You can set most flags with fstream, but it seems like this one is not availble. You can read about the flag here.
I've done this sort thing in the past but it's been a while so I'm not sure I have it right. Not well documented, but in vs2008, fstream takes a FILE object as a constructor. You can create a FILE object from a file id with _fdopen(). You can get a file id from an os handle using _open_osfhandle. So I think it's like...
234,027
234,277
How can I find the index in a string that matches a boost regex?
How can I find the index in a string that matches a boost regex?
If you use boost::regex_match it's the whole string that's matching. Maybe you mean to use regex_search: void index(boost::regex& re,const std::string& input){ boost::match_results<std::string::const_iterator> what; boost::match_flag_type flags = boost::match_default; std::string::const_iterator s = input.b...
234,171
234,183
Parse a Date from a String in Win32
I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of GetDateFormat().
No, but you can write a function that will convert the date format string into a sscanf format string and series of variables. Then copy the data from the variables to the SYSTEMTIME structure and you're all set. It's not trivial, but it is probably the most flexible arrangement if you must support many different date...
234,234
234,273
Are pipes considered dangerous to use in Windows, from a security standpoint?
Are pipes considered dangerous to use in Windows, from a security standpoint?
Pipes aren't a particular security risk in Windows. If you're worried about security, make sure you set the security descriptor on the pipe to an appropriate DACL. If your usage requires that the pipe is open for anyone to connect to, then you have to treat the incoming data as suspicious, just like any file or network...
234,365
234,505
Is TCHAR still relevant?
I'm new to Windows programming and after reading the Petzold book I wonder: is it still good practice to use the TCHAR type and the _T() function to declare strings or if I should just use the wchar_t and L"" strings in new code? I will target only Windows 2000 and up and my code will be i18n from the start up.
I would still use the TCHAR syntax if I was doing a new project today. There's not much practical difference between using it and the WCHAR syntax, and I prefer code which is explicit in what the character type is. Since most API functions and helper objects take/use TCHAR types (e.g.: CString), it just makes sense to ...
234,388
234,407
Generating a Deck of Cards
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards. #include <iostream> #include <vector> using namespace std; int main() { vector<char> deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','10','J','...
Try to create class of Card with suit and card as a member and set it as a type of vector. Like public class Card { public: Card(char suit, char card); char suit, card; }; int main() { vector<Card> deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','T','J','Q','K','A...
234,458
234,491
Do polymorphism or conditionals promote better design?
I recently stumbled across this entry in the google testing blog about guidelines for writing more testable code. I was in agreement with the author until this point: Favor polymorphism over conditionals: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many p...
Actually this makes testing and code easier to write. If you have one switch statement based on an internal field you probably have the same switch in multiple places doing slightly different things. This causes problems when you add a new case as you have to update all the switch statements (if you can find them). By ...
234,482
234,593
using STL to find all elements in a vector
I have a collection of elements that I need to operate over, calling member functions on the collection: std::vector<MyType> v; ... // vector is populated For calling functions with no arguments it's pretty straight-forward: std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc)); A similar thing can be done...
Boost Lambda makes this easy. #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> std::for_each( v.begin(), v.end(), if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ] ); You could even do away with defining MyPred(), if it is simple. This is ...
234,503
234,513
What are you using to unit test your C++ code?
I'm looking into some possible options for unit testing C++ classes. So, short and to the point, what are you using?
I'm using cppunit. It is a pretty good port of the iconic JUnit to c++.
234,724
234,740
Is it possible to serialize and deserialize a class in C++?
Is it possible to serialize and deserialize a class in C++? I've been using Java for 3 years now, and serialization / deserialization is fairly trivial in that language. Does C++ have similar features? Are there native libraries that handle serialization? An example would be helpful.
The Boost::serialization library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here. The only native way to do it is to use streams. That's essentially all the Boost::serialization library does, it extends the stream method by setting up a framework ...
234,866
234,879
Variable Naming Conventions in C++
I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members. For example, the legacy code that I've inheritted has alot of these: struct MyStruct { TCHAR szMyChar[STRING_SIZE]; bool ...
That kind of Hungarian Notation is fairly useless, and possibly worse than useless if you have to change the type of something. (The proper kind of Hungarian Notation is a different story.) I suggest you use whatever your group does. If you're the only person working on the program, name them whatever way makes the mos...
234,872
235,121
Changing folder security permissions via Win32 API
My C++ application stores some common user data in %CSIDL_COMMON_APPDATA%\Company\Product. I want to make sure the Users group has write permissions to this folder which on Vista it does not. How would do I do this?
Figured it out myself using ATL... CDacl oDacl; AtlGetDacl(strFolder, SE_FILE_OBJECT, &oDacl); oDacl.RemoveAces(Sids::Users()); // Remove existing "Users" access oDacl.AddAllowedAce(Sids::Users(), FILE_ALL_ACCESS, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE); AtlSetDacl(strFolder, SE_FILE_OBJECT, oDacl); Of course my r...
235,072
235,103
Do modern compilers optimize the x * 2 operation to x << 1?
Does the C++ compiler optimize the multiply by two operation x*2 to a bitshift operation x<<1? I would love to believe that yes.
Actually VS2008 optimizes this to x+x: 01391000 push ecx int x = 0; scanf("%d", &x); 01391001 lea eax,[esp] 01391004 push eax 01391005 push offset string "%d" (13920F4h) 0139100A mov dword ptr [esp+8],0 01391012 call dword ptr [__imp__scanf (13920A4h)] ...
235,326
236,364
Simplest, safest way of holding a bunch of const char* in a set?
I want to hold a bunch of const char pointers into an std::set container [1]. std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers. I know I can define my own functor and im...
Just go ahead and use the default ordering which is less<>. The Standard guarantees that less will work even for pointers to different objects: "For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not."...
235,376
235,503
C++ dynamic class ( dynamic hack )
Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet : Myobject *ob; // create an object ob->addField("newField",44); // we add the field to the class and we assign an initial value to it printf("%d",ob->newField); // now we can access that field I do...
Use a map and a variant. For example, using boost::variant. See http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html (But of course, you can create your own, to suit the types of your XML attributes.) #include <map> #include <boost/variant.hpp> typedef boost::variant< int, std::string > MyValue ; typedef std::ma...
235,422
235,468
Is there a standard way to do findfirst, findnext with gcc on linux using stl?
I can't seem to find the _findfirst / findfirst, _findnext / findnext API on gcc for Linux, and would actually rather use the Standard Template Library (STL) for that if it is included there. Does anyone know what API there is available for listing files in a directory under Linux for C++ (gcc)?
Check out the Boost.Filesystem library. In particular, the basic_directory_iterator.
235,570
235,693
Can the overall implementation of a component be divided in two objects?
I've seen with Microsoft COM and XPCOM, at least from what I've read and gathered so far, that the implementations of interfaces in a component have to essentially be in the single class that derives all the virtual interfaces. Is this correct? What am I missing? Is there a way to have multiple objects (possibly in sep...
This should be possible, although probably not supported by the standard high-level wrappers. Most of the wrappers (ATL, MFC, etc.) only support mapping a COM object to a single class. However, QueryInterface is allowed to return a different pointer and calls COM object code, so the first COM object could load a differ...
235,616
235,623
Multiple definitions of a function template
Suppose a header file defines a function template. Now suppose two implementation files #include this header, and each of them has a call to the function template. In both implementation files the function template is instantiated with the same type. // header.hh template <typename T> void f(const T& o) { // ... ...
In order to support C++, the linker is smart enough to recognize that they are all the same function and throws out all but one. EDIT: clarification: The linker doesn't compare function contents and determine that they are the same. Templated functions are marked as such and the linker recognizes that they have the sam...
235,664
236,025
How to use std::signaling_nan?
After looking at another question on SO (Using NaN in C++) I became curious about std::numeric_limits<double>::signaling_NaN(). I could not get signaling_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catching SIGFPE but nope... Here is my code: double my_nan = numeric_lim...
You can use the _control87() function to enable floating-point exceptions. From the MSDN documentation on _control87(): Note: The run-time libraries mask all floating-point exceptions by default. When floating point exceptions are enabled, you can use signal() or SEH (Structured Exception Handling) to catch them.
235,762
235,776
How do you throttle the bandwidth of a socket connection in C?
I'm writing a client-server app using BSD sockets. It needs to run in the background, continuously transferring data, but cannot hog the bandwidth of the network interface from normal use. Depending on the speed of the interface, I need to throttle this connection to a certain max transfer rate. What is the best way ...
The problem with sleeping a constant amount of 1 second after each transfer is that you will have choppy network performance. Let BandwidthMaxThreshold be the desired bandwidth threshold. Let TransferRate be the current transfer rate of the connection. Then... If you detect your TransferRate > BandwidthMaxThreshold th...
235,763
235,772
Cancel libcurl easy handle
Is there an easy way to cancel a curl_easy_perform from another thread?
You have to use the callback functions (write/read/progress) to perform the cancel. The other thread needs to set a flag and the callback function checks the flag and returns the proper value to cancel the operation.
236,035
236,052
Unmanaged DLLs in C++
I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you. So, let's assume I have just a functi...
I cannot stress this enough, the C++ compiler does not see header files, after the preprocessor is done, there's just one big source file ( also called the compilation unit ). So strictly you don't need a header to export this function from a dll. What you do need is some form of conditional compilation to export the f...
236,086
236,144
Parsing C++ to generate unit test stubs
I've recently been trying to create units tests for some legacy code. I've been taking the approach of using the linker to show me which functions cause link errors, greping the source to find the definition and creating a stub from that. Is there an easier way? Is there some kind of C++ parser that can give me class...
You may want to investigate http://os.inf.tu-dresden.de/vfiasco/related.html#parsing. But C++ parsing is hard. On the other hand, maybe ctags or something similar can extract class definitions... You may also try to write your own simple (?) parser to generate class stubs from header files... I tried to give you some p...
236,125
351,292
How to convert (not necessarily programmatically) between Windows' wchar_t and GCC/Linux one?
Suppose I have this Windows wchar_t string: L"\x4f60\x597d" and L"\x00e4\x00a0\x597d" and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concret...
One of the most used libraries to do character conversion is the ICU library http://icu-project.org/ It is e.g. used by some boost http://www.boost.org/ libraries.
236,129
237,280
How do I iterate over the words of a string?
How do I iterate over the words of a string composed of words separated by whitespace? Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution: #include <iostream> #include <sstream> #include <string> using namespace std; ...
For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL. #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> int main() { using n...
236,156
236,263
Could you recommend any open source projects where the source is extensively tested with unit tests?
Programming is learned by writing programs. But code reading is said to be another good way of learning. I would like to improve my unit-testing skills by reading, examining real-world code. Could you recommend any open source projects where the source is extensively tested with unit tests? I'm interested in code writt...
AFAIK C++ Boost libraries - http://boost.org/ - have broadly covered code base, and a policy that every new piece of code must have unit tests with it. Might be worth checking.
236,172
236,199
How do I sort a std::vector by the values of a different std::vector?
I have several std::vector, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold ints and some of them std::strings. Pseudo code: std::vector<int> Ind...
friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…n, along with the elements from the vector dictating the sorting order: typedef vector<int>::const_iterator myiter; vector<pair<size_t, myiter> > order(Index.size()); size_t n = 0; for (myiter it = Index.begin(); it !=...
236,335
236,338
When I calculate a large factorial, why do I get a negative number?
So, simple procedure, calculate a factorial number. Code is as follows. int calcFactorial(int num) { int total = 1; if (num == 0) { return 0; } for (num; num > 0; num--) { total *= num; } return total; } Now, this works fine and dandy (There are certainly quicker and ...
2^32 doesn't give you the limit for signed integers. The signed integer limit is actually 2147483647 (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar). You'll need a C++ large number library like this one.
236,399
236,418
What advantages does C++ have over other languages for Qt development?
As well-known, C++ has steeper learning curve than most of the mainstream languages, which results in better performance . But, does using C++ over other languages[like Java,Ruby,Python] for Qt development have still (major) advantages,let's say about Qtopia? If any, what are they?
Qt is natively a C++ API, so any other languages have to have wrapper code around it which needs to be maintained, etc. The primary documentation will also be for the C++ API. I'm not sure if there are any "official" bindings to other languages which are maintained and released together with Qt.
236,669
236,674
What's an easy way to obtain the current svn revision in a c++ visual studio application
Is there any easy way to access the SVN repository revision number and store it in a c++ string in a c++ visual studio application? Thanks for your help in advance!
If you have tortoise SVN you can use SubWCRev.exe Create a file called: RevisionInfo.tmpl int SvnRevision = $WCREV$; Then execute this command: SubWCRev.exe . RevisionInfo.tmpl RevisionInfo.cpp It will create a file ReivisonInfo.cpp with your revision number as follows: int SvnRevision = 5000; From your other files...
236,792
242,676
designing business msgs parser / rewriting from scratch
I take care of critical app in my project. It does stuff related to parsing business msgs (legacy standard), processing them and then storing some results in a DB (another apps picks that up). After more then a year of my work (I've other apps to look after as well) the app is finally stable. I've introduced strict TDD...
I would advise you not to inherit your specific message handling classes from base classes that contain the common code like this: CommonHandler ^ ^ | | = inheritance MsgAHandler ^ ^ | ...
236,801
237,074
Should operator<< be implemented as a friend or as a member function?
That's basically the question, is there a "right" way to implement operator<< ? Reading this I can see that something like: friend bool operator<<(obj const& lhs, obj const& rhs); is preferred to something like ostream& operator<<(obj const& rhs); But I can't quite see why should I use one or the other. My personal ...
The problem here is in your interpretation of the article you link. Equality This article is about somebody that is having problems correctly defining the bool relationship operators. The operator: Equality == and != Relationship < > <= >= These operators should return a bool as they are comparing two objects of the ...
237,064
237,072
C++ Nested classes driving me crazy
i am trying to compile this very simple piece of code class myList { public: std::vector<std::string> vec; class Items { public: void Add(std::string str) { myList::vec.push_back(str); }; }items; }; int main() { myList newList; newList.items.Add("A"); } ...
Add a couple of constructors and a pointer to the parent class. #include <string> #include <vector> class myList { public: std::vector<std::string> vec; myList(): items(this) {} // Added class Items { public: Items(myList *ml): self(ml) {} // Added void Add(std::string str) ...
237,285
237,341
Where do you find templates useful?
At my workplace, we tend to use iostream, string, vector, map, and the odd algorithm or two. We haven't actually found many situations where template techniques were a best solution to a problem. What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a ...
I've used a lot of template code, mostly in Boost and the STL, but I've seldom had a need to write any. One of the exceptions, a few years ago, was in a program that manipulated Windows PE-format EXE files. The company wanted to add 64-bit support, but the ExeFile class that I'd written to handle the files only worked ...
237,370
283,023
Does "std::size_t" make sense in C++?
In some code I've inherited, I see frequent use of size_t with the std namespace qualifier. For example: std::size_t n = sizeof( long ); It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?). Isn't it true that size_t is built into C++ and therefore in the global n...
There seems to be confusion among the stackoverflow crowd concerning this ::size_t is defined in the backward compatibility header stddef.h . It's been part of ANSI/ISO C and ISO C++ since their very beginning. Every C++ implementation has to ship with stddef.h (compatibility) and cstddef where only the latter defines ...
237,425
237,454
What are the coolest examples of metaprogramming that you've seen in C++?
What are the coolest examples of metaprogramming that you've seen in C++? What are some practical uses of metaprogramming that you've seen in C++?
Personally, I think Boost.Spirit is a pretty amazing example of meta-programming. It's a complete parser generator that lets you express grammars using C++ syntax.
237,542
237,635
Getting base name of the source file at compile time
I'm using GCC; __FILE__ returns the current source file's entire path and name: /path/to/file.cpp. Is there a way to get just the file's name file.cpp (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings? I am using this in an error logging...
If you're using a make program, you should be able to munge the filename beforehand and pass it as a macro to gcc to be used in your program. For example, in your makefile, change the line: file.o: file.c gcc -c -o file.o src/file.c to: file.o: src/file.c gcc "-DMYFILE=\"`basename $<`\"" -c -o file.o src/file....
237,716
237,779
Is it possible to write a function like next_permutation but that only permutes r values, instead of n?
std::next_permutation (and std::prev_permutation) permute all values in the range [first, last) given for a total of n! permutations (assuming that all elements are unique). is it possible to write a function like this: template<class Iter> bool next_permutation(Iter first, Iter last, Iter choice_last); That permutes ...
To iterate over nPk permutations, I've used the for_each_permutation() algorithm presented in this old CUJ article before. It uses a nice algorithm from Knuth which rotates the elements in situ, leaving them in the original order at the end. Therefore, it meets your no external memory requirement. It also works for B...
237,804
7,906,630
What new capabilities do user-defined literals add to C++?
C++11 introduces user-defined literals which will allow the introduction of new literal syntax based on existing literals (int, hex, string, float) so that any type will be able to have a literal presentation. Examples: // imaginary numbers std::complex<long double> operator "" _i(long double d) // cooked form { r...
Here's a case where there is an advantage to using user-defined literals instead of a constructor call: #include <bitset> #include <iostream> template<char... Bits> struct checkbits { static const bool valid = false; }; template<char High, char... Bits> struct checkbits<High, Bits...> { static const...
237,899
246,936
How to draw a filled envelop like a cone on OpenGL (using GLUT)?
I am using freeglut for opengl rendering... I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied. Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)? or is there some other api that has an inbuilt...
On Edit3: The way I understand your question is that you want to have OpenGL draw borders and anything between them should be filled with colors. The idea you had was right, but a line strip is just that - a strip of lines, and it does not have any area. You can, however, have the lines connect to each other to define ...
237,978
238,032
What is std::safe_string?
An answer to one of my questions included the following line of code: label = std::safe_string(name); // label is a std::string The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of safe_string and neither, apparently, has google (nor could I find it in...
After searching google code search (I should have thought of this first...) I found this: //tools-cgi.cpp string safe_string (const char * s) { return (s != NULL) ? s : ""; } Which converts NULLs to zero length strings. Although this is not standard it's probably some sort of extension in a specific STL implementa...
238,008
238,023
Relative performance of std::vector vs. std::list vs. std::slist?
For a simple linked list in which random access to list elements is not a requirement, are there any significant advantages (performance or otherwise) to using std::list instead of std::vector? If backwards traversal is required, would it be more efficient to use std::slist and reverse() the list prior to iterating ov...
As usual the best answer to performance questions is to profile both implementations for your use case and see which is faster. In general if you have insertions into the data-structure (other than at the end) then vector may be slower, otherwise in most cases vector is expected to perform better than list if only for...
238,441
238,461
Can a C compiler rearrange stack variables?
I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had: void func() { char c; int i; short s; ... } We would reorder this to be: void func() { int i; ...
As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that. It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment. IIRC newer MSVC compilers use that freedo...
238,465
238,928
Static or dynamic linking the CRT, MFC, ATL, etc
Back in the 90s when I first started out with MFC I used to dynamically link my apps and shipped the relevant MFC DLLs. This caused me a few issues (DLL hell!) and I switched to statically linking instead - not just for MFC, but for the CRT and ATL. Other than larger EXE files, statically linking has never caused me ...
There are some downsides: Bigger exe size (esp if you ship multiple exe's) Problems using other DLL's which rely on or assume dynamic linking (eg: 3rd party DLL's which you cannot get as static libraries) Different c-runtimes between DLL's with independent static linkage (no cross-module allocate/deallocate) No automa...