views:

81

answers:

4

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.

+3  A: 

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.

James McNellis
Ah, you are correct.It was something else causing my bugs.Thanks
Oxinabox
+1  A: 

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.

Charles Salvia
A: 

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.

Oli Charlesworth
A: 

If you are storing objects.. do all your processing and use erase after.

If you are storing pointers to objects (which is a good idea), copy your pointer in a temp variable, use erase and do your processing with the temp var.

I'm still not sure if I understood correctly your question, but for now, this seems the only solution for me.

Best Regards.

Victor Z.
Storing pointers to objects is a good idea?
GMan
why not ? You get a more flexible code.. assuming you'll take care of them and free the space after processing...
Victor Z.
@Victor: Just store the values so you don't have to worry about it. And if you really want pointers, use a smart pointer or pointer container. I fail to see how it's more flexible.
GMan
Store value or reference is prefered than pointer...
wengseng