Pages

21 Apr 2012

Simple auto_ptr implementation

STL auto_ptr utilizes simple concepts realized with templates to achieve automatic memory management in C++.
One simple implementation of auto_ptr could be as follows


template <class T>
class MyAutoPtr
{
//typedef our template pointer and class, so that code looks cleaner
typedef T* _ele ;
typedef MyAutoPtr<T> _eleType;


public:
//make constructor explicit to avoid converting constructor
explicit MyAutoPtr(_ele ptr =0):element(ptr){}


//destructor - delete only if pointer is non zero
~MyAutoPtr()
{
if(element)
delete element;
}


//copy constructor
MyAutoPtr(_eleType &obj) 
:element(obj.release())
{}


//operator overloads
_ele operator -> ()
{
return element;
}
_ele operator * ()
{
return element;
}
//assignment operator
_eleType & operator = (_eleType & rhs)
{
//release the rhs so that ownership is moved to lhs
//reset pointer if needed
reset(rhs.release());
return *this;
}


private:
_ele element;


//inorder to transfer ownership of object, store a copy of object in temp.
//assign zero to pointer and return temp.
_ele release()
{
_ele temp = this->element;
this->element = 0;
return temp;
}


//during assignment delete our object and point to assinged object
void reset(_ele rhs)
{
if(this->element != rhs)
{
delete this->element;
this->element = rhs;
}
}
};

1 comment:

  1. if(this->element != rhs)
    {
    delete this->element;
    this->element = rhs;
    }

    should have:

    if (this->element) delete this->element;

    Otherwise assignment to a clear ptr segvs:
    MyAutoPtr a,b;
    a = b; // Segv

    ReplyDelete