代码之家  ›  专栏  ›  技术社区  ›  namezero

C++的行为/执行顺序

  •  1
  • namezero  · 技术社区  · 6 年前

    我在看一些 example questions 关于CPP协会的CPA-21-01考试,我对第11题有点困惑。 它声明如下:

    以下程序的输出是什么?

    #include <iostream>
    
    using namespace std;
    
    class A {
    public:
        A() {
            a.a = a.b = 1;
        }
        struct { int a,b; } a;
        int b(void);
    };
    
    int A::b(void)
    {
        int x=a.a;
        a.a=a.b;
        a.b=x;
        return x;
    }
    
    int main(void) {
        A a;
        a.a.a = 0;
        a.b();
        cout << a.b() << a.a.b << endl;
    
        return 0;
    }
    

    A.该程序将导致编译错误

    C.01

    D.11

    这可以归结为一个更简单的例子:

    int swap_and_return(int& a, int& b) {
        std::swap(a,b);
        return a;
    }
    
    int main() {
    
        int a = 0;
        int b = 1;
    
        cout << swap_and_return(a,b) << a << endl;
    
        return 0;
    }
    

    到现在为止,一直都还不错;答案是B。

    假设你选择D。

    根据 this ,执行顺序是任意的:

    已经有一个类似的问题 here

    我认为这句话可以翻译成 cout.operator<<(a.b()).operator<<(a.a.b); ,这意味着应该有一个序列点,行为应该是确定性的?

    在实践中,获得了以下结果:

    MS cl.exe,调试:10

    MS cl.exe,发布日期:11

    GCC, C++11 : 11

    Clang

    不用说,我现在有点困惑,因为他们说这是答案B,而实际上执行顺序是任意的。

    谢谢

    1 回复  |  直到 6 年前
        1
  •  4
  •   Lightness Races in Orbit    6 年前

    在C++17之前,您是对的,并且测验不允许给出正确答案。

    the answer is deterministic .