gpt4 book ai didi

C++ 线程安全的静态构造函数

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

给定:

void getBlah() {
static Blah* blah = new Blah();
return blah;
}

在多线程设置中,是否可能多次调用 new Blah()?

谢谢!

最佳答案

C++ 标准不保证静态初始化的线程安全 - 您应该将静态初始化视为需要显式同步。

Alexander Gessler 的引述:

If control enters the declaration concurrently while the object is being initialized, the concurrent execution shall wait for completion of the initialization

来自 C++0x 草案,并不反射(reflect)当前的 C++ 标准或许多 C++ 编译器的行为。

在当前的 C++ 标准中,该段内容如下:

If control re-enters the declaration (recursively) while the object is being initialized, the behaviour is undefined

关于C++ 线程安全的静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2280630/

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