gpt4 book ai didi

c++ - 正在为 C++11 之前的编译器返回线程安全的本地静态对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:33 25 4
gpt4 key购买 nike

对于 C++11 之前的编译器来说,这个单例线程安全吗?正如我们所知,对于 C++11,它是线程安全的。

class Singleton
{
private:
Singleton(){};

public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};

最佳答案

在 C++11 中,使该线程安全的是来自 draft C++11 standard 的以下内容6.7 部分 声明语句 说(强调我的):

The zero-initialization (8.5) of all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed before any other initialization takes place. [...] Otherwise such a variable is initialized 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. [...]

而 C++11 之前的部分 6.7 说:

[...]Otherwise such an object is initialized the first time control passes through its declaration; such an object 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.[...]

它没有 C++11 所具有的相同保证,因此它似乎是 C++11 之前未指定的,因此您不能指望它。尽管这并不妨碍实现做出更强有力的保证。

这是有道理的,因为 C++11 之前的内存模型不包括线程。

关于c++ - 正在为 C++11 之前的编译器返回线程安全的本地静态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27286444/

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