Monday, August 15, 2011


Look at the following code.

The above code will work perfectly if the "do some stuffs" section doesn't throw any unhandled exception. If some exception is thrown, then the object will be created in the heap and won't be deleted till the program termination.

Hence, object creation in heap is always dangerous than object creation in stack. We can avoid the above situation by using auto_ptr templatised class in STL.

Automatic Pointer(auto_ptr) class is a limited garbage collection facility which takes responsibility of object destruction when the auto_ptr goes out of scope.

Auto_ptr takes the responsibility of the destruction of the object. Hence if same auto_ptr points to another object, the previous object is destroyed properly.

Example :-

Output :-

If the responsibility is transferred from 1st pointer to the second pointer(by assignment operator), then 1st pointer is set to NULL. Hence, no two auto pointer points to the same object.

Example :-

Output :-

Certain Links that might prove useful

No comments:

Post a Comment