看代码吧!
#include <iostream>
using namespace std;
class CDemo
{
public:
CDemo(const CDemo & rcd)
{
cout << "Copy constructor: " << &rcd << "->" << this << endl;
}
CDemo()
{
cout << "Default constructor: " << this << endl;
}
CDemo &operator=(const CDemo & rcd)
{
cout << "Assignment operator: " << &rcd << "->" << this << endl;
return *this;
}
CDemo::~CDemo()
{
cout << "Destructor: " << this << endl;
}
};
CDemo foo()
{
cout << "In foo" << endl;
CDemo cd;
cout << "cd is: " << &cd << endl;
// Return a copy of cd.
return cd;
}
int main()
{
CDemo cd2; // 默认构造
cd2 = foo(); // 依次经历一次默认构造,一次拷贝构造(构造返回时的临时对象),一次赋值
cout << "cd2 is: " << &cd2 << endl << endl;
CDemo cd1 = foo();
// 经历了一次构造和一次拷贝构造过程,这里好像不存在拷贝构造返回的临时对象的过程,
//其实并非如此.由于编译器的优化,对象被直接构造在了cd1的缓冲区上.
cout << "cd1 is: " << &cd1 << endl << endl;
const CDemo& rcd = foo();
//这里同样也存在拷贝构造返回时的临时对象的过程,但是,与1中不同的是,该临时对象没
//有马上释放,而是直到main函数返回时才释放.这是为什么呢?其实,这是由const reference
//的特性导致的,C++标准规定, 如果一个临时对象被赋值给一个(常量)引用,这个临时对象在
//这个(常量)引用的生命周期中将不能被销毁(C++标准只规定了对const reference是这样的,
//对于普通的reference,虽然可能也是如此,但并不安全).
cout << "Return from main!" << endl;
return 0;
}
运行结果:
Default constructor: 0012FF70
In foo
Default constructor: 0012FEEC
cd is: 0012FEEC
Copy constructor: 0012FEEC->0012FF60
Destructor: 0012FEEC
Assignment operator: 0012FF60->0012FF70
Destructor: 0012FF60
cd2 is: 0012FF70
In foo
Default constructor: 0012FEEC
cd is: 0012FEEC
Copy constructor: 0012FEEC->0012FF6C
Destructor: 0012FEEC
cd1 is: 0012FF6C
In foo
Default constructor: 0012FEEC
cd is: 0012FEEC
Copy constructor: 0012FEEC->0012FF64
Destructor: 0012FEEC
Return from main!
Destructor: 0012FF64
Destructor: 0012FF6C
Destructor: 0012FF70
Press any key to continue