C++11增加了智能指针:shared_ptr、unique_ptr、weak_ptr
为了加深理解,自己实现智能指针
我们都知道shared_ptr的核心思想通过引用计数来管理内存
先实现单个指针的自我管理,看下面
template <class T>
class Ref
{
public:
Ref() : m_ptr(NULL)
{
}
Ref(T* p) : m_ptr(p)
{
if (m_ptr)m_ptr->AddRef();
}
Ref(const Ref<T>& r) : m_ptr(r.m_ptr)
{
if (m_ptr)m_ptr->AddRef();
}
template <typename U>
Ref(const Ref<U>& r) : m_ptr(r.get())
{
if (m_ptr) m_ptr->AddRef();
}
~Ref()
{
if (m_ptr) m_ptr->Release();
}
T* get() const { return m_ptr; }
operator T*() const { return m_ptr; }
T* operator->() const { return m_ptr; }
T* release()
{
T* retVal = m_ptr;
m_ptr = NULL;
return retVal;
}
Ref<T>& operator=(T* p)
{
if (p) p->AddR