分配顺序与初始化顺序 [英] Order of assignment vs order of initialization

查看:102
本文介绍了分配顺序与初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下示例代码:

int a = 10;
int b = 20;
int c = 30;

int & foo1() {
    qDebug() << "foo1" << endl;
    return a;
}

int & foo2() {
    qDebug() << "foo2" << endl;
    return b;
}

int & foo3() {
    qDebug() << "foo3" << endl;
    return c;
}

int main(void)
{
    foo1() = foo2() = foo3() = 7;
}

由于分配从右到左,我希望首先看到foo3,最后看到foo1,但情况恰恰相反.

Since assignment goes right to left, I expected to see foo3 first and foo1 last, but it is the opposite.

是否具体定义了此类方案的规则?另外,编译器是否会在赋值运算符和其他运算符之间进行区分?如果在与初始化不同的上下文中使用=运算符,那又怎么可能呢?也许链分配与其他链的处理方式有所不同?

Are the rules for such scenarios concretely defined and how? Also, does the compiler differentiate between assignment and other operators and how would that be possible if you are using the = operator in a different context than initialization? Maybe chain assignment is treated differently from other chaining?

推荐答案

完整表达式

foo1() = foo2() = foo3() = 7

可以用下面的树来抽象:

can be abstracted with the following tree:

     =
   /   \
foo1()   = 
       /   \
    foo2()   =
           /   \
        foo3()   7

该树的叶子可以按任何顺序求值.您的编译器可以自由选择.仅对于调用赋值运算符,必​​须首先对挂在表达式上的表达式进行求值.在您的情况下,叶子将按foo1()foo2()foo3()的顺序进行评估.

The leaves of that tree can be evaluated in any order. Your compiler is free to choose. Only for calling the assignment operator the expressions hanging on them must be evaluated first. In your case the leaves get evaluated in the order foo1(), foo2() and then foo3().

=的从右到左的关联性仅在树的形状中可见,而在评估顺序中不可见.

The right to left associativity of = is only seen in the shape of the tree, but not in the order of evaluation. The tree for

std::cout << foo1() << foo2() << foo3()

看起来像

                   << 
                 /    \
              <<      foo3()
            /    \
         <<      foo2()
       /    \
std::cout   foo1()

同样,可以按任何顺序评估foo函数,但是operator<<()的评估顺序是明确定义的. 有关序列点的帖子有一个很好的描述主题.

Again the foo functions may be evaluated in any order, but the order of evaluations of the operator<<() is well-defined. There is an interesting post about sequence points which describes the topics very well.

这篇关于分配顺序与初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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