devxlogo

Deleting Elements of a Container of Pointers

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 v;v.push_back(new Derived);v.clear();  // doesn't delete the object!

size=3>
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 vdelete v[0]; // now clear the containerv.clear();

size=3>

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist