c++11 std::call_once写单列模式

#include <iostream>
#include <memory>
#include <mutex>

class Singleton {
public:
    static Singleton& GetInstance() {
        //c++11保证唯一性
        static std::once_flag flag;
        std::call_once(flag, []() {
            instance_.reset(new Singleton);
            });

        return *instance_.get();
    }

    ~Singleton()
    {
        std::cout << "~Singleton()" << std::endl;
    }

    void PrintAddress() const {
        std::cout << this << std::endl;
    }

private:
    Singleton() = default;

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

private:
    static std::unique_ptr<Singleton> instance_;
};

std::unique_ptr<Singleton>Singleton::instance_;

发布了63 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33048069/article/details/103931440