三元运算符是否以定义的方式短路

Does the ternary operator short circuit in a defined way

如果您有以下情况:

if (x)
{
    y = *x;
}
else
{
    y = 0;
}

然后保证定义行为,因为我们只能取消引用 x 如果它不是 0

同样适用于:

y = (x) ? *x : 0;

这似乎按预期工作(甚至在 g++ 上用 -Wpedantic 编译)

这个有保障吗?

是的,只有第二个或第三个操作数会被评估,草案C++标准部分5.16 [expr.cond]说:

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.