auto_ptr<>: your safe guard against memory leaks

auto_ptr<>: your safe guard against memory leaks

The Standard Library supplies the class template auto_ptr which automatically deallocates heap memory. Likewise, local objects are reclaimed in case of exiting their scope or during “stack unwinding” caused by an exception.

This technique can avoid memory leakage in the case of uncaught exception or even simplify programming by sparing the hassle of explicitly deleting every object allocated using operator new. The auto_ptr class template is declared in the standard header.

 #include  //auto_ptr declaration#include using namespace std;class Date{ /*...*/};void DisplayDate(){	//now create a local object of type auto_ptr auto_ptr pd (new Date); //now pd is owned by the template object	coutDateString();//note: pd is automatically deleted by the destructor of auto_ptr; it shouldn't be deleted by programmer}

In other words, the auto_ptr instance, pd, can be used like an ordinary pointer to Date but it behaves like a local object in respect to its automatic destruction.


Share the Post: