Sign in to follow this  
Drunken_Monkey

Vector Question

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?

Share this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this