Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C++类构造优化 - 不调用拷贝构造函数

C++类构造优化 - 不调用拷贝构造函数假如有下面这样一个类: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");是等价的。《C++ 设计新思维》 下载见 http://www.linuxidc.com/Linux/2014-07/104850.htmC++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htm读C++ Primer 之构造函数陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm读C++ Primer 之智能指针 http://www.linuxidc.com/Linux/2011-08/40177.htm读C++ Primer 之句柄类 http://www.linuxidc.com/Linux/2011-08/40175.htm将C语言梳理一下,分布在以下10个章节中:
  1. Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成长之路(十):其他高级议题
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-09/107335.htm