class singleton {
private:
static singleton* pInstance = NULL; // gist, need initialization
public:
// good for single-thread usage
singleton* getInstance() {
if(pInstance == NULL)
pInstance = new singleton;
return pInstance;
}
// DCLP method: Double-checked lock pattern
// Good for multi-threaded usage
// http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
singleton* getInstance2() {
if(pInstance == 0) {
Lock lock;
if(pInstance == 0) {
pInstance = new singleton;
}
}
return pInstance;
}
};
// http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used
// read Chapter 3.2.1 in Book <API design for C++> for details and why.
class singleton {
private:
// declare constructor and descructor to private to prevent creating subclass.
singleton();
~singleton(); // prevent client from deleting the instance
// stop compiler generating methods of copy object
singleton(const singleton& copy); // not implemented
singleton& operator=(const singleton& copy); // not implemented
public:
// Returning pointer or reference are both fine. But return reference is prefered.
// because if return pointer, clients could potentially delete the instance.
static singleton& getInstance3() {
// the only instance, guranteed to be lazy initialized
// guranteed that it will be destroyed correctly
// however, below is not thread-safe.
static singleton instance;
return instance;
}
};
// the most concise version
class S {
private:
S();
~S();
S(const S& c);
S& operator=(const S& c);
public:
static S& getInstance3() {
static S instance;
return instance;
}
};