天天看點

c++中的深複制和淺複制的了解

淺複制就是新舊兩個對象指向同一個外部内容,而淺複制是指為新的對象制作了外部對象的獨立複制。

如下代碼所示,如果在類中沒有定義複制構造函數,編譯器就會生成預設的複制構造函數,這個構造函數就是淺複制的作用,當代碼t2 = t1執行的時候,就會執行編譯器預設的構造函數。這裡預設的構造函數就是将t1中的buf的值也就是指向的位址,複制給了t2,是以代碼執行的時候兩個指針是相同的:

c++中的深複制和淺複制的了解

如果在類中添加上複制構造函數,并在構造函數中,從新為t2申請一個堆空間。将下面的代碼的注釋打開。在執行到t2 = t1;時會調用複制構造函數,使t2中的成員buf指向一個新的位址。。這樣的話,t1和t2中的成員buf指向的位址就不一樣。執行結果如下:

c++中的深複制和淺複制的了解
class test1
{
public:
	char *buf;
	test1(const char *str)
	{
		buf = new char[strlen(str) + 1];
		strcpy_s(buf, strlen(str) + 1, str);
	}
	/*
	test1(test1 &test)//copy constructor
	{
		buf = new char[strlen(test.buf) + 1];
		strcpy_s(buf, strlen(test.buf) + 1, test.buf);
	}*/
	~test1()
	{
		if (NULL != buf)
		{
			delete buf;
			buf = NULL;
			cout << "the class test1 deconstructor is called" << endl;
		}
	}
};

int main(int argc, char *argv[])
{
	test1 t1("hello word");
	test1 t2 = t1;

	cout << "(t1.buf == t2.buf) ?" << (t1.buf == t2.buf ? "yes" : "no") << endl;
	while (1);
	return 0;
}