-5
#include <conio.h>
#include <iostream>
using namespace std;
class A {
    int i;
public:
    A(int i) : i(i) { cout << i << endl; }
    A(const A &o) : i(o.i) { cout << i << endl; }
    ~A() { cout << i << endl; }
    friend A f(const A &, A, A *);
};
A f(const A &a, A b, A *c) { return *c; }
int main() { 
    f(1, A(2), &A(3));
}

输出:1 3 2 3 2 3 3 1
有人可以帮我理解这个输出序列背后的原因吗?

4

1 回答 1

0

The order of the evaluation of the function arguments is not defined; they can constructed in any order.

As a demonstration of this, here is some empirical evidence of this.

I've made minor modifications to print the output on a single line, also showing the construction ctor, copy construction copy and destruction dtor of each A and removing the undefined behaviour of caused by the use of &A(3).

#include <conio.h>
#include <iostream>
using namespace std;
class A {
    int i;
public:
    A(int i) : i(i) { cout << "ctor" << i << " "; }
    A(const A &o) : i(o.i) { cout << "copy" << i << " "; }
    ~A() { cout << "dtor" << i << " "; }
    friend A f(const A &, A, A *);
};
void f(const A &a, A b, A&& c) { ; }
int main() { 
    f(1, A(2), A(3));
}

Using GCC 4.9, I get ctor3 ctor2 ctor1 dtor1 dtor2 dtor3.

Using MSVC 2013.2, I get ctor1 ctor3 ctor2 dtor2 dtor3 dtor1.


As an aside; IRC, the order in which they are destructed is the reverse of the order in which they are constructed.

于 2014-06-30T07:12:53.403 回答