我无法理解以下代码的输出。
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
};
class B : public A
{
public:
B() { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
};
class C : public B
{
public:
C() { cout << "C()" << endl; }
~C() { cout << "~C()" << endl; }
};
class D : public C
{
public:
D() { cout << "D()" << endl; }
~D() { cout << "~D()" << endl; }
};
const B& returnConstB(B& b) { return b; }
B returnB(B b) { return b; }
A returnA(A a) { return a; }
int main()
{
D d;
returnA(returnB(returnB(returnConstB(d))));
cin.get();
return 0;
}
首先,我在实例化对象d时调用了A,B,C,D构造函数。调用这几个函数后,输出如下:
~B()
~A()
~B()
~A()
~A()
~A()
~A()
~B()
~A()
~B()
~A()
我理解在按值传递参数并返回值时会涉及复制构造函数,但我不能完全理解在这种情况下这些对象何时何地被创建和销毁。提前谢谢!