vector of pointer

c++

Solution

If I delete vector temp, do I destroy the basket[1] object too?

No. First of all, you cannot delete `temp`; rather, it will get destroyed when going out of scope. And when this happens, the objects pointed by elements of the vector won't be automatically `delete`d.

This is, however, not a specific problem of `vector`: using `list` will not save you from this issue. The problem is rather with raw pointers. If you want the pointed objects to be automatically deallocated when the the lifetime of the last pointer which points to it ends, you should use smart pointers.

Depending on the ownership policy that your application needs, you might choose between `shared_ptr` and `unique_ptr`. The caveat with `shared_ptr` is that referencing cycles shall be avoided, to prevent mutually referencing objects from keeping each other alive. You may want to check `weak_ptr` in this respect.

Finally, unless you have a good reason for not using `vector`, `vector` should be the default choice for a container. From Paragraph 23.2.3/2 of the C++11 Standard:

The sequence containers offer the programmer different complexity trade-offs and should be used accordingly. `vector` or `array` is the type of sequence container that should be used by default. `list` or `forward_list` should be used when there are frequent insertions and deletions from the middle of the sequence. `deque` is the data structure of choice when most insertions and deletions take place at the beginning or at the end of the sequence.

Problem

I just wonder what's wrong with vector of pointer. some of my friend recommend me to use list instead of vector. will this cause a problem: ``` vector<Fruit*> basket; basket.push_back(new Apple()); basket.push_back(new Orange()); vector<Fruit*> temp; temp.push_back(basket[1]); ``` If I delete vector temp, do I destroy the basket[1] object too? if not, what's the problem with using vector of pointer?

Original source