深拷贝、浅拷贝的问题出现在:当一个自定义类中出现指针成员时。
考虑一个类myCopy:
#include <iostream>
using namespace std;
class myCopy
{
private:
int len;
char * name;
public:
myCopy(int l, char* n)
{
len = l;
name = new char[len];
strcpy(name, n);
cout << "constructor called" << endl;
}
~myCopy()
{
delete name;
cout << "destructor called" << endl;
}
};
int main()
{
int len = 6;
char *n = "hello";
myCopy c1(len, n);
myCopy c2 = c1;
cout << "ready to call destructor..." << endl;
return 0;
}
上面c2 = c1 (把c1复制给c2)是没问题的,因为即便我们没有定义拷贝构造函数,编译器会自动call默认的拷贝构造函数,只不过默认的拷贝构造是浅拷贝:意思是c1在内存中的“hello"并没有真的拷贝一份给c2,只不过是让c2的name指针也指向了c1的“hello", 所以结果就是内存中只有一个”hello",而却又两个指针指向这个内容。
运行结果为:
constructor called
ready to call destructor...
destructor called
*** Error in `/home/fyj/Desktop/cpp/learn/test/Debug/test': double free or corruption (fasttop): 0x0000000000fb5c20 ***
有两个指针,但最后只有一个指针被析构,所有显示错误。
改正方法就是我们自己写一个拷贝构造函数,让“hello"真正地被拷贝一份给c2。
在类中增加:
myCopy(const myCopy& c)
{
len = c.len;
name = new char[len];
strcpy(name, c.name);
}
这样就有两个name指针,各自指向两块”hello"内存,避免问题:
constructor called
ready to call destructor...
destructor called
destructor called