c++ 套路多

1. 浅拷贝带来的多次析构问题

参见:https://www.cnblogs.com/33debug/p/6657730.html

解决方案,深拷贝。强烈建议自定义拷贝构造函数为深拷贝,否则可能会给自己挖坑。

using namespace std;

MyString::MyString(char* ptr)
{
if (ptr == NULL)
{
_ptr = new char[1];
* _ptr = '';
}
else
{
_ptr = new char[strlen(ptr) + 1];
strcpy(_ptr, ptr);
}
cout << "MyString 1" << endl;
}

MyString::MyString(const MyString& str)
{
MyString tmpStr(str._ptr);
swap(_ptr, tmpStr._ptr);
cout << "MyString 2" << endl;
}

MyString::~MyString()
{
delete _ptr;
cout << "~MyString" << endl;
}

MyString& MyString::operator=(const MyString& s)
{
if (&s == this)
return *this;
MyString tmpStr(s._ptr);
swap(_ptr, tmpStr._ptr);
return *this;
}

原文地址:https://www.cnblogs.com/winstonet/p/10728365.html