编译器自动优化——为什么我的C++编译器不调用拷贝构造函数了?

今天在学习《深入理解C++11》中关于移动构造函数的内容时,发现了这么一个问题:

#include <iostream>
#include <vector>
#include <numeric>
#include <stack>
#include <string>
#include <bitset>
using namespace std;
class HasPtrMem
{
public:
	HasPtrMem() :d(new int{0}) {
		cout << "Constrcut" << ++n_cstr << endl;
	}
	HasPtrMem(const HasPtrMem & h) :d(new int(*h.d)) {
		cout << "copy Constrcut" << ++n_cptr << endl;
	}
	/*HasPtrMem(HasPtrMem && h) :d(h.d) {
		h.d = nullptr;
		cout << "move Constrcut" << ++n_mvtr << endl;
	}*/
	~HasPtrMem() {
		delete d;
		cout << "destruct : " << ++n_dstr << endl;
	}

	int *d;
	static int n_cstr;
	static int n_dstr;
	static int n_cptr;
	//static int n_mvtr;
};

int HasPtrMem::n_cstr = 0;
int HasPtrMem::n_dstr = 0;
int HasPtrMem::n_cptr = 0;
//int HasPtrMem::n_mvtr = 0;

HasPtrMem GetTemp() {
	//HasPtrMem h;
	//cout << "Resource from " << __func__ << ": " << hex << h.d << endl;
	//return h;
	return HasPtrMem();
}

int main() {
	HasPtrMem a = GetTemp();
	
	//cout << "Resource from " << __func__ << ": " << hex << a.d << endl;
	system("pause");
	return 0;
}

这段代码在我的Visual studio2015中并不输出拷贝构造函数的调用,让我百思不得其解,后来通过搜集网上资料得知,是因为编译器自动优化了临时对象的传递,因此将不会调用copy constructor(生成了默认的移动构造函数   ref:深入理解C++11p83)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值