Original Post
I was toying around with creating a generic Singleton class. I was wondering if any of you could comment on this idea: From basic testing it works fine, you can't leak memory, but you can also control the order of destruction if it is important. Does anyone have any suggestions?
#include <cassert>
#include <memory>
#include <iostream>
template<class T>
class Singleton
{
public:
static void initSingleton()
{
assert(instance_.get() == 0);
instance_ = std::auto_ptr<T>(new T);
}
static T& getSingleton()
{
assert(instance_.get() != 0);
return *instance_;
}
static void destroySingleton()
{
assert(instance_.get() != 0);
instance_.reset();
}
virtual ~Singleton()=0;
private:
static std::auto_ptr<T> instance_;
};
template<class T>
std::auto_ptr<T> Singleton<T>::instance_(0);
template<class T>
Singleton<T>::~Singleton() { }
class Something : public Singleton<Something>
{
friend class Singleton<Something>;
friend class std::auto_ptr<Something>;
private:
Something() { std::cout << "created" << std::endl; }
~Something() { std::cout << "destroyed" << std::endl; }
};