序列点和方法链 [英] Sequence Points and Method Chaining

查看:88
本文介绍了序列点和方法链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下表达式通常用于演示未定义未指定的行为:

The following expression is often used to demonstrate undefined unspecified behaviour:

f() + g()

如果 f() g()都对一些共享对象有副作用,则行为是 undefined 未指定,因为执行顺序未知。 f()可以在 g()之前进行计算,反之亦然。

If f() and g() both have side effects on some shared object then the behaviour is undefined unspecified because the order of execution is unknown. f() may be evaluated before g() or vice versa.

现在我想知道当你在一个对象上链成员函数时会发生什么。假设我有一个类的实例,实例名为 obj ,它有两个成员函数 foo() bar(),它们都修改了对象。这些函数的执行顺序不是可交换的。调用一个在另一个之前的效果不是相同的效果,以相反的方式调用他们。两个方法都返回一个引用 * this ,以便它们可以这样链接:

Now I was wondering what happens when you chain member functions on an object. Let's say I have an instance of a class, the instance called obj and it has two member functions, foo() and bar() which both modify the object. The order of execution of these functions is not commutative. The effect of calling one before the other is not the same effect as calling them the other way around. Both methods return a reference to *this so that they can be chained like so:

obj.foo().bar()

但是这个未指定的行为?我找不到任何标准(诚然只是扫描通过),以区分这个表达式和我在顶部的表达式。这两个函数调用都是full-expression的子表达式,因此它们的执行顺序未指定。但必须首先评估 foo() 必须,以便 bar()知道哪个对象修改。

But is this unspecified behaviour? I can't find anything in the standard (admittedly just scanning through) that differentiates between this expression and the expression I gave at the top of the post. Both function calls are subexpressions of the full-expression and so their order of execution is unspecified. But surely foo() must be evaluated first so that bar() knows which object to modify.

也许我错过了一些明显的东西,但我看不到序列点的创建位置。

Perhaps I'm missing something obvious, but I can't see where a sequence point is created.

推荐答案

f() + g()

这里的行为是未指定(不是未定义),因为每个操作数的求值顺序)是未指定的。

Here the behavior is unspecified (not undefined), because the order in which each operand is evaluated (that is, each function is called) is unspecified.

 obj.foo().bar();

这是在C ++中定义的。

This is well-defined in C++.

相关段落§1.9.17从C ++ ISO标准读取

The relevant section §1.9.17 from the C++ ISO standard reads,


当调用函数函数是inline的),在执行之前发生的所有函数参数(如果有的话)
之后有


函数体中的任何表达式或语句
。在复制
返回值之后还有一个
序列点,而在
之前执行
之外的任何表达式的,函数

When calling a function (whether or not the function is inline), there is a sequence point after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body. There is also a sequence point after the copying of a returned value and before the execution of any expressions outside the function.

类似的情况已在以下主题中详细讨论:

Similar cases has been discussed in great detail, in these topics:

  • Undefined Behavior and Sequence Points Reloaded
  • Is this code well-defined?

这篇关于序列点和方法链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆