c++ - 使用 C++11,写 f(x++)、g(x++) 是未定义的行为吗?

标签 c++ c++11 expression undefined-behavior

我正在阅读这个问题:

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/

相关文章:

c++ - 如何将构造函数参数转发给 boost::optional

c++ - std::random_device 在 g++ 中不工作

c# - 如何将此方法作为扩展方法添加到我的类的属性中?

c# - 如何使用 Linq 合并 Select 方法中的表达式

c++ - 临时对象的数据成员是 C++11 中的 xvalue 吗?

c++ - 复合表达式与表达式与子表达式

c++ - C++ 中的大括号语法和迭代器

c++ - 剥离 wxString 的字符

C++:const 的静态分析?

c++ - 让细节命名空间代码看不见 - 优雅