I l@ve RuBoard Previous Section Next Section

6.3 Enforcing the Singleton's Uniqueness

A few language-related techniques are of help in enforcing the singleton's uniqueness. We've already used a couple of them: The default constructor and the copy constructor are private. The latter measure disables code such as this:



Singleton sneaky(*Singleton::Instance()); // error!


//  Cannot make 'sneaky' a copy of the (Singleton) object


//  returned by Instance


If you don't define the copy constructor, the compiler does its best to be of help and defines a public one for you (Meyers 1998a). Declaring an explicit copy constructor disables automatic generation, and placing that constructor in the private section yields a compile-time error on sneaky's definition.

Another slight improvement is to have Instance return a reference instead of a pointer. The problem with having Instance return a pointer is that callers might be tempted to delete it. To minimize the chances of that happening, it's safer to return a reference:



// inside class Singleton


static Singleton& Instance();


Another member function silently generated by the compiler is the assignment operator. Uniqueness is not directly related to assignment, but one obvious consequence of uniqueness is that you cannot assign one object to another because there aren't two objects to start with. For a Singleton object, any assignment is a self-assignment, which doesn't make much sense anyway; thus, it is worthwhile to disable the assignment operator (by making it private and never implementing it).

The last coat of the armor is to make the destructor private. This measure prevents clients that hold a pointer to the Singleton object from deleting it accidentally.

After the enumerated measures are added, Singleton's interface looks like the following.



class Singleton


{


   Singleton& Instance();


   ... operations ...


private:


   Singleton();


   Singleton(const Singleton&);


   Singleton& operator=(const Singleton&);


   ~Singleton();


};


    I l@ve RuBoard Previous Section Next Section