gpt4 book ai didi

c++ - bool的bitwise "and"能保证不短路吗?

转载 作者:行者123 更新时间:2023-11-27 23:41:52 26 4
gpt4 key购买 nike

我最近遇到了一个看起来像这样的代码片段:

bool MyClass::do_work()
{
bool success = true;
for (auto const& worker : m_workers)
{
success &= worker.do_work(); // worker.do_work() returns a bool
}
return success;
}

如果我理解正确,如果所有工作人员返回 true,函数返回 true,如果任何工作人员返回 false,函数返回 false。但是,它总是评估所有 worker (这是需要的)。不涉及短路评估,因为使用了按位运算符 &= 而不是逻辑运算符 &&

这种行为有保证吗?确切地说,是否保证按位 & 总是计算两个操作数,即使它们是 bool 类型?我遇到了很多关于 && 的保证短路评估的 SO 答案,但没有一个回答说 & 有保证的非短路评估。

如果保证了这种行为,这是一种好的编程风格吗?我只是快速浏览了一下就理解了这个函数,因为我以前没有见过这种风格,一开始我很困惑是否涉及短路评估。

是否有比以下更好的选择?

bool MyClass::do_work()
{
bool success = true;
for (auto const& worker : m_workers)
{
if (!worker.do_work())
{
success = false;
}
}
return success;
}

最佳答案

除非标准明确指定,否则在 C++ 中运算符的所有操作数都被评估和取消排序1:

[intro.execution]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. [...]

我想到的仅有的三个异常(exception)是 &&||?: 运算符2.

标准甚至提到 &&3 :

[expr.log.and]

Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

至于这是否是好的编程风格,这是基于意见的。


1 Unsequenced 基本上意味着如果您有 A @B(其中 @ 是运算符),B (及其副作用)可以在 A 之前求值,这就是为什么构造如 i++ + ++i are undefined behavior 的原因.

2 请注意,对于重载的 &&|| 运算符,这不再正确,因为两个操作数都被评估了。 ?: 不能重载。

3 [expr.log.or] 中的 | 也有类似的注释.

关于c++ - bool的bitwise "and"能保证不短路吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54093421/

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