天天看点

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;
}