#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base() :selfid(++n) {cout << "Base() " << selfid << endl;}
Base(const Base& other) :selfid(++n){cout << "Base(" << selfid << ") copy from " << other.selfid << endl;}
Base& operator=(const Base& other){ cout << "Base(" << selfid << ") = " << other.selfid << endl; return *this;}
virtual ~Base(){cout << "~Base(" << selfid << ") destroyed" << endl;}
public:
int selfid;
static int n;
};
int Base::n = 0;
Base Test()
{
Base b;//b Base() 2 e Base() 3
return b;
}
int main()
{
Base b1;//a Base() 1
b1 = Test();//c Base(1) = 2,d ~Base(2) destroyed
Base c(Test());//3
std::cout << c.selfid << endl;
//f ~Base(3) destroyed ,~Base(1) destroyed
return 0;
}
可以看出在函数第二次调用图Test()来构造c的时候,整个过程只构造了一个对象。优化的还是很厉害的。