gpt4 book ai didi

c++ - 魔术静力学保证右侧只执行一次吗?

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

如果我有

atomic<int> cnt=0;

int get_int() noexcept
{
cnt++;
return rand();
}

然后:

void func()
{
static const auto value = get_int();
}

我知道 value 的初始化不会有竞争条件,但我不知道是否get_int() 将被调用一次,或者在我的示例中,cnt 将为 1(而不是 2、3、4 或 5)。

假设多个线程进入func() 并且get_intfunc() 中只有1 个调用点。

最佳答案

C++11 保证不会出现竞争条件 N3797 - §6.7/4:

An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope (3.6.2). 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.92 If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined. [ Example:

int foo(int i) {
static int s = foo(2*i); // recursive call - undefined
return i+1;
}

- end example ]

它不是可重入的,而是线程安全的。确保代码的其他部分不会在 func() 之前调用 get_int()

关于c++ - 魔术静力学保证右侧只执行一次吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759511/

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