auto_ptr does not allow sharing object, i.e. when auto_ptr is shared ownership transfers to rhs. This ensures that we have only one copy of pointer and pointer will be destroyed when scope is over. A simple auto_ptr implementation
However there are situations where we like to share our object pointer. For such need boost has shared_ptr implementation, my version of shared_ptr implementation is as follows
template <class T>
class MySharedPtr
{
public:
//constructor creates the dynamic interger to hold ref counting
explicit MySharedPtr(T* p = 0):m_ptr(p)
{
pRefCount = new int();
*pRefCount = 1;
}
~MySharedPtr()
{
//destroy only if ref count is 1 else null set member
if(1 == *pRefCount)
{
if(NULL != m_ptr)
delete m_ptr;
delete pRefCount;
}
else
{
m_ptr = NULL;
//decrement the counter when not deleteing object
--*pRefCount;
}
}
MySharedPtr(MySharedPtr<T> & rhs)
{
//during copy construction share the object pointer
// and ref counting pointer
this->m_ptr = rhs.m_ptr;
this->pRefCount = rhs.pRefCount;
//increment the counter as we have one more object now
++*pRefCount;
}
MySharedPtr<T>& operator = (MySharedPtr<T>& rhs)
{
if(this->m_ptr != rhs.m_ptr)
{
if(this->m_ptr != NULL)
{
//if rhs object counter is 1 then delete it otherwise
//decrement rhs counter
if(*this->pRefCount == 1)
{
delete m_ptr;
m_ptr = NULL;
delete pRefCount;
pRefCount = NULL;
}
else
{
--*(this->pRefCount);
}
}
//assing rhs and increment counter
this->m_ptr = rhs.m_ptr;
this->pRefCount = rhs.pRefCount;
++*(rhs.pRefCount);
}
return *this;
}
private:
T* m_ptr;
//pointer to hold ref counter
int* pRefCount;
};
No comments:
Post a Comment