- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我过来了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/
嘿。本周的一个教程,其中一个问题要求通过使用其他函数 formatLine 和 formatList 创建一个函数 formatLines,以格式化行列表。 我的代码是这样的; type Line =
我是一名优秀的程序员,十分优秀!