C++ std::call_once 實現單例模式

double64發表於2024-09-22
#if 1
#include <iostream>
#include <memory>
#include <mutex>

using namespace std;

class Singleton
{
public:
    static Singleton &getInstance()
    {
        std::call_once(m_OnceFlag, &Singleton::init);
        return *m_Instance;
    }
    void setData(int data)
    {
        m_Date = data;
    }
    int getData()
    {
        return m_Date;
    }

private:
    Singleton(){}
    Singleton(const Singleton &) = delete;
    Singleton &operator=(const Singleton &) = delete;
    static void init()
    {
        m_Instance.reset(new Singleton);
    }
    static std::unique_ptr<Singleton> m_Instance;
    static std::once_flag m_OnceFlag;
    int m_Date{ 0 };
};

std::unique_ptr<Singleton> Singleton::m_Instance;
std::once_flag Singleton::m_OnceFlag;

int main()
{
    Singleton::getInstance().setData(100);
    cout << Singleton::getInstance().getData() << endl;
    system("pause");
    return EXIT_SUCCESS;
}

輸出:

100





參考:http://www.seestudy.cn/?list_9/39.html

相關文章