在实际的软件开发过程中,对象的生命周期管理一直是软件开发过程中的一个重点和难点,在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时,对象被释放