"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote in message
news:40******** ******@jpl.nasa .gov...
Could somebody please help me with the definition of a singleton?
> cat singleton.cc
class {
private:
// representation
int A;
int B;
public:
//functions
const
int& a(void) const { return A; }
int& a(void) { return A; }
const
int& b(void) const { return B; }
int& b(void) { return B; }
} singleton;
The easiest principle is the so called "Meyers singleton". This simply
returns a reference to a static instance of an object. The following is a
generic implementation of a singleton wrapper which you can use with
whatever object you want. Of course there are some guidelines you should
stick to. The object that becomes a singleton must be derived from
CNonCopyable to prevent sneaky copy construction and so on. Furthermore the
wrapped class must include a friend declaration for the singleton wrapper to
allow access.
template<class T/*, class Tag = void*/>
class CSingleton
{
private:
CSingleton(void ) {}
~CSingleton(voi d) {}
CSingleton( const CSingleton& rhs );
CSingleton& operator=( const CSingleton& rhs);
public:
static T& Instance() { // Meyers singleton
static T m_Instance;
return m_Instance;
}
};
class CNonCopyable {
protected:
CNonCopyable() {};
virtual ~CNonCopyable() {};
private:
CNonCopyable( const CNonCopyable& rhs );
CNonCopyable& operator=(const CNonCopyable& rhs );
};
The following as an example how to implement a wrapped singleton object
class CObj : public CNonCopyable {
protected:
CObj() {};
public:
~CObj() {};
friend class CSingleton<CObj >; // Attention: this must be
provided to enable the singleton wrapper to construct an object
int m_i;
};
Usage:
CObj& MyObj = CSingleton<CObj >::Instance() ;
// The following should not work as sneaky copies are prevented by
inheritance of CNonCopyable
CObj Sneaky( CSingleton<CObj >::Instance() );
HTH
Chris