概念图
传统写法
class String
{
public:
String(const char * s = " ")
{
_str = new char[strlen(s) + 1];
strcpy(_str, s);
cout << "默认构造" << endl;
}
String(const String & s)
:_str(nullptr)
{
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
cout << "传统拷贝构造" << endl;
}
String & operator= (const String & s)
{
if (&s != this)
{
delete[] _str;
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
cout << "传统赋值运算符重载" << endl;
}
return *this;
}
~String()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char * _str;
};
现代写法
namespace cola
{
class String
{
public:
String(const char * s = " ")
{
_str = new char[strlen(s) + 1];
strcpy(_str, s);
cout << "默认构造" << endl;
}
String(const String & s)
:_str(nullptr)
{
cout << "现代拷贝构造" << endl;
String tmp(s._str);
swap(_str, tmp._str);
}
String & operator= (const String & s)
{
if (this != &s)
{
cout << "现代赋值运算符重载" << endl;
String tmp(s);
swap(_str, tmp._str);
}
return *this;
}
~String()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char * _str;
};
}