Skip to main content
GameDev.net gamedev.net
🔒 Locked

Vector Question

Started by Drunken_Monkey Jun 9, 2006 at 12:58 PM 2 replies 400+ views
Original Post
Drunken_Monkey
Drunken_Monkey
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?
SiCrane
SiCrane
No.
Zahlman
Zahlman
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 >.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.