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: Intermediate
May 27, 1999

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Never Store Arrays of Objects in an auto_ptr

The Standard Library's auto_ptr class template automatically destroys an object that is allocated on the free store when the current scope is exited. For example:
 
#include <memory> //definition of auto_ptr
#include <string>
using namespace std;

int main()
{
  auto_ptr<string> ps (new string);
  *ps = "hello";

} //ps is automatically destroyed at this point
Note however, that using auto_ptr to for an array of objects results in undefined behavior because the destructor of auto_ptr calls plain delete (and never delete []) to destroy its bound object. As you know, only operator delete[] should be used in order to destroy an array of dynamically-allocated objects. Therefore, never store arrays of objects in an auto_ptr:
 
int main()
{
  auto_ptr<string> ps (new string[2]); //bad

} //undefined behavior
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