Reputation: 21
I'm using a vector to hold pointers to a class.
class fooContainer{
private:
vector <Foo *> foos;
public:
void processFoo(int fooIndex);
};
The problem I face is that pop_back()
drops the element, I only want to remove it from the vector but not touch the object in question. I also need to remove all elements from a vector in preparation for restarting the main cycle (but keeping the same vector, which is a class attribute).
I need a structure that has dynamic sizing but does not copy or delete its elements, being content to hold pointers to them.
Is there a better alternative structure, or am I using them all wrong?
Upvotes: 1
Views: 358
Reputation: 31589
Vector does copy and destroy its contents, but in your case the content is pointer to object and not the object.
The specific pointer to the object will be destroyed, but other pointers to that object, and the object itself, won't be destroyed.
Upvotes: 4
Reputation: 63250
If you just want to get a copy of your pointer from your vector, then you can use Foo* pfoo = v[0]
or the at(index)
function for checked access.
Also you want to clear all your pointers, you can loop through them and delete them all and call v.clear()
to remove all elements.
If you want a vector that already does the deleting of pointers for you correctly, use a boost::vector_ptr
Upvotes: -1
Reputation: 14591
pop
doesn't "drop" the element, it just removes it from the vector. As your vector contains pointers, you are responsible for deleting them appropriately.
Vector does exactly what you ask for.
To remove the elements, just call vector.clear()
Upvotes: 0
Reputation: 258638
What you have does exactly that. The object elements in the vector point to won't be destroyed unless you explicitly delete
them.
Alternatively, if you want to use the same pointers in multiple places with shared ownership, I suggest using std::shared_ptr
.
Upvotes: 1