C++11 后的单例写法

template<typename T>
class Singleton
{
public:
    static T& getInstance() {
        static T t;
        return t;
    }

    Singleton(const Singleton&) = delete; 
    Singleton& operator=(const Singleton&) = delete; 
protected:
    Singleton() = default;
    ~Singleton() = default;
};

例:

#include<iostream>
class Test:public Singleton<Test>
{
public:
    void myprint()
    {
        std::cout<<"test Singleton"<<std::endl;
    }
};
int main()
{
    Test::getInstance().myprint();
    return 0;
}
posted @ 2023-11-27 11:18  penuel  阅读(8)  评论(0编辑  收藏  举报