问题
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