Jump to content
  • Advertisement
Sign in to follow this  
Drunken_Monkey

Vector Question

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

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!