Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Jun 11, 1998

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 <memory> header.

 
#include <memory> //auto_ptr<> declaration
#include <iostream>

using namespace std;

class Date{ /*...*/};

void DisplayDate()
{
	//now create a local object of type auto_ptr<Date> 
auto_ptr<Date> pd (new Date); //now pd is owned by the template object
	cout<<pd->DateString();

//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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date