gpt4 book ai didi

c++ - 具有 void 类型分支的三元运算符

转载 作者:可可西里 更新时间:2023-11-01 16:09:19 25 4
gpt4 key购买 nike

将三元运算符与返回 void 的函数一起使用是否安全?像这样:

void foo1(){}
void foo2(){}

//////////////

bool to_use_1 = ....;
to_use_1 ? foo1() : foo2();

编译器可以删除这段代码吗?假设它将这些函数视为纯函数,并执行删除这些调用的积极优化

最佳答案

首先,编译器将/不应在逻辑上“删除”任何具有可观察效果的调用( copy elision 除外)。无论优化模式多么激进,这都是不允许的事情。

C++ 标准实际上明确允许条件运算符的操作数的结果为 void,因此这是预期的且安全的。但是,它必须是两者

[C++14: 5.16/1]: 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++14: 5.16/2]: If either the second or the third operand has type void, one of the following shall hold:

  • The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (15.1); the result is of the type and value category of the other.

  • Both the second and the third operands have type void; the result is of type void and is a prvalue. [ Note: This includes the case where both operands are throw-expressions. —end note ]

从技术上讲,这个措辞(在其关于“值”的讨论中)并没有直接说明恰好第二个和第三个表达式之一被求值,即使这些求值没有“值” .但从分析的角度来看,这在本质上是无可争辩的。 可能需要在此处进行编辑改进。

请注意,这些都不能保证您的计算机在执行期间实际上跳转到foo1foo2;在你给出的具体例子中,编译器可以立即看到这两个函数都是空的,并优化掉整行代码。但这不会影响程序的语义,也不会特定于条件运算符的使用。

关于c++ - 具有 void 类型分支的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43190627/

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