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

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
Thanks for your registration, follow us on our social networks to keep up-to-date