Thursday, April 22, 2010

auto_ptr : will take care of memory leaks !!!

The template class describes an object that stores a pointer to an allocated object of type Type* that ensures that the object to which it points gets destroyed automatically when control leaves a block.

The auto_ptr class supports normal pointer operations like =, *, and ->, as well as two functions TYPE* get() and TYPE* release(). The get() function returns a pointer to the object that the auto_ptr points to. The release() function acts similarily to the get() function, but also relieves the auto_ptr of its memory destruction duties.

What happened when you copy an auto_ptr?

An auto_ptr owns the object that it holds a pointer to, and only one auto_ptr may own an object at a time. When you copy an auto_ptr, you automatically transfer ownership from the source auto_ptr to the target auto_ptr; if the target auto_ptr already owns an object, that object is first freed. After the copy, only the target auto_ptr owns the pointer and will delete it in due time, while the source is set back to a null state and can no longer be used to refer to the owned object.

Example:

Things without using auto_ptr:

class MyClass {
public:
MyClass() {}
~MyClass() {}
void myFunc() {}
};

void function() {
MyClass* ptr = new MyClass();
// do some operation
.........
.........
delete ptr;
}

Now consider that you are performing big operation (more than 10 lines of code) and got some exception in between. So delete will never get called and will result a memory leak.

Yes, you can use try-catch and inside catch block you can delete the pointer. But most of the cases we forgot to take care of all these things. auto_ptr will solve this as it will take care of releasing the memory.

#include
using namespace std;

class MyClass {
public:
MyClass() {}
~MyClass() {}
void myFunc() {}
};

int main() {
auto_ptr ptr1(new MyClass), ptr2;

ptr2 = ptr1;// now ptr2 owns the pointer,ptr1 does not
ptr2->myFunc();

MyClass* ptr = ptr2.get(); //returns a pointer to the objects it points to

ptr->myFunc();

return 0;
}// as we go out of scope, ptr2's destructor deletes the pointer, but ptr1's does nothing

Problem with auto_ptr:
It is never safe to put auto_ptrs into standard containers, because copies of auto_ptrs are not equivalent.