c++之拷貝構造函數的研究

代碼如下

#include <iostream>
#include <string>
using namespace std;

static int objectCount = 0;

class HowMany {
public:
	HowMany() {
		objectCount++;
		print("HowMany()");
	}
	void print(const string& msg = "") {
		if (msg.size() != 0)
			cout << msg << ": ";
		cout << "objectCount = " 
			 << objectCount << endl;
	}
	~HowMany() {
		objectCount--;
		print("~HowMany()");
	}
};

HowMany f(HowMany x) {
	cout << "begin of f" << endl;
	x.print("x argument inside f()");
	cout << "end of f" << endl;
	return x;
}

int main() {
	HowMany h;
	h.print("after construction of h");
	HowMany h2= f(h);
	h.print("after call to f()");
	return 0;
}

輸出




輸出分析

對象h創建時調用了HowMany的構造函數HowMany(),實現了objectCount++;

但是在調用f()函數是傳遞對象h作爲參數卻沒有調用構造函數,但是在對象消亡是調用了析構函數~HowMany();

最後在程序結束時銷燬對象h,h2時調用了兩次析構函數,objectCount變成了-2;


發現問題

通過查閱資料才恍然大悟,在調用f()函數是確實是要創建對象,也要調用構造函數,不然是不會調用析構函數的,

但是這種傳值的方式爲對象賦值,即拷貝的形式傳遞的;後面的

HowMany h2= f(h);

原理也是一樣;

解決辦法

增加一個拷貝構造函數:

HowMany(HowMany& x) {
		objectCount++;
		print("HowMany()");
}

輸出



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