c – 继承Singleton

前端之家收集整理的这篇文章主要介绍了c – 继承Singleton前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
快问.无论如何都要继承单例,以便子类是单例吗?我已经四处寻找,但我能找到的每一个单身都是按照课程实现的,而不是通用的.

解决方法

是的,有一种通用的方式.您可以通过 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

猜你在找的C&C++相关文章