answersLogoWhite

0

A singleton is a class of object from which only one instance of the object can be instantiated within your program. They are generally used to store global variables or to provide some common functionality, such as an application log. They are generally frowned upon because of their global nature, but when you need common functionality there are far worse ways of going about it than with a singleton.

There are several design patterns for a singleton, but probably the simplest and most common form is shown below. Note the private constructors and assignment operator, and the static member method containing a static variable -- the only instance of the class that can ever exist.

Access to the members (not shown) is via a static call:

CSingleton::Instance().<member>

class CSingleton

{

private:

CSingleton() {}; // Prevent construction outside of the class.

CSingleton(const CSingleton&); // Prevent copy-construction.

CSingleton& operator=(const CSingleton&); // Prevent assignment.

public:

static CSingleton& Instance()

{

static CSingleton singleton;

// Created on first access.

// Destroyed on application exit.

return( singleton );

}

// Specific members omitted. Dependant upon purpose of singleton.

};

User Avatar

Wiki User

13y ago

What else can I help you with?