【发布时间】:2020-02-22 04:14:22
【问题描述】:
我希望创建一个静态 Class 对象,该对象应在程序运行时保留在内存中。该对象只需要由 init 函数初始化一次,并且输出函数将始终在静态方法中调用。我的代码有意义吗?它是线程安全的吗?
class Singleton
{
public:
static void init(const int value)
{
static Singleton inst;
inst.Value = value;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
int main()
{
int inputValue = 10;
Singleton::init(inputValue);
cout << Singleton::prnValue();
return 0;
}
新编辑: 或者我可以这样尝试吗?
class Singleton
{
public:
static Singleton& init(const int value)
{
static Singleton inst;
inst.Value = value;
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
补充: Meyer 的单例示例看起来像
class Singleton
{
public:
static Singleton& init()
{
static Singleton inst;
return inst;
}
private:
Singleton() {};
};
那么我的代码不是和 Meyer 的例子一致吗?
Try4: 这个怎么样?
class Singleton
{
public:
static Singleton& init(int value)
{
static Singleton inst(value);
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton(value)
{
Value = value;
}
int Value;
};
添加评论: How to pass argument in a singleton 似乎提供了与 Try4 相同的答案。
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
在多线程上下文中(从您的问题文本中不确定),您可以使用经典的 std::call_once 库函数来保护初始化。线索就在名字里。
标签: c++ thread-safety singleton