編譯器自動優化——爲什麼我的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)

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