开发者

Removing something from a STL container without deconstructing it

开发者 https://www.devze.com 2023-01-20 08:47 出处:网络
Ok, I\'m using C++ STL containers (currently vector<customType*>). Now I need to remove elements from the container,

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 m开发者_StackOverflowy variable, and then putting a if (Q[ii]NULL) continue. But this is not so great.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消