Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::vector call the destructor of pointers to objects? [duplicate]

Possible Duplicate:
Deleting pointers in a vector

I know when an std::vector is destructed, it will call the destructor of each of its items. Does it call the destructor of pointers to objects?

vector<myclass*> stuff;

When stuff is destroyed, do the individual objects pointed to by the pointers inside stuff get destructed?


2 Answers

No.

How is std::vector supposed to know how to destroy the pointed-to object? Should it use delete? delete[]? free? Some other function? How is it supposed to know the pointed-to objects are actually dynamically allocated or that it is the One True Owner and is responsible for destroying them?

If the std::vector is the One True Owner of the pointed-to objects, use std::unique_ptr, potentially with a custom deleter to handle the cleanup of the objects.

like image 161
James McNellis Avatar answered Sep 08 '25 22:09

James McNellis


As you said correctly yourself, vector does call destructors for its elements. So, in your example the vector does call "destructors of pointers". However, you have to keep in mind that pointer types have no destructors. Only class types can have destructors. And pointers are not classes. So, it is more correct to say that std::vector applies the pseudo-destructor call syntax to the pointer objects stored in the vector. For pointer types that results in no-operation, i.e it does nothing.

This also answers the second part of your question: whether the myclass objects pointed by the pointers get destroyed. No, they don't get destroyed.

Also, it seems that you somehow believe that "calling destructors on pointers" (the first part of your question) is the same thing as "destroying the pointed objects" (the second part of your question). In reality these are two completely different unrelated things.

In order to create a link from the former to the latter, i.e. to make the vector destroy the pointed objects, you need to build your vector from some sort of "smart pointers", as opposed to ordinary raw myclass * pointers. The vector will automatically call the destructors of the "smart pointers" and these destructors, in turn, will destroy the pointed objects. This "link" can only be implemented explicitly, inside the "smart pointer's" destructor, which is why ordinary raw pointers can't help you here.

like image 37
AnT Avatar answered Sep 08 '25 22:09

AnT