//浅拷贝
class String {
public:
String(const char* s = "")
{
if (NULL == s) {
_pStr = new char[1];
*_pStr = '\0';
}
else {
_pStr = new char[strlen(s) + 1];
strcpy(_pStr, s);
}
}
String(const String& s)
{
_pStr = s._pStr;
}
String& operator=(const String& s)
{
if (this != &s) {
_pStr = s._pStr;
}
return *this;
}
~String()
{
if (NULL != _pStr) {
delete[] _pStr;
_pStr = NULL;
}
}
private:
char* _pStr;
};
//深拷贝
class String {
public:
String(const char* s = "")
{
if (NULL == s) {
_pStr = new char[1];
*_pStr = '\0';
}
else {
_pStr = new char[strlen(s) + 1];
strcpy(_pStr, s);
}
}
String(const String& s) : _pStr(new char[strlen(s._pStr) + 1])
{
strcpy(_pStr, s._pStr);
}
String& operator=(const String& s)
{
if (this != &s) { //先申请空间将s的内容拷贝到一个临时变量再去释放原有的空间
char* temp = new char[strlen(s._pStr) + 1];//防止申请空间失败连原有的空间都没了
strcpy(temp, s._pStr);
delete[] _pStr;
_pStr = NULL;
_pStr = temp;
}
return *this;
}
~String()
{
if (NULL != _pStr) {
delete[] _pStr;
_pStr = NULL;
}
}
private:
char* _pStr;
};
//浅拷贝优化--带有计数版本的String类,用指针指向计数的空间
class String {
public:
String(const char* s = "") : _pCount(new int(1))
{
if (NULL == s) {
_pStr = new char[1];
*_pStr = '\0';
}
else {
_pStr = new char[strlen(s) + 1];
strcpy(_pStr, s);
}
}
String(const String& s)
{
_pStr = s._pStr;
_pCount = s._pCount;
(*_pCount)++;
}
String& operator=(const String& s)
{
if (this != &s) {
if (--(*_pCount) == 0) {
delete[] _pStr;
delete _pCount;
}
_pStr = s._pStr;
_pCount = s._pCount;
(*_pCount)++;
}
return *this;
}
~String()
{
if (NULL != _pStr && --(*_pCount) == 0) {
delete[] _pStr;
delete _pCount;
}
_pCount = NULL;
_pStr = NULL;
}
private:
char* _pStr;
int* _pCount;
};
//深拷贝的简洁写法
class String {
public:
String(const char* s = "")
{
if (NULL == s) {
_pStr = new char[1];
*_pStr = '\0';
}
else {
_pStr = new char[strlen(s) + 1];
strcpy(_pStr, s);
}
}
String(String& s) :_pStr(NULL)//必须对_pStr初始化,防止释放随机值的空间
{
String temp(s._pStr);
swap(_pStr, temp._pStr);
}
String& operator=(String& s)
{
if (this != &s) {
swap(_pStr, s._pStr);
}
return *this;
}
~String()
{
if (NULL != _pStr) {
delete[] _pStr;
_pStr = NULL;
}
}
private:
char* _pStr;
};
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有