浅复制是在复制这个对象的时候,让新旧对象指向同一个外部内容。
深复制是在复制这个对象的时候,为新对象制作了外部对象的独立复制。
浅复制的问题
#include <iostream>
#include <string.h>
using namespace std;
class Test
{
public:
char *buf;
Test()
{
buf = NULL;
}
Test(const char *str)
{
buf = new char[strlen(str) + 1];
strcpy(buf, str);
};
// Test(Test &test)
// {
// cout << "copy create" << endl;
// buf = new char[strlen(test.buf) + 1];
// strcpy(buf, test.buf);
// }
virtual ~Test()
{
if (buf != NULL)
{
cout << "free Test" << endl;
delete buf;
buf = NULL;
}
}
};
int main(int argc, char const *argv[])
{
Test t1("hello");
Test t2 = t1;
cout << t1.buf << endl;
cout << t2.buf << endl;
cout << "t1.buf == t2.buf ? " << (t1.buf == t2.buf? "yes" : "no") << endl;
return 0;
}
发生错误,运行结果是
hello
hello
t1.buf == t2.buf ? yes
free Test
free Test
*** Error in `/home/yangju/test/c++/deepcopy': double free or corruption (fasttop): 0x0000000002541c20 ***
在默认复制构造函数中,t1.buf和t2.buf指向同一个地址,在析构的时候free了两次,发生问题。对于这样的问题。需要用深复制
深复制代码如下:
#include <iostream>
#include <string.h>
using namespace std;
class Test
{
public:
char *buf;
Test()
{
buf = NULL;
}
Test(const char *str)
{
buf = new char[strlen(str) + 1];
strcpy(buf, str);
};
Test(Test &test)
{
cout << "copy create" << endl;
buf = new char[strlen(test.buf) + 1];
strcpy(buf, test.buf);
}
virtual ~Test()
{
if (buf != NULL)
{
cout << "free Test" << endl;
delete buf;
buf = NULL;
}
}
};
int main(int argc, char const *argv[])
{
Test t1("hello");
Test t2 = t1;
cout << t1.buf << endl;
cout << t2.buf << endl;
cout << "t1.buf == t2.buf ? " << (t1.buf == t2.buf? "yes" : "no") << endl;
return 0;
}
运行结果如下:
copy create
hello
hello
t1.buf == t2.buf ? no
free Test
free Test
[Finished in 0.4s]