c++单例模式模板

所有单例模类直接继承此模板即可,线程安全,效率高(无锁),延时构造。

#include <iostream>
using namespace std;

template <typename T>
class Singleton {
public:
    //外部获取单例的接口
    static T& getInstance() {
        static Token token;
        static T instance(token);   //函数静态变量可以实现延时构造。
        return instance;
    }

    //禁止拷贝
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

protected:
    //只有子类才能获取令牌。
    struct Token{};

    //构造和析构函数私有化
    Singleton() = default;
    virtual ~Singleton() = default;
};

//具体单例模式
class Single : public Singleton<Single> {
public:
    //Token保证,父类需要调用,其他人无法调用。
    Single(Token token) {
        cout << "construct: " << this << endl;
        //做你想做的事情。
    }
    ~Single() = default;

    //禁止拷贝
    Single(const Single&) = delete;
    Single& operator=(const Single&) = delete;

};

int main()
{
    cout << "main begin" << endl;
    Single &s1 = Single::getInstance();
    Single &s2 = Single::getInstance();
    cout << boolalpha << (&s1 == &s2) << endl;
    cout << "main end" << endl;
    return 0;
}
发布了10 篇原创文章 · 获赞 11 · 访问量 2717

猜你喜欢

转载自blog.csdn.net/waxtear/article/details/104182639