string的模拟实现
当我们在自己实现一个简单的string类时,有时我们可能只有构造和析构函数,而没有实现自己的拷贝构造函数,而编译器自身给我们提供的拷贝构造函数,只能完成值拷贝,及两个对象中的地址公用同一块空间,就会发生同一块内存连续被多次释放,从而出现问题,如下程序所示。
namespace SDK
{
class string
{
public:
string(const char* s = "")
{
_str = new char[strlen(s) + 1];
strcpy(_str, s);
}
char* c_str()
{
return _str;
}
~string()
{
if (_str != nullptr)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
}
int main()
{
SDK::string a("hello world");
SDK::string b(a);
cout << a.c_str() << endl;
cout << b.c_str() << endl;
return 0;
}
2、完整版的sting类
namespace SDK
{
class string
{
public:
string(const char* s = "")
{
_str = new char[strlen(s) + 1];
strcpy(_str, s);
}
string(const string& s) : _str(new char[strlen(s._str) + 1])
{
strcpy(_str, s._str);
}
string& operator=(const string& s)
{
if (this != &s)
{
char* pStr = new char[strlen(s._str) + 1];
strcpy(pStr, s._str);
delete[] _str;
_str = pStr;
}
return *this;
}
char* c_str()
{
return _str;
}
~string()
{
if (_str != nullptr)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
}
int main()
{
SDK::string a("hello world");
SDK::string b(a);
b = "2021-7-28";
cout << a.c_str() << endl;
cout << b.c_str() << endl;
return 0;
}