gpt4 book ai didi

c++ - 在类似于 Scott Meyer 的单例惯用语的实现中使用新线程安全来实例化单例吗?

转载 作者:行者123 更新时间:2023-11-28 04:50:08 25 4
gpt4 key购买 nike

我过来了this question最近,对 Instance() 函数的实现产生了疑问:

class Configuration
{
public:
static Configuration* Instance() {
static Configuration * myInstance = new Configuration();
return myInstance;
}

int i;
// delete copy and move constructors and assign operators
Configuration(Configuration const&) = delete; // Copy construct
Configuration(Configuration&&) = delete; // Move construct
Configuration& operator=(Configuration const&) = delete; // Copy assign
Configuration& operator=(Configuration &&) = delete; // Move assign

protected:
Configuration() {

}
~Configuration() {}

// ...
}

不幸的是,OP 似乎无法提供重现他们声称的读取访问违规的 MCVE。

  • 在该实现中使用实例指针和 new 是否仍然保证线程安全(竞争条件可能是该错误的潜在原因)?

这是 working code 的示例,虽然只涉及一个线程。

最佳答案

Is using an instance pointer and new in that implementation still guaranteed to be thread safe (a race condition could be a potential reason for that error)?

是的,它是线程安全的。

来自 N4659:

9.7 Declaration statement [stmt.dcl]

Dynamic initialization of a block-scope variable with static storage duration (6.7.1) or thread storage duration (6.7.2) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

由于 myInstance 是一个 block 作用域变量,具有动态初始化的静态存储持续时间,即使涉及多个线程,代码也是线程安全的。

关于c++ - 在类似于 Scott Meyer 的单例惯用语的实现中使用新线程安全来实例化单例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48389757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com