13.26
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "StrBlob.h"
#include "StrBlobPtr.h"
using namespace std;
class HashPtr{
public:
HashPtr(const string& s = string()) :ps(new string(s)), i(0),use(new size_t(1)) { }
//定义类指针的拷贝构造函数
//此处拷贝构造函数都是先初始化,再执行函数体,所以不存在++(*use)中use未初始化的问题
HashPtr(const HashPtr& h) :ps(h.ps), i(h.i), use(h.use) { ++(*use); }
//定义值行为的赋值运算符
HashPtr& operator= (const HashPtr&);
//解引用运算符
string& operator* ();
//析构函数
~HashPtr();
private:
string *ps;
int i;
size_t *use;//引用计数器,指向一个动态分配的内存单元,记录多少个对象共享*ps成员
};
inline
HashPtr::~HashPtr()
{
if (--(*use) == 0)
{
delete ps;//释放ps内存空间
delete use;//释放计数器内存空间
}
}
inline
HashPtr& HashPtr::operator= (const HashPtr& h)
{
++(*h.use);//先递增右侧计数器
if (--(*use) == 0)//在递减左侧计数器
{
delete ps;
delete use;
}
ps = h.ps;
i = h.i;
use = h.use;
return *this;
}
inline
string& HashPtr::operator*()
{
return *ps;
}
int main()
{
StrBlob b1;
StrBlob b2 = { "a", "an", "the" };
b1 = b2;
b2.push_back("about");
cout << "b2大小为:" << b2.size() << endl;
cout << "b2首尾元素为:" << b2.front() << ' ' << b2.back() << endl;
cout << "b1大小为:" << b1.size() << endl;
cout << "b1首尾元素为:" << b1.front() << ' ' << b1.back() << endl;
system("pause");
return 0;
}
本文介绍了一个名为HashPtr的智能指针类的设计与实现,该类使用引用计数来管理动态分配的字符串资源。文章展示了如何通过拷贝构造函数、赋值运算符和析构函数来维护引用计数,确保当最后一个引用被销毁时,动态分配的资源能够得到正确的释放。
924

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



