C ++,三元运算符操作数评估规则 [英] C++, ternary operator operand evaluation rules
问题描述
假设我有以下代码:
std::vector<T> R;
if (condition) R = generate();
...
for (int i = 0; i < N; ++i) {
const auto &r = (R.empty() ? generate() : R);
}
看起来无论 R,generate都被调用。 empty()
。是标准行为吗?
It appears that generate is called regardless of R.empty()
. Is that standard behavior?
推荐答案
从C ++ 11标准的第5.16 / 1节:
From Paragraph 5.16/1 of the C++ 11 Standard:
条件表达式从右到左。第一个表达式被上下文转换为bool(第4条)。它被计算,如果它是真的,条件表达式的结果是第二个表达式的值,否则第三个表达式的值。 仅评估第二个和第三个表达式中的一个。与第一表达式相关联的每个值计算和副作用在与第二或第三表达式相关联的每个值计算和副作用之前被排序。
Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.
这篇关于C ++,三元运算符操作数评估规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!