简体   繁体   English

C ++是静态变量初始化与=原子?

[英]C++ is static variable initialization with = atomic?

The Meyers Singleton depends on the fact that local static variable initialization is atomic . Meyers Singleton依赖于本地静态变量初始化是原子的这一事实。

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. 基类getInstance()方法应该调用将返回适当类型的工厂。

My first idea is 我的第一个想法是

static Foo *instance = FooFactory(...);

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. N3337的8.5p2似乎表明这是严格初始化而不是初始化和赋值,我将其解释为整个语句是原子的。 Is this correct? 这个对吗?

If not would the statement 如果不是声明

static Foo *instance(FooFactory(...));

be different? 有所不同吗?

Edit 8.5.2 -> 8.5.p2 编辑8.5.2 - > 8.5.p2

Since C++11, initialization of static variables which are local to functions is atomic and thread safe, so yes, your lines of code is thread-safe and practically equivalent. 从C ++ 11开始,函数本地的静态变量的初始化是原子的和线程安全的,所以是的,你的代码行是线程安全的,实际上是等价的。 (Syntax-wise your first version calls for copy constructor, but no compiler will generate it). (语法方面,您的第一个版本调用复制构造函数,但没有编译器会生成它)。

However, it is not clear what arguments are going to be provided to your Factory function and where are those going to be taken from? 但是,目前尚不清楚将为您的工厂功能提供哪些参数以及将从哪些参数中取出?

variable_type variable_name = initializer is always initialization and not default construction and assignment. variable_type variable_name = initializer始终是初始化,而不是默认构造和赋值。 [dcl.init]/15 has [dcl.init] / 15有

The initialization that occurs in the form 在表单中发生的初始化

 T x = a; 

as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.5.1) is called copy-initialization. 以及参数传递,函数返回,抛出异常(15.1),处理异常(15.3)和聚合成员初始化(8.5.1)称为复制初始化。 [ Note: Copy-initialization may invoke a move (12.8). [注意:复制初始化可以调用移动(12.8)。 —end note ] - 尾注]

8.5.2 is "[dcl.init.string]", and doesn't seem to be relevant. 8.5.2是“[dcl.init.string]”,似乎没有相关性。 I think you mean 8.5 para2. 我认为你的意思是8.5 para2。

Yes, this is strictly initialization (specifically copy initialization - see 8.5 para14). 是的,这是严格的初始化(特别是复制初始化 - 见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.) (如果初始化创建线程,这只是一个问题 - 但我敢打赌它。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM