#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默认构造2,g默认构造4
return b;//c复制构造3,d析构2,h复制构造5,i析构4
}
int main()
{
Base b1;//a默认构造1
b1 = Test();//e赋值操作符1=3,f析构3
Base c(Test());//5,c直接使用了函数的返回值对象
std::cout << c.selfid << endl;
//析构5,析构1
return 0;//k析构1
}
可以看出函数返回值有时候并没有复制构造对象,有时候复制构造了对象,编译器总是会优化。这是Debug的版本,Release版本优化的更厉害