是否可以强制通过单例实例化一个类

时间:2021-05-30 04:44:32

标签: c++ singleton

当我使用 C++11 编码时,我通常使用单例设计模式。以下是我设计单身人士的方式:

template<typename T>
class Singleton {
private:
    Singleton() = default;
    ~Singleton() = default;
public:
    static T * GetInstance() {
        static T t;
        return &t;
    }
    Singleton(const Singleton &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton & operator=(const Singleton &) = delete;
    Singleton & operator=(Singleton &&) = delete;
};

然后,我们可以定义我们想要的任何类,例如class Test{};Singleton<Test>::GetInstance(); 将生成一个对象。

一切正常。

然而,今天我认为 class Test{}; 可以摆脱限制。我的意思是,即使我定义了类 Singletion<T>,但其他开发人员可以定义他们的类,例如 Test,并且不使用 Singleton,因此如果他们可以生成许多对象想。但是我想要的是,如果你决定定义一个类,它应该是单例的,你不能通过调用构造函数来生成对象,而只能通过调用Singleton<Test>::GetInstance()

一句话,我想得到这个:

Test t;  // compile error
Test *p = Singleton<Test>::GetInstance(); // OK

为此,我尝试了一些棘手的方法,例如,我让类 Test 继承 Singleton<Test>

class Test : public Singleton<Test> {
public:
    Test() : Singleton<Test>() {}
};

因此,如果您正在定义一个应该是单例的类,那么您继承了类 Singleton,现在您的类无法通过调用构造函数生成任何其他对象。但它不起作用,因为 Singleton 的构造函数是私有的。但是如果我在类 friend T; 中写 SingletonTest t; 将成为合法...

好像不能强制类用户只用Singleton来构造对象。

有人可以帮我吗?或者告诉我我正在做一些不可能的事情...

1 个答案:

答案 0 :(得分:4)

您可以使用 CRTP 模式来实现这一点

template <class T>
class Singleton {
public:
    Singleton& operator = (const Singleton&) = delete;
    Singleton& operator = (Singleton&&)      = delete;

    static T& get_instance() {
        if(!instance)
            instance = new T_Instance;
        return *instance;
    }

protected:
    Singleton() {}

private:
    struct T_Instance : public T {
        T_Instance() : T() {}
    };

    static inline T* instance = nullptr;
};

class Example : public Singleton<Example> {
protected:
    Example() {}
};

int main()
{
    auto& test = Example::get_instance();
    Example e; // this will give you error
}