C ++是=原子的静态变量初始化吗? [英] C++ is static variable initialization with = atomic?
问题描述
Meyers Singleton取决于以下事实:局部静态变量初始化为原子.
The Meyers Singleton depends on the fact that local static variable initialization is atomic.
我正在构建类似的东西,但我希望单例实际上是许多派生类型之一.基类 getInstance()
方法应调用一个将返回适当类型的工厂.
I'm building something similar but I want the singleton to actually be one of a number of derived types. The base class getInstance()
method should call a factory that will return the appropriate type.
我的第一个想法是
static Foo *instance = FooFactory(...);
8.5p2, N3337 似乎表明这严格是初始化,而不是初始化和赋值,我认为这意味着整个语句都是原子的.这样对吗?
8.5p2 of N3337 seems to indicate that this is strictly initialization and not initialization and assignment and I interpret that to mean the entire statement is atomic. Is this correct?
如果不是,则声明
static Foo *instance(FooFactory(...));
与众不同吗?
编辑8.5.2-> 8.5.p2
Edit 8.5.2 -> 8.5.p2
推荐答案
8.5.2是"[dcl.init.string]",似乎并不相关.我认为您的意思是8.5 para2.
8.5.2 is "[dcl.init.string]", and doesn't seem to be relevant. I think you mean 8.5 para2.
是的,这是严格的初始化(特别是复制初始化-参见8.5 para14).
Yes, this is strictly initialization (specifically copy initialization - see 8.5 para14).
如果声明在函数内部,那么,如所链接问题的答案所示,一切都很好.
If the declaration is inside a function, then, as the answer to the linked question shows, all is well.
但是,如果这是命名空间范围内的静态变量,那么我看不到任何需要初始化才能保证线程安全的东西.(这仅是初始化创建线程的问题,但我敢打赌.)
However if this is a static variable at namespace scope, then I can't see anything which requires the initialization to be thread safe. (That is only a problem if initialization creates threads - but I bet it does.)
这篇关于C ++是=原子的静态变量初始化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!