拷贝构造函数

C++语言 码拜 9年前 (2016-04-02) 1214次浏览
#include <iostream>
#include <tr1/memory>
using namespace std;
class base
{
	public:
		base(int id): id(id){cout << "base() " << id << endl;}
		base(const base& b): id(b.id){cout << "base(const base& b) " << id << endl;}
		~base(){cout << "~base()" << endl;}
		base operator+(const base& b)
		{
			base tmp(0);
			tmp.id = id + b.id;
			return tmp;
		}
		void display(){cout << id << endl;}
	private:
		int id;
};
int main()
{
	base b1 = 1;
	base b2 = b1 + 2;
	b1.display();
	b2.display();
	return 0;
}

这段代码的输出为

base() 1
base() 2
base() 0
~base()
1
3
~base()
~base()

gcc 4.8.4
问一下 b2  是怎么样初始化的啊?还有就是加号重载函数的返回是值传递,没有调用拷贝构造函数吗?
ps 假如把重载函数改成

base& operator+(const base& b)
		{
			base tmp(0);
			tmp.id = id + b.id;
			return tmp;
		}

输出是:

base() 1
base() 2
base() 0
~base()
base(const base& b) 3
~base()
1
3
~base()
~base()
解决方案

20

编译的时候用了std=c++11么

40

单步类的实例“构造”或“复制”或“作为函数参数”或“作为函数返回值返回”或“参加各种运算”或“退出作用域”的语句对应的汇编代码几步后,就会来到该类的“构造函数”或“复制构造函数”或“运算符重载”或“析构函数”对应的C/C++源代码处。
VC调试时按Alt+8、Alt+7、Alt+6和Alt+5,打开汇编窗口、堆栈窗口、内存窗口和寄存器窗口看每句C对应的汇编、单步执行并观察相应堆栈、内存和寄存器变化,这样过一遍不就啥都明白了吗。
对VC来说,所谓‘调试时’就是编译连接通过以后,按F10或F11键单步执行一步以后的时候,或在某行按F9设了断点后按F5执行停在该断点处的时候。
ROV:http://www.programlife.net/cpp-return-value-optimization.html

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明拷贝构造函数
喜欢 (0)
[1034331897@qq.com]
分享 (0)