引用计数是实现对象共享的一种方式,在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