//行为像值的类
class HasPtr
{
public:
HasPtr(const std::string &s = std::string()):ps(new std::string(s)), i(0) {}
HasPtr(const HasPtr &p):ps(new std::string(*p.ps)), i(p.i) {}
HasPtr& operator=(const HasPtr &rhs)
{
std::string *newp = new string(*rhs.ps);
delete ps;
ps = newp;
i = rhs.i;
return *this;
}
~HasPtr() {delete ps;}
private:
std::string *ps;
int i;
};
//行为像指针的类
class HasPtr
{
public:
HasPtr(const std::string &s = std::string()):ps(new std::string(s)), i(0), use(new std::size_t(1)) {}
HasPtr(const HasPtr &p):ps(p.ps), i(p.i), use(p.use) {++*use;}
HasPtr &operator=(const HasPtr &rhs)
{
++*rhs.use;
if (--*use == 0)
{
delete ps;
delete use;
}
ps = rhs.ps;
i = rhs.i;
use = rhs.use;
return *this;
}
~HasPtr()
{
if (--*use == 0)
{
delete ps;
delete use;
}
}
private:
std::string *ps;
int i;
std::size_t *use;
};
C++ primer第五版_定义行为像值的类_行为像指针的类
最新推荐文章于 2021-09-01 22:31:52 发布