PDA

View Full Version : Vectors & auto-"delete"



Darhuuk
11th January 2008, 00:13
I'm making a program in which I have several vectors which contain pointers to object & I need to move those pointers from one vector to another.

Now, let's make an example as simple as possible and say I have 2 vectors: atHome & notHome. Both contain pointers to CDs (so we have 2 std::vector<*CD>). Now, I move a CD from my home to a friend's. Thus, the pointer needs to be removed from atHome & added to notHome. The adding is simple enough, I just do a push_back(). However, I can't find a way to remove the pointer from the atHome vector. Both pop_back() & erase() call the destructor of the object they're removing, so I obviously can't use that or I would lose the CD object & the notHome vector would contain an invalid pointer (same goes for clear() if I wanted to remove all the pointers from the vector).

I'm sure there's an easy way to solve this, but I can't come up with one. I know in this example you could just add a location field to the CD class, but in the program I'm making such a thing is not possible and also that would cause an incredible amount of overhead, since each time you'd want to find every CD at home, you'd need to iterate through the complete vector.

And so I continue on my quest to fill this forum with mostly newbie questions ;).

jpn
11th January 2008, 09:35
std::vector::pop_back() does not delete anything.

Darhuuk
11th January 2008, 09:38
Hm, the C++ Reference says it does: http://www.cplusplus.com/reference/stl/vector/pop_back.html.


void pop_back ( );

Delete last element

Removes the last element in the vector, effectively reducing the vector size by one and invalidating all iterators and references to it.

This calls the removed element's destructor.

I'll make some simple tests & see if my program crashes.

wysota
11th January 2008, 10:40
It deletes the object held and in your case this is a pointer and not the object pointed by the pointer. So before (or after) popping, you still need to call delete.

Darhuuk
11th January 2008, 10:53
Ah ok, sorry, the explanation on that site threw me off. So it calls some kind of "pointer" destroyer, k. Thanks!

wysota
11th January 2008, 11:24
No, it just frees the memory. Pointers don't have destructors.