加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 继承Singleton

发布时间:2020-12-16 03:26:39 所属栏目:百科 来源:网络整理
导读:快问.无论如何都要继承单例,以便子类是单例吗?我已经四处寻找,但我能找到的每一个单身都是按照课程实现的,而不是通用的. 解决方法 是的,有一种通用的方式.您可以通过 CRTP实现Singleton,例如: templatetypename Tclass Singleton{protected: Singleton() n
快问.无论如何都要继承单例,以便子类是单例吗?我已经四处寻找,但我能找到的每一个单身都是按照课程实现的,而不是通用的.

解决方法

是的,有一种通用的方式.您可以通过 CRTP实现Singleton,例如:
template<typename T>
class Singleton
{
protected:
    Singleton() noexcept = default;

    Singleton(const Singleton&) = delete;

    Singleton& operator=(const Singleton&) = delete;

    virtual ~Singleton() = default; // to silence base class Singleton<T> has a
    // non-virtual destructor [-Weffc++]

public:
    static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
    {
        // Guaranteed to be destroyed.
        // Instantiated on first use.
        // Thread safe in C++11
        static T instance;

        return instance;
    }
};

然后从中得出让你的孩子成为单身人士:

class MySingleton: public Singleton<MySingleton>
{
    // needs to be friend in order to 
    // access the private constructor/destructor
    friend class Singleton<MySingleton>; 
public:
    // Declare all public members here
private:
    MySingleton()
    {
        // Implement the constructor here
    }
    ~MySingleton()
    {
        // Implement the destructor here
    }
};

Live on Coliru

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读