c++ - 使用 CRTP 实现单例

标签 c++ singleton crtp

看完this answer我已经尝试实现一些简单的 CRTP 用法。我想我会尝试实现单例模式(是的,我知道 - 它只是为了练习和研究)模式,因为链接的答案有点已经做到了......除了事实上它不编译。

引用代码如下:

template <class ActualClass> 
class Singleton
{
   public:
     static ActualClass& GetInstance()
     {
       if(p == nullptr)
         p = new ActualClass;
       return *p; 
     }

   protected:
     static ActualClass* p;
   private:
     Singleton(){}
     Singleton(Singleton const &);
     Singleton& operator = (Singleton const &); 
};
template <class T>
T* Singleton<T>::p = nullptr;

class A: public Singleton<A>
{
    //Rest of functionality for class A
};

然后我将其“现代化”为:

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

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

   protected:
     static inline T* instance = nullptr;
};

class A: public Singleton<A> {
    //Rest of functionality for class A
};

然后我尝试创建对该实例的引用:

auto& x = A::get_instance();

显然没有编译。

值得一提的是,我收到了非常相似的错误消息,特别是:

note: 'A::A()' is implicitly deleted because the default definition would be ill-formed: class A : public Singleton<A>.

显然,第二段代码无法编译,因为我们删除了默认构造函数并尝试将其与new T 一起使用。在get_instance方法。

让我感到惊讶的是,第一个代码段也没有编译,并出现类似的错误消息。链接的答案是否有错误?我如何使用 CRTP 为单例实现通用基类/接口(interface)

最佳答案

这里是“现代化”片段的修改:

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 A : public Singleton<A> {
protected:
    A() {}
};

int main()
{
    auto& x = A::get_instance();
}

代码段的更改摘要:

  • protected 单例中的默认构造函数
  • private 嵌套结构以访问派生类的 protected 构造函数
  • protected 派生类中的构造函数以防止实例化

此外,无需删除通过向单例类添加默认构造函数实现而隐式删除的构造函数。

不像Richard Hodges那么小' 示例,但是静态 instance 成员使得添加 delete_instance() 方法以用于自动化单元测试变得容易。

关于c++ - 使用 CRTP 实现单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974670/

相关文章:

c++ - 像 C# HashSet<T> 和 Dictionary<K,V> 这样的快速 C++ 容器?

c++ - 为什么内置赋值返回一个非 const 引用而不是 C++ 中的 const 引用?

ios - 我们应该为一个单例类创建多个对象吗?这适合单例设计模式吗

java - 具有静态内部类和双重检查锁定的单例

c++ - 如何实现编译时检查 CRTP 中的向下转换是否有效?

c++ - 从可变参数继承并使用参数包: default constructor构造

c++ - 如何定义和测试字符串值的宏?

design-patterns - 用什么替换单例?

c++ - 将 CRTP 用于析构函数是否安全?

c++ - 通过重新解释转换将 constexpr 值转换为指针