MOOC清华《面向对象程序设计》第3章:移动构造函数实验

#include <iostream>
using namespace std;

class Test{
public:
	int* buf;  //only for demo 
	Test(){
		buf = new int(3);
		cout << "Test():this->buf@" << hex << buf << endl;
	}
	~Test(){
		cout << "~Test():this->buf@" << hex << buf << endl;
		if(buf) delete buf;
	}
	Test(const Test& t):buf(new int(*t.buf)){
		cout << "Test(const Test&) called. this->buf@" << hex << buf << endl;
	}
	Test(Test&& t):buf(t.buf){
		cout << "Test(Test&&) called. this->buf@" << hex << buf << endl;
		t.buf = nullptr;
	}
};

Test GetTemp(){
	Test tmp;
	cout << "GetTemp():tmp.buf@" << hex << tmp.buf << endl;
	return tmp; 
}

void fun(Test t){
	cout << "fun(Test t):t.buf@" << hex << t.buf << endl;
}

int main(){
	Test a = GetTemp();
	cout << "main():a.buf@" << hex << a.buf << endl;
	fun(a);
	return 0;
}

当编译选项只有 -std=c++11 时的运行结果:


可见移动构造函数并没有被调用。原因是编译器自动做了返回值优化。需要增加一条编译选项:-fno-elide-constructors ,见下图(Dev C++ 5.11):



当这条编译选项也被加进去之后,再次编译运行,结果如下:


可以看见移动构造函数已经被调用。


若在源代码中去掉移动构造函数,而编译选项依然是上述两条语句时,编译运行结果为:


发现拷贝构造函数顶替了移动构造函数的调用位置,但是拷贝构造函数中 buf 的地址并不是GetTemp()函数中 buf 的地址。也就是说 临时变量 tmp 的值并没有被保存下来,由此可见移动构造函数的独特作用,是拷贝构造函数代替不了的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值