这是我几年前从网上挑选的一个简单的引用计数智能指针,并进行了一些修补:
/// A simple non-intrusive reference-counted pointer.
/// Behaves like a normal pointer to T, providing
/// operators * and ->.
/// Multiple pointers can point to the same data
/// safely - allocated memory will be deleted when
/// all pointers to the data go out of scope.
/// Suitable for STL containers.
///
template <typename T> class counted_ptr
{
public:
explicit counted_ptr(T* p = 0)
: ref(0)
{
if (p)
ref = new ref_t(p);
}
~counted_ptr()
{
delete_ref();
}
counted_ptr(const counted_ptr& other)
{
copy_ref(other.ref);
}
counted_ptr& operator=(const counted_ptr& other)
{
if (this != &other)
{
delete_ref();
copy_ref(other.ref);
}
return *this;
}
T& operator*() const
{
return *(ref->p);
}
T* operator->() const
{
return ref->p;
}
T* get_ptr() const
{
return ref ? ref->p : 0;
}
template <typename To, typename From>
friend counted_ptr<To> up_cast(counted_ptr<From>& from);
private: // types & members
struct ref_t
{
ref_t(T* p_ = 0, unsigned count_ = 1)
: p(p_), count(count_)
{
}
T* p;
unsigned count;
};
ref_t* ref;
private: // methods
void copy_ref(ref_t* ref_)
{
ref = ref_;
if (ref)
ref->count += 1;
}
void delete_ref()
{
if (ref)
{
ref->count -= 1;
if (ref->count == 0)
{
delete ref->p;
delete ref;
}
ref = 0;
}
}
};
每个智能指针的存储要求适中:只有真实指针和引用计数。