// singleton.h
#include <memory> // for auto_ptr
using namespace std;
class Singleton {
typedef auto_ptr<Singleton> SingletonPtr;
// the auto_ptr should be returned by reference;
// otherwise the returned copy will receive the ownership
// over the sole instance of the class
static SingletonPtr& get_instance();
// so that the auto_ptr may delete the singleton
friend class auto_ptr<Singleton>;
// Singleton objects should NOT be copy constructed or
// assigned. Therefore, copy constructor and assignment
// operator made private so that clients cannot invoke them
// and the compiler doesn't create them implicitly.
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
protected:
// the constructor is protected, so that no instances of this
// class may be created except in the dedicated function
// 'get_instance' or by the derived classes
Singleton() { /* initialize the singleton object */ }
// the destructor is protected so that nobody deletes the
// singleton by mistake (or maliciously)
~Singleton() { /* destroy the singleton object */ }
public:
static Singleton& instance() { return *get_instance(); }
static const Singleton& const_instance() { return instance(); }
};
// singleton.cxx:
#include "singleton.h"
Singleton::SingletonPtr& Singleton::get_instance()
{
static SingletonPtr the_singleton(new Singleton);
return the_singleton;
}