I'm fond of this method....
class Single
{
public:
static Single &getSingle()
{
static Single theSingle;
return theSingle;
}
private:
Single(); // private constructor to enforce singleton
//public: // (1) if you uncomment this line then (2) below
// can be made to compile (and crash!).
~Single();
};
Single::Single()
{
}
Single::~Single()
{
}
int main()
{
Single &s = Single::getSingle();
// delete &s; // (2) won't compile if you uncomment unless you
// uncomment (1) above; but, who would do this?
return 0;
}
This has the benefit that the reference can't be freed (though, as I show, the caller can jump through hoops to free it, so the private destructor is still good practice). However, I'd suspect that most people would see a reference and know that deleting it is probably bad.
Buyer beware, however, that the standard is pretty hush-hush on its thread safety. Though, most practical compilers (g++) wrap the local static member ("theSingle") with locks to insure it does not get constructed more than once. In my opinion, this is preferable to roll-your-own. However, if you must, a pthread_once_t control is probably the way to do it as here:
#include <pthread.h>
class Single
{
public:
static Single &getSingle()
{
pthread_once(&onceCtl, BuildTheSingle);
return *theSingle;
}
private:
static Single *theSingle;
static pthread_once_t onceCtl;
static void BuildTheSingle();
Single();
~Single();
};
pthread_once_t Single::onceCtl = PTHREAD_ONCE_INIT;
Single *Single::theSingle = NULL;
void Single::BuildTheSingle()
{
theSingle = new Single();
}
Single::Single()
{
}
Single::~Single()
{
}
Which uses the same reference return to, IMO, instruct the caller that it's not theirs and they shouldn't be free'ing it.
I suppose you could also use auto pointers or something, too, but...this is good enough for me, lol.
edit: for the record, the former implementation is thread-safe in C++0x, as such, in any newer code compiled with C++0x compliant compiler, I'd recommend it to rid all the boilerplate crap and distill it right to only that code which is both sensible and required. Just one man's opinion....