Singles Club

Note: This entry has been restored from old archives.

A friend of mine was recently asked to jot down a C++ singleton implementation in a job interview, ah the venerable singleton. I guess we’ve all used it sometime or another, possibly trying to fit it into our designs just because it is cool.

Anyway, this dude is positively allergic to anything that looks inefficient. However, since threads are still considered cool locks become necessary, and locks are slow! So a seemingly common enhancement of the singleton is the “Double-Checked Locking Pattern”. This has the dual goals of supporting threaded client code safely and making optimisation junkies happy.

Singleton* Singleton::instance() 
{
    if (pInstance == 0) 
    {
        Lock lock;
        if (pInstance == 0) 
        {
            pInstance = new Singleton;
        }
    }
    return pInstance;
}

[[copied from the paper below]]

I wouldn’t opt for this myself, but I’ve seen it and would have used it if asked for (or I saw a need for) something more efficient. My default implementation would leave out the top level if wrapper, which is the part that makes it “Double-Checked Locking”.

However! It gets horribly complicated, my friend’s interviewer took issue with this implementation. The explanation being that a compiler implementation has the right to decide to assign pInstance to the allocated memory prior to actually executing the class construction code. This was met with disbelief, and when I was told about it I had a hard time believing it too. But things really can be this bad, for an in-depth coverage of the problems with the “Double-Checked Locking Pattern” have a read of this paper (PDF) by Scott Meyers and Andrei Alexandrescu (found in this DDJ article, page 4).

What a nightmare.

It reminds me of something someone I used to work with always said about the C++ standard: “watch out for the weasel words”. More clearly, watch out for the things the standard doesn’t promise.

My friend did get the job, despite the disagreement, and it sounds like a good one. Congratulations! Todo list for first day: eat humble pie. Or maybe: debate practicality of DCLP given constraints of known compiler and platform behaviour and the possible requirement for performance over portability? 😉


On a totally random note, why do so many well-known artists have (supposedly official) MySpace pages that totally suck? Try reading this, or this. (Ah, the aural fun of opening multiple myspace pages.) Maybe their web designers just can’t handle working without 100% flash?