浅拷贝,深拷贝,简洁版的深拷贝,浅拷贝的优化版(引用计数)

#include<iostream>
class String
{
private:
char*_pStr;
public:
String(const char*pStr==' ')
{
if(NULL==pStr)
{
_pStr=new char[1];
*_pStr='\0';
}
else
{
_pStr=new char[strlen(pStr0+1];
strcpy(_pStr,pStr);
}
}
//浅拷贝
String(const String&s)
:_pStr(s._pStr)
{}
String &operator=(const String &s)
{
if(_pStr!=s._pStr)
{
strcpy(_pStr,pStr);
return *this;
}
//深拷贝
String(const String& s)
:_pStr(new char[strlen(s._pStr)]
{
strcpy(_pStr,s._pStr);
}
String &operator=(const String &s)
{
if(this!=&s)
{
char*pTemp=new char[strlen(s._pStr)];
   strcpy(pTemp,s._pStr);
   delete[] _pStr;
   _pStr=pTemp;
}
return *this;
}
//简洁版深拷贝
String(const String& s)
{
String tmp(s._pStr);
std::swap(_pStr,tmp._pStr);
}
String &operator=(const String &s)
{
if(this!=&s)
{
String tmp(s._pStr);
std::swap(_pStr,tmp._pStr);
}
return *this;
}
~String
{
if(_pStr!=NULL)
{
delete[] _pStr;
_pStr=NULL;
}
}
};
//浅拷贝的优化版,引用计数
#include<iostream>
using namespace std;
class String
{
private:
char* _pStr;
static int _count;
public:
String(const char *pStr=='')
{
if(NULL==pStr)
{
_pStr=new char[1];
_pStr='\0';
}
else
{
_pStr=new char[strlen(pStr)];
strcpy(_pStr,pStr);
}
++_count;
}
String(const String&s)
{
if(_pStr!=pStr)
{
strcpy(_pStr,pStr);
++_count;
}
}
String& operator=(const String&s)
{
if(this!=&s)
{
_pStr=s._pStr;
++_count;
}
return *this;
}
~Sting()
{
id(--_count==0)
{
delete[] _pStr;
_pStr=NULL;
}
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值