• 12
• 10
• 10
• 13
• 10

# Vector Question

This topic is 4302 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Okay, I have a vector set up like this...
vector<c*> list;

c* _j = new c;
c** j = &_j;

list.push_back(*j);


When "list" is destroyed, do all of the nodes in "list" free the memory of what they're pointing to?

No.

##### Share on other sites
std::vector cleans up the things that it allocates. It didn't allocate the c's pointed at by the c*'s, so those are your responsibility.

This is a good thing. If it behaved the other way, then (a) you wouldn't be able to instantiate a vector of non-pointers, because the destructor wouldn't be valid - you can't delete non-pointers; (b) client code would double-delete and thus crash and burn if it tried to delete the things it allocated, which is what it should normally do.

You should normally *not* make a vector of pointers. If you do need it for some reason, then consider the reason, and choose a solution from below:

- Ignore it; you're storing "non-owning" pointers to things ("weak references"), and you already have code in place that cleans up what needs to be cleaned up. Although you might be better off with some kind of handle class instead (say for example that your vector of pointers represents a "subset" or "view" of a larger vector of objects, by referencing the elements of the large vector rather than holding copies; then you might make a handle class which contains a pointer to the large vector itself, plus an integer index. Or maybe you would instead decide to store the big collection as a std::map, and then make std::vectors - or std::sets - of key values.)

- Use a Boost ptr_container, such as boost::ptr_vector.

- Use a normal vector of "smart pointer" objects, such as std::vector<boost::shared_ptr<c> >.

##### Share on other sites
Quote:
 Original post by Zahlman- Use a normal vector of "smart pointer" objects, such as std::vector >.

To the OP: there's a brief introduction to them in section 5 of Using Modern C++ to Eliminate Memory Problems.