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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date