Order of execution in operator <<

后端 未结 3 874
梦谈多话
梦谈多话 2020-11-29 12:18

I have difficulties in understanding the sequence of calls in the code below. I was expecting to see the output below

    A1B2

While I can

相关标签:
3条回答
  • 2020-11-29 12:51

    The compiler can evaluate the function printcbase() as this:

    void printcbase(cbase* b ){
        int a = b->FooA();    // line 1
        int b = b->FooB();    // line 2
        std::cout << a;       // line 3
        std::cout << b;       // line 4
        stc::cout << std::endl;
    }
    

    or some of many permutatins of lines marked as 1 - 4. You are only guaranteed that that the line 1 is done before the line 3, and line 2 before the line 4 (and of course line 3 before line 4). Standard does not say more and indeed you can expect different results with different C++ compilers.

    0 讨论(0)
  • 2020-11-29 12:58

    The order of execution of << is well defined but the order of evaluation of sub-expressions is not defined in C++. This article and the C code example illustrates the problem you mentioned.

    BA12 and AB12 are both correct. In the following code:

    std::cout<< b->fooA() << b->fooB()
    

    1 will appear before 2 but A could appear before or after B since the compiler does not promise whether it will evaluate fooA or fooB first.

    0 讨论(0)
  • 2020-11-29 12:58

    The shift operators are left-associative; a << b << c is read as (a << b) << c, meaning that if a is of a type with member user-defined operator<< (and returns that type) then the expression reads as a.operator<<(b).operator<<(c). If instead a free operator<< is used, then this reads as operator<<(operator<<(a, b), c).

    So the evaluation of a << b is sequenced before the evaluation of (a << b) << c, but there is no sequencing dependency between the evaluation of b and c:

    a << b << c[1]
    |         |
    a << b[2] |
    |    |    c[5]
    a[3] b[4]
    

    If we number the side-effects as above, then the side-effects can be sequenced as any of:

    54321
    53421
    45321
    43521
    43251
    35421
    34521
    34251
    
    0 讨论(0)
提交回复
热议问题