我有以下Singleton策略类实现:
template <typename T>
class Singleton
{
Singleton(){}; // so we cannot accidentally delete it via pointers
Singleton(const Singleton&) = delete; // no copies
Singleton& operator=(const Singleton&) = delete; // no self-assignments
Singleton(Singleton&&) = delete; // WHY?
Singleton& operator=(Singleton&&) = delete; // WHY?
public:
static T& getInstance() // singleton
{
static T instance; // Guaranteed to be destroyed.
// Instantiated on first use.
// Thread safe in C++11
return instance;
}
};
Run Code Online (Sandbox Code Playgroud)
然后我通过奇怪的重复模板模式(CRTP)使用
class Foo: public Singleton<Foo> // now Foo …Run Code Online (Sandbox Code Playgroud)