我正在阅读这个问题:
Undefined behavior and sequence points
特别是 C++11 answer ,并且我理解评估“排序”的想法。但是——我写的时候有没有足够的顺序:
f(x++), g(x++);
?
也就是说,我是否保证 f()
获得 x
的原始值,而 g()
获得一次递增的 x
?
吹毛求疵者的注意事项:
- 假设
operator++()
已经定义了行为(即使我们已经覆盖了它),f()
和g()
也是如此>,不会抛出异常,等等 - 这个问题与此无关。 - 假设
operator,()
没有被重载。
最佳答案
不,行为已定义。引用 C++11 (n3337) [expr.comma/1] :
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause [expr]). Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression.
我将“每个”理解为“每个”1。在对 f
的调用序列完成并且 f
返回之前,不能对第二个 x++
进行评估。2
<子>
1 析构函数调用不与子表达式相关联,仅与完整表达式相关联。因此,您会在完整表达式的末尾看到与临时对象创建相反的顺序执行。
2 本段仅适用于用作运算符时的逗号。当逗号具有特殊含义时(例如在指定函数调用参数序列时),这不适用。
关于c++ - 使用 C++11,写 f(x++)、g(x++) 是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45815301/