在C ++中的链调用中的评价顺序 [英] Order of evaluation in chain invocation in C++

查看:163
本文介绍了在C ++中的链调用中的评价顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有类 A

  
public:
A& func1(int){return * this; }
A& func2(int){return * this; }
};

和2个独立功能:

  int func3(); 
int func4();

现在在此代码中:

  A a; 
a.func1(func3()).func2(func4());

是函数的求值顺序 func3() func4()已定义?



根据此回答未定义的行为和序列点,其中一个序列点是:




  • 在函数调用时(无论函数是否为内联函数),在执行函数体中的任何表达式或语句之前,对
    执行的所有函数参数(如果有) code>§1.9/ 17 )。



<平均值, func3()必须在 func4()之前调用作为 func1 )参数必须在调用 func2()之前发生?

解决方案

它的要点是在函数调用中, X(Y,Z);不确定地评估所有 X Y Z 相对于彼此排序。唯一的顺序是: Y Z 顺序 X 评估为



假设我们有:

  typedef void(* fptr)(int,double); 
fptr a();
int b();
double c();

a()(b(),c());

三个函数 a b c 可以按任何顺序调用。当然,这一切都适用于任何子表达式。


Let's say we have class A:

class A {
public:
    A& func1( int ) { return *this; }
    A& func2( int ) { return *this; }
};

and 2 standlone functions:

int func3();
int func4();

now in this code:

A a;
a.func1( func3() ).func2( func4() );

is order of evaluation of functions func3() and func4() defined?

According to this answer Undefined behavior and sequence points one of the sequence points are:

  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

So does "evaluation of all function arguments" mean, func3() has to be called before func4() as evaluation of func1() arguments has to happen before call of func2()?

解决方案

The gist of it is that in a function call, X(Y, Z) ; evaluation of all of X, Y, Z are indeterminately sequenced with respect to each other. The only sequencing is that Y and Z are sequenced-before the call to the function which X evaluated to.

Suppose we have:

typedef void (*fptr)(int, double);
fptr a();
int b();
double c();

a()(b(), c());

The three functions a, b, c may be called in any order. Of course this all applies recursively to any sub-expressions.

这篇关于在C ++中的链调用中的评价顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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