//行为像值的类
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第五版_定义行为像值的类_行为像指针的类
最新推荐文章于 2022-03-04 23:46:10 发布
本文介绍了两种不同的C++类实现:一种模仿值的行为,另一种模仿指针的行为。通过具体的类定义展示了深拷贝和浅拷贝的概念,以及如何正确处理资源分配与释放,避免内存泄漏。
846

被折叠的 条评论
为什么被折叠?



