编译器自动优化——为什么我的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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章