我正在使用 C++ 原子重构一些代码。代码如下所示:
std::atomic<bool> someFlag{}; // This can be set to true using a public method
// ...
const bool cond1 { someFunction() };
const bool cond2 { otherFunction() };
if (someFlag.load())
{
someFlage.store(false);
if (cond1 && cond2)
{
performSomeAction();
}
}
Run Code Online (Sandbox Code Playgroud)
我目前正计划if像这样重写语句:
if (std::atomic_exchange(&someFlag, false) &&
cond1 && cond2)
{
performSomeAction();
}
Run Code Online (Sandbox Code Playgroud)
极其重要的是,在此if语句之后,someFlag变量设置为false。因此,我想,以确保调用atomic_exchange总是发生,无论价值cond1和cond2。无论优化设置如何,布尔表达式都是从左到右计算的,我能保证会是这种情况吗?