开发者

About C++ STL list class method erase()

开发者 https://www.devze.com 2023-02-08 22:02 出处:网络
The documentation of list::erase() says, \"call destructor before\", what does this mean? If I want to erase(it) a item and then push_back(*it) the item开发者_JAVA技巧 again, will that be illegal sinc

The documentation of list::erase() says, "call destructor before", what does this mean? If I want to erase(it) a item and then push_back(*it) the item开发者_JAVA技巧 again, will that be illegal since it was destructed already?


Yes, this will result in undefined behavior. Once you erase a list iterator you invalidate the iterator, meaning that the object it references is no longer guaranteed to be valid. This means that if you then try to use the iterator in any context, including trying to dereference the value to add it to the list again, it will result in undefined behavior, which could crash the program, overwrite important memory, or do nothing.

If you want to move an element of a list to the back, consider using the list's splice method:

myList.splice(myList.end(), myList, it);

This moves the element to the end without making a copy.


The element in the container is destroyed when it is removed from the container. If you want to keep the object after you remove it from the container, you need to make a copy of it and use the copy instead.

Your proposed code:

v.erase(it);
v.push_back(*it);

is invalid because it is invalidated after the erasure. You cannot use an iterator after it has been invalidated.


Mixing erase and iterators can be a very tricky business. The validity of various iterators after you've done an erase can vary form container to container. The thing you should do if you want to do an erase and a push_back is to save a copy of what's in *it first, then using the copy when you do a push_back.


The item is erased by destroying it and then removing the reference to it from the list. If you want to retain the item then you need to take a copy of it before calling erase. All of this suggests that perhaps std::list is not the correct container for your needs.

0

精彩评论

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