Using a singleton in C++

末鹿安然 提交于 2019-12-25 03:26:29

问题


I have a class which is a Singleton class. In the CPP file I have:

static std::unique_ptr<CStage> s;
    MSOCPPAPITYPE_(ICStage&) GetInstance()
    {
        try
        {
            s = std::make_unique<CStage>();
        }
        catch (...)
        {

        }
        return *s;
    }

Within another file I call GetInstance().SetMValue(true); which is a function that sets a member variable of the class to true. The default value of the member variable is false. Then I call GetInstance().GetMValue(); which returns the value of the member variable. Instead of returning true I get a false return value. This causes me to believe that I am not properly using the singleton. How do I properly use my class as a singleton?


回答1:


I can't see the need for using std::unique_ptr here. You can simplify your GetInstance() function as follows

static MSOCPPAPITYPE_(ICStage&) GetInstance() {
    static CStage theInstance;
    return theInstance;
}    


来源:https://stackoverflow.com/questions/25092657/using-a-singleton-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!