0
std::vector<Object *> pVector;

when out of scope, is the array/vector of pointers can delete every pointer element automatically? or must delete the every object manually?

So if can I think that: if the vector/array store no-pointer elements, it will call deconstructor automatically? but if stored pointers, it should delete elements manually?

jiafu
  • 6,338
  • 12
  • 49
  • 73

3 Answers3

2

vector properly destroys objects stored IN the vector. The destructor will be called. If you have a vector of pointers, then this means the pointer's own destructor (and not what it points to).

The destructor for a raw pointer does nothing. This is what you want if you have a non-owning pointer to an object that another part of the program will destroy.

The destructor for a smart pointer does whatever is necessary to make sure the object gets freed at the right time. For unique_ptr, that's right now. For shared_ptr, it's whenever the reference count hits zero.

Use the right kind of pointer, and trust vector to trigger the behavior associated with that pointer when the element is erased.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

No, the vector will only delete the memory it holds, which is memory to hold the pointers - effectively, it'll be an array of some size such as:

Object **array = new Object*[size]; 

When the destructor is called, all that gets deleted is this array store:

delete[] array;

As you can see, this will not free whatever those pointers are pointing to. This is why you should use a vector of unique_ptr or shared_ptr as opposed to raw pointers.

Yuushi
  • 25,132
  • 7
  • 63
  • 81
0

When the std::vector is destroyed, it calls the Object * destructor not the Object so only the pointer to the memory is destroyed.

You should use either smart pointers (std::shared_ptr<Object> or std::unique_ptr<Object>), either boost::ptr_vector<Object> which will manage memory for you.

UldisK
  • 1,619
  • 1
  • 17
  • 25