C++对象生命周期管理--通过引用计数指针对象来封装管理对象生命周期

在实际的软件开发过程中,对象的生命周期管理一直是软件开发过程中的一个重点和难点,在C++标准库中也逐渐的出现了一系列的智能指针(标准库/boost库中都涉及到),但是这种智能指针的设计,只是对Object进行封装,接管了相关的生命周期,但是有时候在具体的业务需求中,需要对象自己管理自己的生命周期,那么在对象中需要封装相关的引用计数,当引用计数为0时,需要删除对象本身,为了满足该业务需求,设计该基础工具类,方便后期使用,具体代码如下:

#ifndef  INTRUSIVEPTR_HPP_
#define  INTRUSIVEPTR_HPP_

#include <inttypes.h>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>

namespace ts
{
    /**
     *@brief 侵入式的引用计数管理对象生命周期[使用者需要继承该类,只能通过new对象来进行初始化资源]
     *侵入式:需要了解基础结构的具体实现,通过继承等方式使用
     *非侵入式:不需要了解基础结构的具体实现,通过配置的方式使用
     */
    template <typename T>
    class IntrusivePtr : boost::noncopyable
    { 
    //! Intrusive reference count
    //! 可以考虑把计数封装为一个独立的处理对象
    size_t _count;

    //! Synchornization object
    typedef boost::mutex::scoped_lock lockType;
    boost::mutex m_mutex;

    public:

    /**
    * Create an IntrusivePtr with a count. intrusive
    */
    IntrusivePtr(size_t InitialCount=1) : _count(InitialCount) {
    }

    /**
    * Destroy an IntrusivePtr
    */
    virtual ~IntrusivePtr() {}

    /**
    * Add a reference to this object, it will take one more
    * call to delReference() for it to be deleted.
    */
    void addReference() 
    {
        lockType l(m_mutex);
        ++_count;
    }

    /**
    * Remove a reference from this object, if the reference count
    * drops to 0 as a result, the object deletes itself.
    */
    void delReference() {

    bool result = false;

    {
      lockType l(m_mutex);
      result = (--_count == 0);
    }


    if(result)
      delete this;
    }
    };
};

#endif // INTRUSIVEPTR_HPP_


如代码中描述,具体的实现对象需要继承该基础类,使用者通过主动调用”addReference()“和”delReference()“来对引用计数进行管理,当引用计数为0时,对象被释放

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值