primer C++笔记
拷贝控制和资源管理
//类值版本
class ValHasPtr
{
public:
ValHasPtr(const string& s = string())
:ps(new string(s)), i(0) {}
ValHasPtr(const ValHasPtr& p)
:ps(new string(*p.ps)), i(p.i) {}
ValHasPtr& operator=(const ValHasPtr&);
~ValHasPtr() { delete ps; }
private:
string *ps;
int i;
};
ValHasPtr& ValHasPtr::operator=(const ValHasPtr& rhs)
{
auto newp = new string(*rhs.ps);
delete ps;
ps = newp;
i = rhs.i;
return *this;
}
引用计数
引用计数的类
//引用计数版本
class PointerHasPtr
{
public:
PointerHasPtr(const string& s = string())
:ps(new string(s)), i(0), use(new size_t(1)) {}
PointerHasPtr(const PointerHasPtr& p)
:ps(p.ps), i(i), use(p.use)
{
++*use;
}
PointerHasPtr& operator=(const PointerHasPtr&);
~PointerHasPtr();
private:
string *ps;
int i;
size_t *use;
};
PointerHasPtr& PointerHasPtr::operator=(const PointerHasPtr& rhs)
{
++*rhs.use;
if (--*rhs.use)
{
delete ps;
delete use;
}
ps = rhs.ps;
i = rhs.i;
use = rhs.use;
return *this;
}