Recently I\'ve met with opinion that I shouldn\'t use vector of pointers. I wanted to know - why I cant?
For example if I have a class foo
it is possib
Because the vector's destructor won't call delete
on the pointers, so it's easy to accidentally leak memory. A vector's destructor calls the destructors of all the elements in the vector, but raw pointers don't have destructors.
However, you can use a vector of smart pointers to ensure that destroying the vector will free the objects in it. vector
can be used in C++11, and in C++98 with TR1 you can use vector
(though shared_ptr
has a slight overhead compared to a raw pointer or unique_ptr
).
Boost also has a pointer container library, where the special delete-on-destruction behavior is built into the container itself so you don't need smart pointers.