Using a singleton in C++

2019-08-30 06:22发布

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?

标签: c++ singleton
1条回答
ゆ 、 Hurt°
2楼-- · 2019-08-30 06:31

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;
}    
查看更多
登录 后发表回答