我们写的代码会被编译器拆分
看编译器怎么拆分的
显示初始化操作
例子
#include <iostream> using namespace std; class X { public: int m_i; X(const X& tmpx) { m_i = tmpx.m_i; cout << "拷贝构造函数被调用" << endl; } X() { m_i = 0; cout << "拷贝构造函数被调用" << endl; } }; int main() { X x0; x0.m_i = 15; X x1 = x0; X x2(x0); X x3 = (x0); }
程序员视角
X x0; x0.m_i = 15; X x1 = x0; X x2(x0); X x3 = (x0);
切换到编译器的角度
分为两步
以X x1 = x0;
为例子
第一步 定义一个对象,为对象分配内存。从编译器视角来看,这句是不调用x类的构造函数。
第二步 直接调用对象的拷贝构造函数去了
X x1; x1.X::X(x0)
参数初始化
#include <iostream> using namespace std; class X { public: int m_i; X(const X& tmpx) { m_i = tmpx.m_i; cout << "拷贝构造函数被调用" << endl; } X() { m_i = 0; cout << "构造函数被调用" << endl; } ~X() { cout << "析构函数被调用" << endl; } }; void func(X tempx) { return; } int main() { X x0; func(x0); }
程序员视角(现代编译器)
X x0; func(x0);
切换到编译器的角度(老编译器)
X _temp(); _temp.X::X(x0); func(_temp) _temp.X::~X();
返回值初始化
#include <iostream> using namespace std; class X { public: int m_i; X(const X& tmpx) { m_i = tmpx.m_i; cout << "拷贝构造函数被调用" << endl; } X() { m_i = 0; cout << "构造函数被调用" << endl; } ~X() { cout << "析构函数被调用" << endl; } }; X func() { X x0; return x0; } int main() { X my = func(); int abc; abc = 0; }
在老编译器中是这样的结果
切换到编译器的角度
X my; //不会调用X的构造函数 func(my); //编译器角度的func void function(X &extra) { X x0;//不调用X的构造函数 extra.X::X(x0); return; }