关于C++的拷贝
构造函数和赋值构造函数,有如下代码:
#include "stdafx.h"
class CTest
{
public:
	CTest(){};
	CTest(const CTest &test);
	CTest& operator=(const CTest &test);
public:
	int a;
};
CTest::CTest(const CTest &test)
{
	// 1
	this->a = test.a;
	
	// 2
	*this = test;
}
CTest& CTest::operator=(const CTest &test)
{
	if (&test == this)
		return *this;
	// 3
	*this = test;
	return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
	CTest test1;
	test1.a = 10;
	CTest *pTest = new CTest(test1);
	delete pTest;
	// 4
	CTest test2 = test1;
	// 5
	CTest test3;
	test3 = test1;
	return 0;
}
在拷贝构造函数和赋值构造函数中不能直接使用代码中的*this = test这样的方式进行值的拷贝,因为这样会引起循环调用operator=,从而导致
堆栈溢出。应该将参数中的test中的数据拷贝过来:
this->a = test.a;
return *this;
另外代码4处的方式并不会引起赋值构造函数的调用,而5处的代码则会调用赋值构造函数。