博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ RCSP智能指针简单实现与应用
阅读量:4631 次
发布时间:2019-06-09

本文共 2469 字,大约阅读时间需要 8 分钟。

智能指针的实现代码来源博客:《http://blog.csdn.net/to_be_better/article/details/53570910》

修改:添加 get()函数,用以获得原始指针(raw pointer)。

其余思路来源《Effective C++》

智能指针的实现代码如下:

template 
class SmartPtr;template
class Ptr{ friend class SmartPtr
; T *m_ptr; size_t m_count; Ptr(T *p = NULL) : m_ptr(p), m_count(1) {} ~Ptr() { delete m_ptr; }};template
class SmartPtr{ public: SmartPtr(T *p = NULL) : m_p(new Ptr
(p)) {} SmartPtr(const SmartPtr &sp) : m_p(sp.m_p) { ++m_p->m_count; } SmartPtr &operator=(const SmartPtr &sp) { ++sp.m_p->m_count; if (--m_p->m_count == 0) { delete m_p; } m_p = sp.m_p; return *this; } T *operator->() { return m_p->m_ptr; } const T *operator->() const { return m_p->m_ptr; } T operator*() { return *m_p->m_ptr; } T *get() /*get raw pointer*/ { return m_p->m_ptr; } ~SmartPtr() { if (--m_p->m_count == 0) delete m_p; } private: Ptr
*m_p;};

引用计数型智能指针(reference-counting smart pointer, RCSP)可实现持续追踪共有多少对象指向某笔资源,并在无人指向它时自动删除该资源。

在c++中资源管理中为防止意外退出而导致资源泄漏。

这种reference counting 可以允许copying行为,如需抑制copying,以private 方式继承Uncopyable类即可。

Uncopyable类:

class Uncopyable{  protected:    Uncopyable() {}    ~Uncopyable() {}  private:    Uncopyable(const Uncopyable &);    Uncopyable &operator=(const Uncopyable &);};

一个应用例子:

目的是创建一个类的智能指针,用以描述文件的一些属性的类,在后续代码中使用这个指针来赋予或读取这些属性。当然,使用智能指针为了防止资源泄漏,符合本文初衷。

由成员函数:createFileAttrs() 产生动态创建一个静态的智能指针,由这个指针去给类中的成员变量分配资源,并返回这个指针,即可实现功能。

测试类:

class FileAttr{public:    ~FileAttr();    static SmartPtr
createFileAttrs(); char *md5;private: FileAttr();};FileAttr::FileAttr(){}FileAttr::~FileAttr(){ cout << "destructor" << endl; delete[] md5;}SmartPtr
FileAttr::createFileAttrs(){ static SmartPtr
fileAttr(new FileAttr()); fileAttr->md5 = new char[20]; return fileAttr;}

应用方法:

int main(){    SmartPtr
fa = FileAttr::createFileAttrs(); // 使用智能指针 /* FileAttr *fa = FileAttr::createFileAttrs().get(); // 或者使用原始指针 */ { memcpy(fa->md5, "md51", 4); } { memcpy(fa->md5 + 4, "md52", 4); } cout << fa->md5<

打印输出:

md51md52

destructor

由于自定义类未重载operator=,所以直接使用智能指针比较合适,需要原始指针的话调用get()函数即可。

转载于:https://www.cnblogs.com/bobojiang/p/8580015.html

你可能感兴趣的文章
delegate代理设计模式
查看>>
如何为ListView加上快速滑块,是否可以修改快速滑块图像呢?
查看>>
ChartCtrl源码剖析之——CChartLegend类
查看>>
python3 dict(字典)
查看>>
关于Unity中摇杆的操作
查看>>
解决idea2018无法安装lombok的问题
查看>>
【UVA】10935 Throwing cards away I(STL队列)
查看>>
ae工具是一种特殊的命令
查看>>
名人名言
查看>>
异常处理:写一个方法void triangle(inta,intb,int c),判断三个参数是否能构成一个三角形。...
查看>>
自组织神经网络介绍:自组织特征映射SOM(Self-organizing feature Map),第三部分
查看>>
如何自己编译生成hadoop的eclipse插件,如hadoop-eclipse-plugin-2.6.0.jar
查看>>
Markdown打造高逼格博客
查看>>
前端模块化(五):RequireJs
查看>>
SQLiteOpenHelper
查看>>
arcgis js api 4.x 基于tomcate的离线开发环境搭建
查看>>
js中的函数对象
查看>>
前后台交互实例二:前台通过django在数据库里面增删改查数据
查看>>
全部选择和全部取消多选框
查看>>
Haproxy+Keepalived负载均衡
查看>>