在C ++中使用单例 [英] Using a singleton in C++
问题描述
我有一个类是Singleton类。在CPP文件中我有:
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;
}
在另一个文件中调用 GetInstance()。SetMValue (true);
这是一个将类的成员变量设置为 true
的函数。成员变量的默认值为 false
。然后我调用 GetInstance()。GetMValue();
,它返回成员变量的值。而不是返回 true
,我得到一个 false
返回值。这使我相信我没有正确使用单例。如何正确使用我的类作为单例?
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?
推荐答案
我看不到使用 std :: unique_ptr
这里。您可以如下简化 GetInstance()
函数
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;
}
这篇关于在C ++中使用单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!