深拷贝实现
class mystring
{
public:
mystring(const char* str = "") {
_str = new char[strlen(str) + 1];
strcpy(_str, str);
cout << "构造" << endl;
}
mystring(const mystring& s)
:_str(new char[strlen(s._str) + 1])
{
strcpy(_str, s._str);
cout << "拷贝" << endl;
}
mystring& operator=(const mystring& s) {
if (this != &s){
char* tmp = new char[strlen(s._str) + 1];
strcpy(tmp, s._str);
delete[] _str;
_str = tmp;
}
cout << "赋值" << endl;
return *this;
}
~mystring() {
if (_str) {
delete[] _str;
_str = nullptr;
}
cout << "析构" << endl;
}
const char* c_str() const {
return _str;
}
private:
char* _str;
};