C++ Primer(第5版) 练习 13.27
练习 13.27 定义你自己的使用引用计数版本的HasPtr。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
class HasPtr{
public:
HasPtr(const string &s = string()): ps(new string(s)), i(0), use(new size_t(1)) {}
HasPtr(const HasPtr &s): ps(s.ps), i(s.i), count(s.use) { ++*count; }
HasPtr& operator= (const HasPtr &s);
~HasPtr();
private:
string *ps;
int i;
size_t *count;
};
HasPtr::~HasPtr(){
if(--*count == 0){
delete ps;
delete count;
}
}
HasPtr& HasPtr::operator= (const HasPtr &s){
++*s.count;
if(--*count == 0){
delete ps;
delete count;
}
ps = s.ps;
i = s.i;
count = s.count;
return *this;
}