单例

单例模板

#include <memory>
#include <mutex>
#include <iostream>
using namespace std;
template <typename T>
class Singleton {
protected:
    Singleton() = default;
    Singleton(const Singleton<T>&) = delete;
    Singleton& operator=(const Singleton<T>& st) = delete;

    static std::shared_ptr<T> _instance;
public:
    static std::shared_ptr<T> GetInstance() {
        static std::once_flag s_flag;
        std::call_once(s_flag, [&]() {
            _instance = shared_ptr<T>(new T);
            });

        return _instance;
    }
    void PrintAddress() {
        std::cout << _instance.get() << endl;
    }
    ~Singleton() {
        std::cout << "this is singleton destruct" << std::endl;
    }
};

template <typename T>
std::shared_ptr<T> Singleton<T>::_instance = nullptr;

对象通过 std::shared_ptr 管理:
在这个实现中,单例对象 _instance 是通过 std::shared_ptr 创建和管理的。因此,当你在派生类中调用 shared_from_this() 时,
不会抛出 std::bad_weak_ptr 异常,因为 shared_from_this() 需要对象是通过 std::shared_ptr 创建的。

posted on 2024-10-21 11:22  不败剑坤  阅读(22)  评论(0)    收藏  举报

导航