string的基本实现
实现string的构造,拷贝构造,赋值运算符重载,析构函数
class my_string
{
public:
my_string(const char* str = " ")
{
if (nullptr == str)
{
assert(false);
return;
}
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
my_string(const my_string& s)
:_str(new char[strlen(s._str) + 1])
{
strcpy(_str, s._str);
}
~my_string()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
注意事项:
1.构造函数传参时,系统给的默认缺省参数为空格;
2.对象为空时,程序非法,需要在构造函数时处理;
3.析构函数释放空间后,需要将指针置空,避免野指针的问题;
4.拷贝构造必须为深拷贝;
my_string& operator=(const my_string& s)
{
if (this != &s)
{
char* pstr = new char[strlen(s._str) + 1];
strcpy(pstr, s._str);
delete[] _str;
_str = pstr;
}
return *this;
}
赋值运算符重载:
1.还是深拷贝;
2.赋值时需要删除原来this指针的位置,换成新位置;
my_string(const my_string& s)
:_str(nullptr)
{
my_string strtmp(s._str);
swap(_str, strtmp);
}
my_string& operator=(my_string& s)
{
swap(_str, s._str);
reutrn *this;
}
这是一种现代写法,先利用中间变量构造初始化一段空间,拷到数据,然后与目标对象交换即可(目标对象必须初始化)