Frames Catherine White
Frames Catherine White

Reputation: 28192

Removing something from a STL container without deconstructing it

Ok, I'm using C++ STL containers (currently vector<customType*>). Now I need to remove elements from the container, but using erase deconstructs the object, which is bad, since I'm taking it off one, and putting it onto a variable doing some processing then onto another one.

At the moment my code is quite nasty, and I'm just putting NULL in its place after I've read it, into my variable, and then putting a if (Q[ii]NULL) continue. But this is not so great.

Upvotes: 1

Views: 1809

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

STL container operations have copy semantics. So any time you add or remove elements, the constructor or destructor will get called accordingly (assuming a non-primitive type). And if the vector gets resized in the process, all objects will be copy-constructed and the originals destructed. There's no way to avoid all this copying.

The only way to avoid the overhead is to have a vector of (smart) pointers instead of objects.

Upvotes: 0

Charles Salvia
Charles Salvia

Reputation: 53289

You can't really remove the element from the vector without destroying it. If your vector stores pointers, you can remove the pointer to the element, which won't actually destroy the element itself.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355009

If you have a container of pointers (which it sounds like you do since you are assigning NULL to "erased" elements), then erasing an element from the container does not delete the pointed-to object. You are responsible for doing that yourself.

If you have a container of objects (well, non-pointer objects), then you need to copy the element out of the container before you erase it.

Upvotes: 3

Related Questions