赋值顺序和初始化顺序? [英] Order of assignment vs order of initialization?

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

问题描述

以这个示例代码:

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


$ b b

可以用以下树抽象:

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 函数可以以任何顺序来评估,但是运算符是明确定义的。有一个有趣的关于序列点的帖子,其中描述的主题非常好。

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天全站免登陆