Stack OverflowWhat is your most useful C/C++ utility?
[+114] [38] user17544
[2009-01-22 15:55:35]
[ c++ c code-snippets ]

It seems that every project has a "utility" module with various code snippets used throughout other files and which doesn't fit any particular pattern.

What utility classes, functions, and macros do you find most useful in your C/C++ projects? Please keep the entries small (under 100 lines) and give only one example per post.

(12) Should be community wiki. - tunnuz
(4) "Should be community wiki" - why? - Graeme Perrow
Agree with Graeme - dmityugov
(1) @Graeme because its argumentative and subjective - fortran
(6) It's a poll. It doesn't pose a specific question that people can answer, it just solicits opinion. - bmargulies
(9) Bah! Humbug! Mixing c and c++ in this context is not helpful. The best c++ answer simply won't work in a c context and some significant fraction of the best c answers are not needed in c++. - dmckee
(5) Avoid C/C++ projects, preferring those in one language or the other. C-with-classes projects are abhorrent. - Johnsyweb
(2) @fortran: "subjective and argumentative" is a reason to close, not a reason for CW. If the question is so subjective and argumentative that it is a problem, then vote to close, don't CW it. And if you're going to suggest that a question be CW'ed, think up some real arguments for it. - jalf
@jalf Is "So you don't get 10k rep?" a valid reason? - muntoo
@muntoo why would it be? - jalf
[+69] [2009-01-22 18:04:31] Josh Kelley

Get the number of elements in an array:

#define ITEMSOF(arr)    (sizeof(arr) / sizeof(0[arr]))

(0[arr] is identical to arr[0] for arrays but will intentionally fail if it's used against a C++ object that overloads operator[].)

The C++ version is less intuitive but more type-safe:

template<int n>
struct char_array_wrapper{
    char result[n];

template<typename T, int s>
char_array_wrapper<s> the_type_of_the_variable_is_not_an_array(const T (&array)[s]){

#define ITEMSOF(v) sizeof(the_type_of_the_variable_is_not_an_array(v).result)

Taken from this question [1] and Imperfect C++, by Matthew Wilson, section 14.3.


Microsoft now has _countof() in stdlib.h which is very similar. - Rob K
(22) Very nice! That's the first time I've ever seen the fact that x[y] === y[x] being useful! - j_random_hacker
Cool, didn't know about 0[arr]. +1 - Zach Langley
+1 from another Matthew Wilson reader. - Michael Burr
You should drop the parents: "sizeof arr" is enough; sizeof is not a function. - unwind
(23) If you're using C++, you shouldn't be using arrays at all. Use vectors. - Rocketmagnet
How come the macro works with char arr[10] but not with char *arr ? - Naseer
(7) @Naseer: The macro gives incorrect results work with char *arr because C and C++ don't know the size pointed to by a pointer. The template version intentionally fails to compile when used with char *arr for this reason. - Josh Kelley
@Josh - I thought in char arr[10] arr is also a pointer. How is the size known for that array ? Shouldn't the size in this case also be the size of the pointer ? - Naseer
(4) @Naseer: char arr[10] is in most respects a pointer, but sizeof (in the macro version) and certain template parameters (in the second version) still know that it's an array. Once you pass char arr[10] to a function taking char* as a parameter, the array decays into a pointer, and C/C++ can no longer distinguish the two or know the array's size. - Josh Kelley
Thank you - that was very informative ! - Naseer
(2) Very cool. Why not leave the function unimplemented to produce a link error if used outside sizeof? - Potatoswatter
(1) Not downvoting; but I have to ask: where would you ever use this? Every time I've had an array of known size, it's because the size is some easily available expression such as MAX_ITEMS. Arrays of unknown size (such as pointers to allocated memory) aren't amenable to your method and need an accompanying size variable. - Edmund
(1) Arrays in C++ are one of the only thing that can be initialized statically. I often find myself using them to initialize global maps. - BatchyX
(1) a) Use size_t, not int, to store sizes. b) A more elegant (IMHO) C++ solution is template <typename T, size_t N> size_t array_size(const T (&arr)[N]) { return N; } - Chris Lutz
This is really cool and informative, but I don't know when I'd ever need to use it. Actually, up until now I've never needed to use anything like it. As someone pointed out, it works on char arr[10], but you already know the size... so what's the point of using this? - leetNightshade
@Edmund, @leetNightshade - This lets you avoid repeating the size of the array. (Even if you're using an easily available expression like MAX_ITEMS, repeating it means that you might forget to update it if you change the array to use a different expression.) I also use ITEMSOF for code like static int static_data[] = {...}; for (size_t i = 0; i < ITEMSOF(static_data); i++) {...} - Josh Kelley
[+46] [2009-01-29 23:21:37] Ferruccio
#include <boost/...

(6) (+1) But I think the asker meant quick hacks of 100 lines of less. - Arrieta
(20) "#include <boost/..." is a quick hack of 100 lines or less. - tstenner
@tstenner: good point. - Arrieta
(16) no, it compiles to about 2GB, it is nor quick, nor small - ufotds
(5) Actually, most of Boost is header-only. It only compiles to what is actually used. If you recompile all of Boost every time you use it, you're doing something seriously wrong. - Ferruccio
(1) @Ferruccio Still... - muntoo
"Compiles to what is actually used"? Hardly. Everything from Boost.Container or Boost.Format to the smallest, trivialest utilities such as scoped_ptr and tribool somehow end up including the entire Lambda or MPL components when bcp'd. Not that I don't like Boost, but for this question... I'd downvote if I could. - Luis Machuca
@LuisMachuca: Yes, there are a lot of interdependencies in Boost which result in bcp dragging in a lot more components than you would expect. This has nothing to do with compiling. When you compile a program most modern C++ compilers are smart enough not instantiate templated code which is not actually used and linkers will not drag in object modules from libraries that are not actually referenced. This is more of a C++ feature than a Boost feature, although having well-designed modular code helps. - Ferruccio
[+42] [2009-01-22 17:21:27] cojocar

This is useful for debugging:

#ifdef NDEBUG
#define Dprintf(format, ...)
#define Dprintf(format, ...) \
    fprintf(stderr, "[%s]:%s:%d: " format, __FILE__, \
        __func__, __LINE__, ##__VA_ARGS__)

It uses variadic macros [1].

Edit: use NDEBUG which is standard.


(2) Why not check for NDEBUG, which is the standard macro used to determine whether we're in debug-mode or not? Also, it's bad practice to start names of user-defined macros with __... - Christoph
(3) Now I can upvote in good conscience: +1 - Christoph
(1) NDEBUG is only standard when running Visual Studio... - rubenvb
I'm pretty sure you can change your code to be fprintf(stderr, "["__FILE__"]:%s:%d: "format, __func__, __LINE__, ##__VA_ARGS__) and thus make the macro call slightly more efficient (you can do this because __FILE__ is a string literal provided by the preprocessor). - Trevor Boyd Smith
[+33] [2009-01-22 21:57:40] David Rodríguez - dribeas

My own implementation of make_string() as proposed here [1] by Arkadiy [2]:

class make_string
   template <typename T>
   make_string& operator<<( T const & datum )
      buffer_ << datum;
      return *this;
   operator std::string () const
      return buffer_.str();
   std::ostringstream buffer_;

// usage:
void f( std::string const & );
int main()
   std::string name = "David";
   f( make_string() << "Hello " << name << "!" );

j_random_hacker suggests adding a const char* conversion to the class above so that it can be used with legacy/C libraries that take null terminated strings. I have had not that much time to think about it, but I feel unease as adding that conversion would allow the following code to compile [edit: bad example, read answer to second comment]:

const char* str = make_string() << "Hello world"; // 1
// ...
std::cout << str << std::endl; // 2

To the compiler the code above is correct, but the usage is wrong as in line 1 the make_string() temporary is destroyed and the pointer is no longer valid.

Response to second comment:

Assume a simple implementation of const char* operator:

class make_string
// ...
   operator const char* () 
      return buffer_.str().c_str();

The str() creates a std::string object, whose scope is inside the operator const char_ method. The c_str() returns a pointer inside that std::string. By the time the caller receives the pointer, the std::string has gone out of scope and the memory has been released.

The other big difference with the code sample where the user requests the .c_str() from the std::string returned from the conversion operator is that the user is explicitly doing it and as such it appears in the code. If the conversion to null terminated string is implemented the user will have more trouble to detect where the error is.

void f( std::string const & );
void g( const char* );

f( make_string() << "Say hi" ); // works ok
g( make_string() << "Bye" ); // kills the application
g( (make_string() << "Hi again").c_str() ); // ok again std::string temporary is alive until g() returns

Now, try to explain what is so wrong with the second and not with the first or third lines one to the poor programmer whose application keeps dying. After all, she is just using a feature you are offering.

Another detail is that you could have a std::string member attribute and use it to force the lifespan of the std::string to be equivalent to that of the make_string object.

Anyway, I recomend everyone to read Modern C++ Design from Andrei Alexandrescu, and specially the chapter on smart pointers. The discussion of what features to implement is quite interesting. It changed my set of mind from 'implement as many features as you can' to a more conservative 'implement what is required, weight advantages and disadvantages of all other features'


Very nice dribeas. Can I suggest adding an operator const char*() conversion as well, since many libraries still take C-style strings? They won't conflict. I also found that MSVC++9 needs a 2nd operator<<() template that binds to non-const ref for handling some manipulators. - j_random_hacker
Well, the compiler also won't complain if you try to assign (make_string() << ...).c_str() to your str variable, which is the same thing IMHO -- in both cases you have to accept that there are parts of a contract that can't be enforced by the language. But it's up to you of course. - j_random_hacker
I was about to mention that you could add a std::string member variable to solve the problem of the temporary in operator const char*(), when I saw you had done so yourself! So I think this removes any "danger." But I agree that c_str() is a more explicit (e.g. greppable) way to indicate danger. - j_random_hacker
You can fix the char const* storage problem by treating the string maker as a global resource. But it's not threadsafe and it still lets you do char const* hi=string_maker << "Hello world"; char const* bye=string_maker << "Bye"; cout << hi;. Guess its best to just say no. - community_owned
Why not use boost::lexical_cast? - Matt Fichman
your implementation currently doesnt support stream manipulators like std::endl, why not add it ? - smerlin
@smerlin: The main reason is that I have never actually needed it, over one year of usage. In your particular case you can add '\n' (std::flush will have no effect in a string stream). I have used some other manipulators (std::hex and the like) to produce formatted output. It is just the 'function-style' manipulators that are not accepted. - David Rodríguez - dribeas
@David - Why not inherit from std::ostringstream instead of forwarding operator<< to a private member? That way, all manipulators work, and all other stream functions work the way users expect them to work, but you can overload the casting operators to work the way you want them to. Also, for a (non-const) char * overload, you could use strdup (or something similar: char *stringdup(const std::string &s) { char *c = new char[s.size()]; memcpy(c,; return c; }). - Chris Lutz
@Chris Lutz: Just by principle. Inheritance is designed for code reuse, but for elder code to be reused with your new class, not the other way around. This is a clear example where the code is not designed to be a drop in replacement for an ostream. It could use private inheritance (implemented in terms of), but you would need to add a using declaration... I guess that would be more concise than the code above, just did not think about it. - David Rodríguez - dribeas
On the use of strdup, I don't think that is a good idea. The code is designed to be an in-place string builder. Adding that method would take that functionality away: the user would have to store the returned pointer in a variable and delete[] it afterwards. The purpose of the class, when it was designed, was to be used as: foo( make_string() << "Hello, " << name ); the use is simple and the greatness of it is its simplicity of use. - David Rodríguez - dribeas
@David - Yeah, I remembered that after I wrote it. You could write the string data into a static buffer and return that, but that wouldn't be thread-safe. I'm at a loss to figure out a safe way to do this, other than adding operator char * to the string class. (Which is, of course, a bad idea.) - Chris Lutz
Very nice, will add to my util.h! - Viktor Sehr
Brilliant! I will definitely start using this! - templatetypedef
[+29] [2009-01-22 16:00:07] Evan Teran

I use these pretty often, they are string trim functions.

inline std::string &rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
    return s;

inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;

inline std::string &trim(std::string &s) {
    return ltrim(rtrim(s));

Do they modify the input string and return it? Why? - 1800 INFORMATION
(1) yes and yes, the reason why is so you can write things like: trim(s).c_str(); and all that good stuff. You could easily alter then to make a copy (just remove the &'s from the code and you get a copy of the string instead). - Evan Teran
(11) gosh, c++ scares me :-) - Eli Bendersky
(5) Personally, I'd make the parameters const& and return a copy. I know there'd be complaints about inefficiency, but I think that otherwise you'd end up with bugs because someone was surprised that the string object he passed in was modified. - Michael Burr
(2) Good point, in the end the documentation should make it abundantly clear that the function modifies its input. - Evan Teran
(2) You should also make the predicate a parameter so you can trim things other than spaces. - jmucchiello
(1) an optional parameter defaulting to spaces - advs89
Speaking of inefficiency, my rtrim function runs a lot faster than yours. After a benchmark of 1,000,000 tests, yours averaged about 27 microseconds. My function averaged under 5 microseconds. So, your functions are beautiful in their simplicity, but after testing, I don't see why I would want to use those functions; granted, I have to benchmark your other two functions first, but I think the first result is rather conclusive as to the standard libraries usefulness in this case. What say you, is there a reason to stand behind your implementation? - leetNightshade
@leetNightshade: can you post a pastebin link to your implementation? And what compiler with which options did you use? Only after I have more information can I make a fair comparison. - Evan Teran
@Evan Sure, I've never used it before, and I have some work to do, so please give me some time to get back to you. And I hope you didn't think my first post was attacking your implementation, sorry if it seemed that way. I just got really excited when I saw yours, then decided to test it out. - leetNightshade
@Evan Okay, after doing fairly thorough research of my own, I can say why yours is slower. One: don't use iterators, they're slower than manual iteration using indices from my tests. Two: yours has multiple function calls, not1, a function pointer call which will have to do a lookup, and isspace. So, find_f using iterators, and erasing using iterators, is slow. Your way is brute force, and doesn't take an algorithmic approach. - leetNightshade
You can find a faster implementation here:… If you're still curious, my implementation appears to even still beat out the implementation I mention. - leetNightshade
@Evan Benchmarks were in debug & no optimizations. W/ optimizations in release yours runs smoother. Long empty string: Yours: 0.231862 Mine:0.207122 in ms. On a somewhat long string with a bunch of spaces: Yours: 0.442006 Mine:0.424327 in ms. Again on larger strings: Yours: 1.2955 Mine: 1.2686 and Yours: 1.27273 Mine: 1.25933 in ms. So, seems very negligible with enhancements turned on and in release mode; and thus, maybe a case where it doesn't really matter that much then? In debug in one example, yours: > 25 ms. My improved version: 3.65ms. Chat topic? - leetNightshade
(2) @leetNightshade: thanks for the follow up, always keep in mind that benchmarks in debug builds are meaningless, only when optimizations are enabled does it makes sense to compare speed. - Evan Teran
@Evan I thought I should direct you to this find: link[link] If you absolutely want to have short and simple trim functions, you should use those; they're as fast as you can get, I think, using straight up std string stuff, and it has more features as you can check for more than just a standard space. - leetNightshade
[+24] [2009-01-23 17:32:23] Daniel Earwicker

When calling a Win32 API that wants to write into a string buffer, it would be nice to be able to pass it a std::string or std::wstring directly.

Here's a simple way to enable that:

template <class C>
class _StringBuffer
    typename std::basic_string<C> &m_str;
    typename std::vector<C> m_buffer;

    _StringBuffer(std::basic_string<C> &str, size_t nSize)
        : m_str(str), m_buffer(nSize + 1) { get()[nSize] = (C)0; }

        { commit(); }

    C *get()
        { return &(m_buffer[0]); }

    operator C *()
        { return get(); }

    void commit()
        if (m_buffer.size() != 0)
            size_t l = std::char_traits<C>::length(get());

            m_str.assign(get(), l);


    void abort()
        { m_buffer.resize(0); }

template <class C>
inline _StringBuffer<C> StringBuffer(typename std::basic_string<C> &str, size_t nSize)
    { return _StringBuffer<C>(str, nSize); }

So now I can say:

std::string str;
GetWindowsDirectory(StringBuffer(str, MAX_PATH), MAX_PATH);

StringBuffer gives a writeable buffer to the API, and then on destruction it copies it into str.

(2) This is extremely cool. This is going in my utility library, along with makestring(). - j_random_hacker
(13) In C++ _StringBuffer is a reserved identifier, shouldn't be used for your own class template. - robson3.14
[+20] [2009-11-02 22:48:35] epatel

A simple hexdumpis often good to have...

#include <ctype.h>
#include <stdio.h>

void hexdump(void *ptr, int buflen) {
  unsigned char *buf = (unsigned char*)ptr;
  int i, j;
  for (i=0; i<buflen; i+=16) {
    printf("%06x: ", i);
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%02x ", buf[i+j]);
        printf("   ");
    printf(" ");
    for (j=0; j<16; j++) 
      if (i+j < buflen)
        printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.');

[+20] [2009-11-11 13:45:41] S.C. Madsen

This is Evil, I know, but it has come in handy:

#define private public
 #include "OhSoEncapsulatedLittleObject.hpp" // Let me at'em!
#undef private

(6) +1; also #define protected public and #define class struct - David X
(2) Absolutely! I use this from time to time when writing tests for class libaries, where I want to check post-conditions on private members on the classes. - S.C. Madsen
(1) You left out the #undefs - jmucchiello
I added the #undef - ufotds
(1) This will not necessarily give you access to member functions. Some compilers will mangle public/private/protected names differently. Of course, you still have access to data. - Ferruccio
@Ferruccio: I disagree. If mangling is different wouldn't it be problematic to use the object in the first place? - S.C. Madsen
The name of the object itself and data members are not mangled. Member function names are mangled (both to support overloading and provide typesafe linkage across compilation units). Some compilers will take into account a function's visibility when generating the mangled name. I ran into this problem when I tried to use this trick in a unit test. It would compile, but the linker could no longer resolve member functions. (I've since come to realize that unit tests should only use the public interface of an object) - Ferruccio
[+19] [2009-01-22 15:57:43] Cody Brocious
#define ever ;;

Example use:

for(ever) { ... }

(14) Nice trick... But I'm not sure if people won't find while(true) to be more explicit ? - Wookai
while(true) will produce a warning on some compilers because the condition is a constant. - Evan Teran
(2) It wasn't meant as a serious suggestion by any means. - Cody Brocious
(12) lol, people like it. Though, I'd prefer: #define forever for(;;) that way you can just write: forever { ... } - Evan Teran
(24) for(;"ever";) - community_owned
(6) what(ever) {...} - Baltimark
(1) @Baltimark: no problem: #define what(IGNORE) for(;;) - Christoph
+1 funny Nicely done. - Rodyland
(2) It is funny, but not really useful. - Ismael
(1) Nice one lraimbilanja. - j_random_hacker
(1) How about: #define ty int n = 0; n < 40; n++ - Daniel Earwicker
(2) @Earwicker: or #define ty_two ;;) puts("DON'T PANIC" so that you can do for(ty_two); - Christoph
(18) Sorry, but I don't like this. ;; is shorter to type than "ever", and who doesn't recognize this construct? "ever", though, must make you think once more. while (1) is the best here, IMHO - Eli Bendersky
Haha what a funny one. I'd do while(true) though - Ray Hidayat
(41) -1, that's horrible - Patrick
(3) Macros are generally bad. If somebody names something "ever", that'll be a hard-to-track-down bug. - David Thornley
hate it. Prefer while (1) - jmucchiello
@Iraimbilanja: That's much nicer! - Johnsyweb
Prefer #define ever (;;). Everything is cleaner without parenthesis. - Chris Lutz
(7) It's funny to see people taking this seriously... - peoro
(1) @peoro It's funny to see people believe Cody wasn't serious. - muntoo
[+14] [2009-01-22 17:56:17] community_owned

Fastest vs Easiest way to read a full file into a std::string.

string fast(char const* filename) {
    ifstream file(filename, ios::ate);
    int size = file.tellg();
    file.seekg(0, ios::beg);
    scoped_array<char> buffer(new char[size]);, size);
    return buffer.get();

string easy(char const* filename) {
    ostringstream ss;
    ss << ifstream(filename).rdbuf();
    return ss.str();

Edit by Arrieta:

For the benefit of the community, and as a respectful extension to your clever post, I point out to code provided by Tyler McHenry [1]:

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),

Interesting, but is there no way to avoid the string copy? - StackedCrooked
(2) @StackedCrooked: No extra copy will be created here. Google for Return Value Optimization. - missingfaktor
What about not being able to access the file etc. How would you determine what caused access to fail? I'm contrasting with fopen. - bruce.banner
[+13] [2009-01-22 16:01:22] Evan Teran

I also use this lexical cast in the few cases where linking to boost is undesirable, the only problem is that it does no error checking (but that can be easily added by checking the stream state before returning.

template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
    T2 out;
    std::stringstream ss;
    ss << in;
    ss >> out;
    return out;

most of boost is in headers, you shouldn't have to link to anything in boost to get boost::lexical_cast<> - littlenag
fair enough, but every now and then I'm on a system where boost isn't immediately available. - Evan Teran
(5) This is true - try to convince your management and/or team to bring in an open source lib (even if it's all headers) that they are unfamiliar with. It tends to elicit much fear. - Michael Burr
(1) @Michael Burr: precisely. There are too many answers to very trivial question (e.g. trim) that say "use boost"! - lttlrck
(1) Also, I hope boost's implementation of this would check whether ss >> out actually succeeds (and reads the whole of what's in the buffer of ss), while yours fails to do so. If T2 is a POD, this will actually return _a random result. Makes for hours of debugging fun. - sbi
[+10] [2009-01-22 16:02:32] j_random_hacker

The following code implements a couple of list_sequence() template functions that I find helpful for debugging. Basically, you can call:

cout << list_sequence(myVector, ", ") << "\n";

to list any standard container (such as vector<T> or list<T>) to stdout, or more generally,

cout << list_sequence(begin, end, ", ") << "\n";

to list an arbitrary iterator range between iterators begin and end.



#include <iostream>
#include <string>
#include <iterator>

template<typename X> class sequence_lister;     // Forward reference

template<typename InIter>
inline std::ostream& operator<<(std::ostream& os, sequence_lister<InIter> const& sl) {
//  copy(sl._first, sl._last, ostream_iterator<typename InIter::value_type>(os, sl._delim));
    for (InIter i = sl._first; i != sl._last; ++i) {
        if (i != sl._first) {
            os << sl._delim;

        os << *i;

    return os;

template<typename InIter>
class sequence_lister {
    sequence_lister(InIter first, InIter last, char const* delim = "") :

    // Also allow construction from any container supporting begin() and end()
    template<typename Cont>
    sequence_lister(Cont& cont, char const* delim = "") :

    sequence_lister(sequence_lister const& x) :

    sequence_lister& operator=(sequence_lister const& x) {
        _first = x._first;
        _last = x._last;
        _delim = x._delim;

    friend std::ostream& operator<< <>(std::ostream& os, sequence_lister<InIter> const& sl);

    InIter _first, _last;
    char const* _delim;

template<typename InIter>
inline sequence_lister<InIter> list_sequence(InIter first, InIter last, char const* delim = "") {
    return sequence_lister<InIter>(first, last, delim);

template<typename Cont>
inline sequence_lister<typename Cont::const_iterator> list_sequence(Cont& cont, char const* delim = "") {
    return sequence_lister<typename Cont::const_iterator>(cont, delim);

Thanks Evan :) It's the only utility-type thing I've written that I now can't live without... - j_random_hacker
Why didn't you use the copy algorithm that you have commented out? - Harper Shelby
(1) cause it will put a delimiter after the last item perhaps? - Evan Teran
Shouldn't delim be const char*? - jmucchiello
@jmucchiello: Good idea, done. (No functional difference as string literals can be used fine with plain char * since C++ gives them a special conversion for C-compatibility reasons, still it helps document the intention). Ideally I would change the Cont& types to Cont const& too, but I can't be 100% sure it won't break something... If anyone can spare the time to test that, by all means change it. - j_random_hacker
[+9] [2009-01-22 16:15:35] plinth

CCASSERT - force a compile-time assert

#define CCASSERT(predicate) _x_CCASSERT_LINE(predicate, __LINE__)
#define _x_CCASSERT_LINE(predicate, line) typedef char constraint_violated_on_line_##line[2*((predicate)!=0)-1];

Typical usage:


In which compiler is this supposed to work? The LINE macro won't be expanded, because it will be joined via ## before processing! - Christoph
(1) compile time asserts are very useful, but currently awkward to make work on all compilers. The new C standard is defining static asserts though. More details here: - pixelbeat
(8) Consider using Boost's static assert instead. - Seth Johnson
[+8] [2009-11-02 22:39:52] fnieto - Fernando Nieto

This class to trace the time spent on the execution of the expressions in the scope:

#include <iostream>
#include <sys/time.h>

class trace_elapsed_time
   explicit trace_elapsed_time(const std::string& msg, std::ostream& out = std::cout)
   : msg_(msg), out_(out)
      gettimeofday(&init_time_, 0);
      timeval now;
      gettimeofday(&now, 0);
      double elapsed_seconds = now.tv_sec - init_time_.tv_sec + 
                               now.tv_usec/1e6 - init_time_.tv_usec/1e6;
      std::string::size_type pos = msg_.find("%t");
      out_ << msg_.substr(0, pos) << elapsed_seconds 
           << msg_.substr(pos+2, msg_.size()-1) << std::flush;
   std::string msg_;
   std::ostream& out_;
   timeval init_time_;

Example of use:

int main()
   trace_elapsed_time t("Elapsed time: %ts.\n");
   usleep(1.005 * 1e6);


Elapsed time: 1.00509s.

Note: You can make this code portable using boost time functions and linking against the corresponding library.
Note2: I recently found a very similar multiplatform utility in boost: boost::progress_timer [1]


[+7] [2009-01-22 18:14:25] Igor Oks

Convert any streamable variable to string:

#include <string>
#include <sstream>
#include <iostream>

template<class Source>
string ToString(const Source& Value)
    std::ostringstream oss;
    oss << Value;
    return ss.str();

See also Evan's lexical_cast [1] answer.


you should take a look at my "lexical_cast" answer above, it lets you go both to and from a string. - Evan Teran
you are right. though this one is doing it without the second type (but 1 direction only :-]) - Igor Oks
In most cases for my answer, you can omit the second type like this: int x = lexical_cast<int>("12345"); because the compiler can figure out the type of the parameter. - Evan Teran
is the '\0' really required? And what would be the consequence of simply returning ss.str()? - lttlrck
(2) and why use strstream rather than stringstream? - lttlrck
@hapalibashi: because this snippet is quite old. Feel free to edit it. - Igor Oks
@Igor: Done so. - sbi
[+7] [2009-01-22 16:03:23] Arkadiy

I can't post the code - it belongs to my employer, after all - but the thing I found most useful is

int number = 2;
sendMessage(makestring() << "This message has a " << number << " in it.");

IOW, in-place stream formatting. Implementation is left as an exercise to the reader (or maybe boost hast it :) ).

(1) Very nice! Lemme guess: makestring() produces an object of some type derived from ostream, which has an implicit conversion to char*. - j_random_hacker
Actually... Wouldn't that mean that the temporary returned by makestring() actually gets destructed before sendMessage() gets called? Do you use a static or preallocated char buffer to avoid that? - j_random_hacker
(1) it could always have cast to std::string overloaded... then no scope issues. - Evan Teran
(1) To j_random_hacker: "Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created." (12.2/3) - community_owned
(1) makestring is a class, and it has a templated operator << to transfer the call to the ostringstream it owns, plus another one for manipulators. - Arkadiy
Really nice idea :) Since your code is not free, I will post my own implementation as an anwer. - David Rodríguez - dribeas
Thanks lraimbilanja. I realise now: everything works provided the temporary is created at the top lexical level. It's only if a function called by the top level expression creates a temporary and returns its address or the address of one of its members that the temporary gets destroyed too early. - j_random_hacker
Google uses that for their logging class. So your employer is.... :) - Andrei Taranchenko
j_random_hacker: Yep. - community_owned
Andrei: I wish... - Arkadiy
[+7] [2009-01-22 16:03:27] Evan Teran

finally, my last answer is a string split function which splits on a single character delimiter of your choice.

inline void split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {

We have s.find_first_of(delim) instead of getline. Which one works faster? - Igor Oks
(5) Does it matter? How often is a string split the time limiting step in your application? - Martin Beckett
[+3] [2009-01-22 16:03:45] Christoph

Reading in a whole file, ISO-C:

size_t fget_contents(char ** buffer, const char * name, _Bool * error)
    FILE * file = NULL;
    char * temp = NULL;
    size_t read = 0;

    // assume failure by default
    *buffer = NULL;
    if(error) *error = 1;

    	file = fopen(name, "rb");
    	if(!file) break;

    	long size = fsize(file);
    	if(size < 0) break;

    	// no io error till now
    	if(error) *error = 0;

    	temp = malloc((size_t)size + 1);
    	if(!temp) break;

    	read = fread(temp, 1, (size_t)size, file);
    	temp[read] = 0;

    	// `temp` is needed because realloc may fail here!
    	*buffer = realloc(temp, read + 1);
    	if(!*buffer) break;

    	temp = NULL;
    	if(error) *error = (size != (long)read);

    // cleanup
    if(file) fclose(file);
    if(temp) free(temp);

    return read;

why do { ... } while (0) ??? - Marcin Koziuk
@marcin: to be able to skip code without using return - I could have used a goto instead, but there would have been only one label; this was the nicest way I could think of to properly handle all possible error conditions and still close file... - Christoph
(9) A neat demonstration of how goto is sometimes better! Would be much clearer in this case. - Daniel Earwicker
(1) But when programming C, you get used to the do...while(0) abuse: it's pretty common when defining multi-statement macros... - Christoph
Also, I believe it's a common pattern in the one-exit-point-per-function camp... - Christoph
sorry for replying to this while it's sooo old, but shouldn't that whole do { ... } while(0) construct just be replaced with another function call? Then there'd be less questionable code, you could use returns instead of breaks, and the function size would be reduced. - Carson Myers
@Carson: see if you can refactor the code and make it more clear while still handling all error cases the same way; I couldn't do it, but perhaps you can - Christoph
I'm confused. If the fread doesn't read the whole file shouldn't you loop and do another fread for the rest of the file? That's what I usually do. - jmucchiello
The do...while(0) "abuse" is interesting. Since I am C++-only I like learning C-idioms - because I have to work with C pretty soon... - vobject
This is not ISO C due to the unknown fsize() function. - Jens
can replace fsize by fseek to end + ftell - EvilTeach
[+3] [2009-01-24 13:53:03] user17544

Here is one of mines that I didn't saw it here (reproduced without a compiler, might not be exact):

class Monitor
    	Monitor() { InitializeCriticalSection(&m_cs); }
    	~Monitor() { DeleteCriticalSection(&m_cs); }
    	void Lock() { EnterCriticalSection(&m_cs); }
    	void Unlock() { LeaveCriticalSection(&m_cs); }

class Locker
    	Monitor& m_monitor;
    	Locker(Monitor& monitor) : m_monitor(monitor) { m_monitor.Lock(); }
    	~Locker() { m_monitor.Unlock(); }		

#define SCOPE_LOCK(monitor) Locker locker##__LINE__(monitor)

And it can be used like this:

    class X : public Monitor {};
    X x;

void use_x()

    //use x
    //on scope exit, x is unlocked

Nice use of RAII. - j_random_hacker
(4) Two notes - CRITICAL_SECTION is win32, so this isn't cross-platform. Also, the Boost threading library can do pretty much the same thing with boost::lock_guard - Branan
Hi, thanks for the comment. Cross-platform-ness is not an issue for me. And the sample can be easily adapted for other platforms. Didn't knew about boost::lock_guard. I'll look into it. - user17544
check out the MFC CCriticalSection and CSingleLock equivalents. - gbjbaanb
(4) Shouldn't these classes be made non-copyable? - StackedCrooked
[+3] [2009-01-23 03:45:37] HUAGHAGUAH
#include <queue.h>

Never write buggy linked list implementations again. [1]

#include <tree.h>

Never write buggy tree implementations again. [2]

Fully portable and legal for close-source commercial products.


(4) Um, tree.h is not portable it's BSD. Whereas queue is portable but not in the <queue.h> form (which is either BSD or old C++), rather in the <queue> form (which is standard C++). - community_owned
(2) Sometimes it would be useful to have a tree type, but the Standard C++ Library has linked lists and queues pretty well covered, as well as sets and maps for doing what most people want to use trees to do (they're trees underneath). - j_random_hacker
[+3] [2010-09-11 17:47:39] Maister

With C++0x, I have a neat little string builder that I like to pass as arguments to exceptions, etc.

#include <sstream>
#include <iostream>
using namespace std;

void mksubstr(const ostringstream& stream)

template<class T, class... Args>
void mksubstr(ostringstream& stream, const T& first, const Args&... rest)
   stream << first;
   mksubstr(stream, rest...);

template<class T, class... Args>
string mkstring(const T& first, const Args&... rest)
   ostringstream buf;
   buf << first;
   mksubstr(buf, rest...);
   return buf.str();

int main()
   int x = 1, y = 10;
   cout << mkstring("Foo: (", x, ", ", y, ")") << endl;

I would call it join() or similar, but this is quite handy. - Jon Purdy
[+2] [2010-02-04 23:29:38] pm100

typedef boost::shared_ptr<Foo> FooPtr;

systematically getting team to use shared_ptr and using it in a common way

[+2] [2009-01-22 16:14:02] Laserallan

I've found myself writing the equivalent if the function too many times (sorry for typos):

template<class __p> static void deleteVector(std::vector<__p*>& target) {
    for(std::vector<__p*>::iterator i = target.begin(); i != target.end(); ++i) {
        delete *i;

Might be the perfect example of where to use some kind of smart pointer, but it's not all projects that uses that kind of coolness.

(1) I have something like this, it's very useful! I instead only declare a DeletePointer functor and do it this way: for_each(v.begin(), v.end(), DeletePointer()); - Ray Hidayat
(1) Doubt your code is exception safe. You should use a container of smart pointers or a pointer container. (And __p is a reserved identifier.) - GManNickG
@Gman: any code that throws exceptions in destructors is insane anyway. So I think that it is ok exception wise. - Evan Teran
(2) @Evan: I mean std::vector<int*> v = /* populate */; do_stuff(v); deleteVector(v);. If do_stuff throws, game over. This follows the same old principle: if you're ever in a position to manually free something, you've done it wrong. Wrap it up. - GManNickG
@GMan: gotcha, fair enough. - Evan Teran
[+2] [2010-05-20 22:27:08] James Morris

Thought there were far too few answers that can be used with C.

#include <getopt.h>

#define HAS_ARG 1

static struct option longopts[] = {
    {   "option-a",          HAS_ARG,    0,  'a' },
    {   "option-b",          HAS_ARG,    0,  'b' },
    {   0,                   0,          0,   0  }

void show_usage(char* argvzero)
    printf("%s usage\n", argvzero); /* more follows */

int process_args(int argc, char** argv)
    /* do stuff to process the commandline options using <getopt.h> API */

[+1] [2009-01-22 18:20:31] Graeme Perrow

I use this for adding debug logging that (a) disappears in non-debug code and (b) supports variable arguments. Similar to cojocar's answer [1] but doesn't use variadic macros (which aren't supported by all compilers):

extern int MyDebugLogRoutine( const char *fmt, ... );
#ifdef NDEBUG
#define Dprintf(x)
#define Dprintf(x) MyDebugLogRoutine x

// need double parens
Dprintf(( "Format string that supports %s\n", "arguments" ));

Why isn't the #else: #define Dprintf(x) MyDebugLogRoutine ( x )? - jmucchiello
@jmucchiello: The first set of double parens gets "absorbed" by the macro, so the macro expands to MyDebugLogRoutine ( "Format string that supports %s\n", "arguments" );. - Graeme Perrow
Right, so if you did the #define with parens you wouldn't have that problem. This is the normal idiom: #define func(x) hiddenfunc(x) - jmucchiello
If I wanted to call Dprintf once with two parameters Dprintf('%s', 'abc') and once with three Dprintf('%s %s', 'abc', 'def'), the compiler would complain that Dprintf only takes one parameter. I need to double the parens so that I really am calling Dprintf with only one parameter. Perhaps some compilers allow this - the ones I use do not. - Graeme Perrow
You could write the macro with variadic arguments: #define Dprintf(x, ...) MyDebugLogRoutine(x, ##__VA_ARGS__) This way you don't need the double parentheses. - Shahbaz
@Shahbaz - As I said in my answer and comment, I didn't use variadic macros since they weren't supported by all the compilers that we used at the time. - Graeme Perrow
[+1] [2009-01-22 21:52:33] David Rodríguez - dribeas

Stringify defined as ToString here [1]

Parse defined simetrically:

template <typename T>
void parse( std::string const & str, T & data )
   std::istringstream st(str);
   st >> data;

STL iterator printout (dump to stream) (maybe similar in functionality to sequence_lister here [2]?):

// dump to stream 
class stream_dumper { 
   explicit stream_dumper( std::ostream& o, std::string const & sep = "" )
      : out_( o ), sep_( sep ), first_(true) {}    
   template <typename T>
   void operator()( T const & t )   {
      if ( first_ ) first_ = false;
      else out_ << sep_;

      out_ << t;    
   std::ostream& out_;
   std::string sep_;
   bool first_; 

// usage 
void f( std::vector<int> const & v, std::list<double> const & l ) {
   // dump the vertor separating with commas
   std::for_each( v.begin(), v.end(), stream_dumper( std::cout, ", ") );
   // dump the list separating with |
   std::for_each( l.begin(), l.end(), stream_dumper( std::cerr, "|" ) ); 

I used to have a similar solution to free memory held in containers through pointers, but that code is now obsolete with the use of boost::shared_ptr


For stringify/parse, check out boost's lexical_cast. - Daniel Earwicker
[+1] [2009-10-21 17:27:31] Mandrake
dprintf (char *format, ...)

#ifdef DEBUG


    	int rete;
    	va_list args;
    	static char buffer[1000000];//yes 1000000, I need this to debug
    	int ret;
    	va_start (args, format);
    	ret = vsprintf (buffer, format, args);
    	OutputDebugString (buffer);
    	printf (buffer);




(1) not doing much multithreaded work ? static is really not gonna work then - Bahbar
yes , I agree , sorry - Mandrake
[0] [2009-10-23 21:19:18] CC.

Working with VTK the following defs were useful:

#define EPSILON 0.00001

// ex. if ( FLOAT_EQ(d,1) ) ...
#define FLOAT_EQ(x,y) ( ((x-EPSILON) < y) && (y < (x+EPSILON)) )

// Fit "val" to be between e1 and e2, just like vtkMath::ClampValue
#define FLOAT_CLAMP(val, e1, e2) \
 if ( (val)<(e1) ) (val)=(e1); \
 if ( (val)>(e2) ) (val)=(e2); \

// 3D coordinate    
#define FLOAT_COPY(src, dst) \
 (dst)[0]=(src)[0]; \
 (dst)[1]=(src)[1]; \
 (dst)[2]=(src)[2]; \

#define FLOAT_FILL(v, value) \
 (v)[0]= (v)[1]= (v)[2]=(value); \

#define FLOAT_SET(v, x,y,z) \
 (v)[0]=(x); \
 (v)[1]=(y); \
 (v)[2]=(z); \

Of course "const double epsilon = 0.00001;" and similar can be used instead of define. There's a CodeGuru article with explanations

ya might consider using the epsilon values from math.h - EvilTeach
[0] [2009-01-23 10:40:37] Remo.D

What a coincidence! I'm just collecting mines here [1]. Everything is in C and is meant to be absolutely minimal, with as few dependencies as possible. At the moment I have:

  • Debugging macros (similar to what cojocar already showed)
  • Logging macros (similar to log4j but only logs to file)
  • Unit testing framework (produces a TAP compliant result)
  • Variable length strings (that can be intermixed with C strings)
  • Associative arrays (where keys and values can be strings, integers, pointers or other tables)
  • Pattern matching (different from regular expressions). Used with the variable length strings it offers search and replace functionalities similar to what many scripting languages have.

It's a work in progress and I add code, examples and documentation when time permits. The code is for my own projects but is released under BSD should someone else find it useful.


tl;dr and 6 more - Matt Joiner
[0] [2010-11-22 11:35:15] kylef

This is useful when working with sockets, it allows you to send a format string. The downside to this is that this function is that the output string limited to 8192. You could use asprintf, but not all operating systems support this.

int sendf(int sock, char *format, ...) {
    va_list args;
    char buf[8192];

    va_start(args, format);
    vsnprintf(buf, 8192, format, args);

    return send(sock, buf, strlen(buf), 0);

[0] [2011-07-31 16:35:50] Viktor Sehr

My parallel-for\foreach macro; simple cut-and-paste from my parallel_for.h Also available at:


    - Easy to use macro for making for/foreach loops run in parallel
    - Uses boost::thread
    - Contact: viktor.sehr [at]

  Examples of usage:

    Traditional for-loop
    for(size_t i = 0; i < container.size(); ++i) { container[i] = sin(container[i]); } 
    pfor(i, 0,  container.size(), { container[i] = sin(container[i]); });

    BOOST_FOREACH or C++0x foreach loop
        BOOST_FOREACH(auto& val, container) { val = sin(val); } 
        for(auto& val: container) { val = sin(val); }
    pforeach(auto& val, container, { val = sin(val); });

    Traditional for-loop with specified range
    for(int i = -1000; i < 1000; ++i){...} 
    pfor(i, -1000,  1000, {...});


#pragma once

#include <vector>
#include <boost/thread.hpp>
#include <type_traits>

// Default configuration
#define PFOR_NUM_KERNELS (::parallel_for::num_kernels_)
#define PFOR_THREAD_TYPE ::boost::thread

// Parallelism disabled?

namespace parallel_for {
inline unsigned get_num_kernels() {
    auto val = boost::thread::hardware_concurrency();
    return val == 0 ? 1 : val;
static unsigned num_kernels_ = get_num_kernels();

  typedef decltype(STOP_N) index_type_pfor; \
  auto func = [&](index_type_pfor start_pfor, index_type_pfor stop_pfor) { \
    for (index_type_pfor IDX = start_pfor; IDX < stop_pfor; ++IDX) { \
      SCOPE; \
    } \
  }; \
  index_type_pfor num_threads_pfor = static_cast<index_type_pfor>( PFOR_NUM_KERNELS ); \
  index_type_pfor start_pfor = static_cast <index_type_pfor> (START_N); \
  index_type_pfor stop_pfor = static_cast <index_type_pfor> (STOP_N); \
  index_type_pfor distance_pfor = stop_pfor - start_pfor; \
  threads_pfor.reserve(num_threads_pfor); \
  for (index_type_pfor i = 0; i < num_threads_pfor; ++i) { \
    index_type_pfor start = (distance_pfor/num_threads_pfor) * i; \
    index_type_pfor stop = (i + 1 == num_threads_pfor ? distance_pfor : (distance_pfor/num_threads_pfor) * (i+1)); \
    start += start_pfor; \
    stop += start_pfor; \
    threads_pfor.emplace_back( PFOR_THREAD_TYPE(func, start, stop) ); \
  } \
  for(auto it = threads_pfor.begin(), it_end = threads_pfor.end(); it != it_end; ++it) { \
      it->join(); \
  } \

{ \
  auto& container_pfor = CONTAINER; \
  typedef decltype(container_pfor.begin()) iterator_type_pfor; \
  auto func_pfor = [&](iterator_type_pfor start_pfor, iterator_type_pfor stop_pfor) { \
    for (; start_pfor != stop_pfor; ++start_pfor) { \
      VAR = (*start_pfor); \
      SCOPE; \
    } \
  }; \
  auto num_threads_pfor = PFOR_NUM_KERNELS; \
  threads_pfor.reserve(num_threads_pfor); \
  size_t step_pfor = container_pfor.size() / num_threads_pfor; \
  iterator_type_pfor start_pfor = container_pfor.begin(); \
  for (size_t i_pfor = 1; i_pfor < num_threads_pfor; ++i_pfor) { /* i starts at 1 as we only loop num_threads-1 times */ \
    iterator_type_pfor stop_pfor = start_pfor; \
    std::advance(stop_pfor, step_pfor); \
    threads_pfor.emplace_back( PFOR_THREAD_TYPE(func_pfor, start_pfor, stop_pfor) ); \
    start_pfor = stop_pfor; \
  } \
  threads_pfor.emplace_back( PFOR_THREAD_TYPE(func_pfor, start_pfor, container_pfor.end()) ); \
  for(auto it = threads_pfor.begin(), it_end = threads_pfor.end(); it != it_end; ++it) { \
      it->join(); \
  } \

// SINGLE_FOR (for debugging\profiling)
{ \
  typedef decltype(STOP_N) index_type_pfor; \
  index_type_pfor start_pfor = START_N; \
  index_type_pfor stop_pfor = STOP_N; \
    for (index_type_pfor IDX = start_pfor; IDX != STOP_PFOR; ++IDX) { \
        SCOPE; \
    } \

// SINGLE_FOREACH (for debugging\profiling)
{ \
    auto& container_evaluated = CONTAINER; \
    for (auto it = container_evaluated.begin(), it_end = container_evaluated.end(); it != it_end; ++it) { \
        VAR = *it; \
        SCOPE; \
    } \

//  Convenience macros
#define pfor PARALLEL_FOR
#define pforeach PARALLEL_FOREACH
#define sfor SINGLE_FOR
#define sforeach SINGLE_FOREACH

[0] [2011-09-20 23:46:22] Rupert

Before you write a double to the database, to avoid "Query error: Unknown column 'nan' in 'field list'" errors, apply the following wrapper:

static inline double SafeDouble(double const &d, double const def=0.0)
        return (isfinite(d) && isfinite(-d))?d:def;

[0] [2009-01-22 16:02:34] Christoph

Determine a file's size with ISO-C:

long fsize(FILE * file)
    if(fseek(file, 0, SEEK_END))
        return -1;

    long size = ftell(file);
    if(size < 0)
        return -1;

    if(fseek(file, 0, SEEK_SET))
        return -1;

    return size;

(2) On binary files this will work fine, but if they're opened in text mode, you may be in for a surprise... - rmeador
"In the GNU library, and on all POSIX systems, there is no difference between text streams and binary streams. When you open a stream, you get the same kind of stream regardless of whether you ask for binary." - Christoph
Windows has some issues with non-text files opened in text mode and auto-converts \r\n to \n (this isn't an issue when determining the size of a buffer needed to hold the file's contents); this has an easy fix: always open files in binary mode! - Christoph
(3) Wouldn't stat or fstat be alot better suited for this purpose? - roe
@roe: these functions are not part of the ISO-C standard library - Christoph
Is filelength() part of ISO-C? - Ferruccio
(2) Ferruccio: Does it have all of its vowels? Yes? So obviously not in ISO-C! - jkerian
(3) @Christoph: stat/fstat on POSIX and GetFileSize(Ex) on Windows covers you on 99.9% of all systems anyone cares about. Using these functions will almost assuredly be faster. - Adam Rosenfield
[0] [2009-01-22 16:01:30] Cody Brocious
#define NuLog(str, args...) {\
    fprintf(NULOG_OUTPUT, "Log (" NUMODULE_NAME "): " str "\n", ##args); \
    fflush(NULOG_OUTPUT); \

Define NUMODULE_NAME in each component of your software and log to your heart's content.

[0] [2010-08-31 12:25:26] Donal Fellows

In my C code, I often have dynamic array structures declared like this:

struct {
    int num;
    SomeType *list;
} foobar;

To make that easier in code where I'm iterating over those dynamic arrays a lot, I use this macro:

#define FOREACH(var,lst) \
    for(i=0 ; (i<(lst).num?(((var)=(lst).list[i]),1):0) ; i++)

Which means I can then do this:

int i;
SomeType foo;

FOREACH(foo, foobar) {
    /* Do something with foo here... */

While yes, it's not the world's most reusable (the i is an issue, but that's awkward to fix and maintain strict C89 compatibility) it helps a lot because it means that I have my iteration code written correctly, once. I have another similar construct – FOREACH_HASH – for iterating over the key/value pairs in hash tables, but that's more horrific and harder for other people to reuse so I won't repeat it here.

[-1] [2010-05-22 05:46:49] Arrieta

A very nerd one, which works if you are surrounded by nerds who do not care about code maintenance:

#define as ;while
int main(int argc, char* argv[]){
 int n = atoi(argv[1]);
 do printf("n is %d\n", n) as ( n --> 0);
 return 0;

[-1] [2010-04-27 22:01:52] ahe
#include <glib.h>

[-1] [2009-10-22 19:38:51] n1ckp

When a class need to override the default copy constructor/assignment I sometime use something like this:

class SomeClass
   struct Members
      int a;
      int b;

   Members m;
   int* evilptr;

   SomeClass(SomeClass const& rhs) : m(rhs.m), evilptr(new int(*rhs.evilptr))


   ~SomeClass(){ delete evilptr; }

   SomeClass& operator=(SomeClass const& rhs)
      m = rhs.m;
      evilptr = new int(*rhs.evilptr);
      return *this;

This way, if you add a new members to the class you can't forget to add it to the copy constructor/assignement operator. This save some possibility of error.

Of course in my exemple I could use some kind of clone_ptr but in real life this is not always this simple. Also beware that I never check for NULL in my exemple when dereferencing evilptr, you should of course adapt the code according to your needs.

[Edit]: I added a destructor for those complaining about memory leaks. Please note that I still omit a lot of checks as the point I was trying to illustrate was that with wrapping normally-copyable variable in a struct you don't need to update the copy constructor/assignment operator when adding/removing a variable from a class. That's the only point of my answer so please try to judge it on that and not on a bunch of other points not really related to the case.

(1) I'm confused, does this not leak all over the place? You need the Big Three, and the pointer should be wrapped up. - GManNickG
@GMan: The point I was trying to illustrate was that Members do not need to be updated in the copy constructor and the assignement operator by wrapping it in a struct. The rest is left to the reader. As it is community wiki you're of course welcome to ameliorate it and you're also welcome to use the type of pointer that you prefer. - n1ckp
(1) You can never provide a code with new without delete or a smart pointer, and expect it to be viewed in a positive light. I could indeed change it myself, but what point it that? Also, for what reason is the evil pointer in there? What value should evilptr get at construction? This feels more like an incomplete code snippet than like a code trick to me. - Jasper
@Jasper: please let me LOL. Sorry I read my answer again and maybe when reading fast I understand that you did not get the trick. Read my comment to GMan above. Memory management, smart_ptr or the value of the pointer is in no way important in the code sample so was omitted. The point is that you don't have to update the copy constructor when adding/deleting a member of a class by wrapping them in a Member struct. The pointer is to illustrate a member that should not be copied normally -- and nothing else ,that's why I didn't took care of deleting it. - n1ckp
Also, to clarify, in the exemple, we could use a deep_copy_ptr (that's what I meant by clone_ptr I guess) but then it would destroy the exemple as it could then be added to the members struct without any problem. The point is that in real life some pointer need special care so cannot be copied normally. This is the point of the trick -- not needing to update those variable than can be copied normally. Sorry if my answer was not clear enough. It is noted and I will see what I can do about it. - n1ckp
@n1ck: If that's how it is, your presentation is clearly in the way of your point - I really didn't get it. Perhaps you could start off with something like When you need a custom copy constructor/assignment operator for one or more elements of your object, you can wrap all other objects in a struct so you won't need to update your copy constructor/assignment operator when changing the object. Like this: and then give the code sample instead of just letting the code speak for itself (which it didn't do very well in my opinion). - Jasper
@n1ck: Additionally, you could provide a comment at the evilptr code, explaining that it is not a part of the trick, but just something you needed a custom copy constructor for, that will provide a lot of clarity. Also, I would say that a code sample may leave a lot to the reader (like making a class useful in any way) and may make certain assumptions about added functions if noted (like assuming that other functions don't modify your pointer), but I do think code samples should work all on their own... As such, I would recommend adding a normal constructor or using std::auto_ptr - Jasper
I still don't see the point. Bad practice, use the copy-and-swap idiom. - GManNickG
@GMan: see my new answer:…. You're right that it do not use the copy-and-swap idiom though but I was not totally sure how to implement the most optimal copy construction so left it to the reader for the moment. - n1ckp
@n1ck: What I mean is I still don't see the point, and until you clarify this and finish it, nobody will. You're the only one who knows what you intend with it. There's no point in sticking all the members into a struct just to make copying easier, when you can properly implement copy-semantics with the copy-and-swap idiom, which is cleaner. - GManNickG
@GMan: Did you read my new link or what? It clearly indicate a use case. I have a bare pointer that is only an alias and the other members should be copied normally. I don't see how the copy-and-swap idiom would help in that case. It would surely improve the code I agree with you but it will not solve my problem. - n1ckp
@n1ck: Yes, it doesn't clarify anything. Again, all you're giving is intent (I fix problem x by doing y), but fail to actually explain problem x or problem y in detail. We don't know what the members are, what the pointers for, why you need to do it this way, etc. The code, as it stands, leaks and is incomplete. You really need to give concrete examples when you present an idea. - GManNickG
@GMan: Well I didn't want to post full code at the time. With the new post you should be able to tell what it is about. If you work with deep copy it is possible you have experienced the need to do something like this. Before I knew of this trick I just copied the values in the copy constructor instead, one by one, but was error prone. I just wanted to share it with the stackoverflow community so that they know there is a better way to do things and now you're complaining about that the code is not perfect. Yes I aknowledged that point, now move on, please. - n1ckp
@n1ck: I can now, but honestly the code would be better off using the copy-and-swap idiom then this idiom, in my opinion. My complaint is that when you say "do this", the "this" part needs to be complete and well. It still leaks, as it stands. I get the point, it's just that the point is lost around all the bad stuff. - GManNickG
@GMan: Just think the pointer as representing the "parent" (enclosing class) pointer in my other answer. It do not need to be copied when deep copying. The values (POD) should be copied, the pointer need to point to the correct memory location which the parent know during the copying. When the parent is copied it pass the pointer value to the child (each child need to know about the parent if you will) but this pointer is not updated in the normal way. This solution prevent that (and possibly other problems) that is the reason why I want to post it. - n1ckp
@GMan: I just read your answer about copy-and-swap and I don't know why you sent me there because it suffer exactly from the problem that I say I have fixed: what happen when you add a value to your dummy_array class and forget to update the swap function -> bug (possibly not detected directly too - it might crash way later). By wrapping the members in a struct you don't have to remember to update those values that should only be copied normally. - n1ckp
@GMan: I edited my other answer with a code sample if you're interested. - n1ckp