#include <iostream>
#include <cstdlib>
template< class T >
class AutoPointer
{
public :
explicit AutoPointer( T* rhs = NULL )
:is_owner( rhs != NULL ), g( rhs )
{ }
AutoPointer( AutoPointer& rhs )
:is_owner( rhs.is_owner )
{
g = rhs.release();
}
~AutoPointer()
{
free_mem();
}
const AutoPointer& operator =( AutoPointer& rhs )
{
if ( &rhs != this )
{
T* other = rhs.deref();
if ( other != g )
{
free_mem();
is_owner = rhs.is_owner;
}
else if ( rhs.is_owner )
{
is_owner = true;
}
g = rhs.release();
}
return *this;
}
T& operator *() const
{
return *deref();
}
T* operator ->() const
{
return deref();
}
T* deref() const
{
return g;
}
T* release()
{
is_owner = false;
return g;
}
private:
T* g;
bool is_owner;
void free_mem()
{
if ( is_owner )
delete g;
}
};
struct Integer
{
Integer( int a ):x( a )
{ }
~Integer()
{
std::cout << "DESTRUCT " << x << '\n';
}
int x;
};
int main( )
{
AutoPointer< Integer > p1( new Integer( 3 ) );
AutoPointer< Integer > p2 = p1;
AutoPointer< Integer > p3;
std::cout << ( *p1 ).x << " " << ( *p2 ).x << '\n';
p3 = p1;
std::cout << p1->x << " " << p2->x << " " << p3->x << '\n';
// 3 is owned by p2.
AutoPointer< Integer > p4( new Integer( 4 ) );
std::cout << p1->x << " " << p2->x << " " << p3->x << " " << p4->x << '\n';
p2 = p4;
std::cout << "3 is no longer owned! p1 and p3 are stale!!!" << '\n';
std::cout << p2->x << " " << p4->x << std::endl;
return 0;
}
Wednesday, July 8, 2009
How to implement Auto Pointer C++
In C++, auto_ptr<> is a smart pointer which automatically destroy itself when the program ends. Implementing an auto_ptr class is really easy and straightforward.
Subscribe to:
Post Comments (Atom)
Very neat.
ReplyDeletethanks,
--Sarath.
Your program crashes when Autopointer equals operator is called with both the objects pointing to the same integer.
ReplyDeleteThe Equality operator should be modified as follows
const AutoPointer& operator =( AutoPointer& rhs )
{
cout<< " Equals Operator" << endl;
if ( &rhs != this )
{
cout<< " Equals Operator not same object" << endl;
T* other = rhs.deref();
if ( other != g )
{
cout<< " Equals Operator diff object not pointing to same integer" << endl;
free_mem();
is_owner = rhs.is_owner;
}
else if ( rhs.is_owner )
{
is_owner = true;
}
else
{
cout<< " Equals Operator diff object pointing to same integer" << endl;
is_owner = false;
}
g = rhs.release();
}
else
{
cout<< " Equals Operator same object" << endl;
}
return *this;
}