次のコードは、シングルトン パターンの私の実装です。
#include <iostream>
template<class T>
class Uncopyable
{
protected:
Uncopyable(){}
~Uncopyable(){}
private:
Uncopyable(const Uncopyable<T>&);
Uncopyable& operator=(const Uncopyable<T>&);
};
template <class T>
class Singleton : private Uncopyable<T>
{
public:
static T* getInstancePtr()
{
return instance;
}
protected:
Singleton<T>()
{
if(instance == 0)
{
instance = new T();
}
};
~Singleton<T>()
{
};
private:
static T* instance;
};
template<class T> T* Singleton<T>::instance = 0;
class Test : public Singleton<Test>
{
public:
Test(){};
~Test(){};
inline void test() const
{
std::cout << "Blah" << std::endl;
}
private:
friend class Singleton<Test>;
protected:
};
int main(int argc, char* argv[])
{
Test* t = Test::getInstancePtr();
Test* t2 = Test::getInstancePtr();
t->test();
t2->test();
return 0;
}
この形式で動作しますが、シングルトンのコンストラクタとデストラクタが非公開ではなく保護されているため、本当に正しいかどうかはわかりません。それらをプライベートとして宣言すると、クラスにアクセスできないため、コードはコンパイルされません。この実装は安全に使用できますか、または 1 つのインスタンスのみが作成および使用されるように改善するためにできることはありますか?
ありがとう