您的位置:首页 > 其它

如何实现引用计数对象

2006-07-07 11:09 639 查看
引用计数是实现对象共享的一种方式,在c++中被广泛的使用。对于它的实现也有千差万别,我这里仅仅提供一种最为常见的方法,以便大家不时之需。
// Author : Wang yanqing
// Module : Smart pointer
// Version : 0.01
// Date : 03-Aug-2005
// Reversion:
// Date :
// EMail : hello.wyq@gmail.com
#ifndef _SMART_PTR_REFCNT_OBJ_H
#define _SMART_PTR_REFCNT_OBJ_H

#include <algorithm>

#include "smart_ptr_refcnt_impl.h"
#include "noncopyable.h"

template <typename T, typename U>
class RefCntObj
{
RefCntImpl<T, U> *pc;

public:
explicit RefCntObj( T *pt, const U &del )
: pc ( new RefCntImpl<T, U>( pt, del ) )
{
assert( pt != NULL );
assert( pc != NULL );
}

RefCntObj( const RefCntObj &rhs ) : pc( rhs.pc )
{
assert( pc != NULL );
pc->incRefCnt();
}

~RefCntObj()
{
pc->decRefCnt();
}

RefCntObj& operator =( const RefCntObj &rhs )
{
assert( pc != NULL );
assert( rhs.pc != NULL );

// Check itself
if ( this == &rhs || pc == rhs.pc )
return *this;

// decrease old object's reference count
pc->decRefCnt();

// Increase new object's reference count
pc = rhs.pc;
pc->incRefCnt();

return *this;
}

inline void incRefCnt()
{
assert( pc != NULL );
pc->incRefCnt();
}

inline void decRefCnt()
{
assert( pc != NULL );
pc->decRefCnt();
}

inline T* get() const
{
assert( pc != NULL );
return pc->get();
}

inline void swap( RefCntObj &rhs )
{
if ( this == &rhs || pc == rhs.pc )
return;

assert( pc != NULL );
assert( rhs.pc != NULL );
std::swap( pc, rhs.pc );
}
};

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: