-1

I have a collection of pointers, for example std::vector<std::string*>.

Which is the most appropriate way to automatically delete the instances pointed by its items when the collection is deleted?

When I delete the collection, I would automatically like to delete all pointed items.

Dabiel Kabuto
  • 2,762
  • 4
  • 29
  • 45
  • By instance, do you mean instance or pointer to instance? I.e. `std::vector` or `std::vector`? – sashoalm Mar 28 '14 at 11:05
  • possible duplicate of [Cleaning up an STL list/vector of pointers](http://stackoverflow.com/questions/307082/cleaning-up-an-stl-list-vector-of-pointers) – sashoalm Mar 28 '14 at 11:24

3 Answers3

8

The simplest way to ensure the container's elements are correctly destroyed is to store objects, not pointers.

If you really need pointers (perhaps for polymorphism), then store smart pointers - usually std::unique_ptr, but perhaps std::shared_ptr (or its TR1 or Boost equivalents) if you need to share ownership, or are stuck with a pre-2011 compiler.

Don't try to juggle raw pointers - that's a recipe for memory leaks and worse.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

You can use std::shared_ptr (see here)

Example:

class A { ... };

{
    std::list<std::shared_ptr<A>> data;
    data.push_back(std::make_shared<A>()); // add element to the list
}
// at this point data is deleted and all created class instanced with it 

Another way is to use proper RAII. This means that the class destructor is responsible to delete all acquired resources. Than you can store instanced per value in your container.

Danvil
  • 22,240
  • 19
  • 65
  • 88
1

The items are automatically deleted.

For example, for std::vector<std::string>, the destructor of each instance of std::string will be called.

If you asked about pointers to instances, C++ pointers don't have destructors.

sashoalm
  • 75,001
  • 122
  • 434
  • 781