程序员人生 网站导航

C++类构造优化 - 不调用拷贝构造函数

栏目:php开源时间:2014-09-30 05:40:55
假如有下面这样一个类:
class A{ public: A(int p, char q):x(p), c(q){ cout << "constructor called" << endl; } A(const A& a){x = a.x; c = a.c; cout << "copy constructor called" << endl;} ~A(){cout << "destructor called" << endl;} private: int x; char c; };
如果按照下面的语句生成对象a:

A a = A(1,'a');
按照预想会先调用自定义构造函数生成临时对象,而后调用拷贝构造函数,最后会发生两次析构。

但是,实际上上述代码经优化后只调用构造函数A(int,char),并不调用拷贝函数,而且只发生一次析构。
即A a = A(1,'a');与A a(1,'a');是等价的。
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐