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
Mar 5, 2001

Deleting Elements of a Container of Pointers


This is a common source of misunderstanding: a programmer creates a container of pointers, then fills that container with pointers to dynamically allocated objects. When the container is destroyed, the programmer mistakenly assumes that the objects are deleted. However, they aren't because the container contains pointers, not real objects. Consider:
 
vector<Base *> v;
v.push_back(new Derived);
v.clear();  // doesn't delete the object!

To properly destroy the objects of a container of pointers, you should explicitly delete its pointers before destroying the container itself:
 
v.push_back(new Derived);
// delete the object whose pointer is stored in v
delete v[0]; 
// now clear the container
v.clear();
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap