Checking if an iterator is valid

后端 未结 11 545
耶瑟儿~
耶瑟儿~ 2020-11-30 02:52

Is there any way to check if an iterator (whether it is from a vector, a list, a deque...) is (still) dereferencable, i.e. has not been invalidated?

I have been usi

11条回答
  •  春和景丽
    2020-11-30 03:20

    Trying and catching is not safe, you will not, or at least seldom throw if your iterator is "out of bounds".

    what alemjerus say, an iterator can always be dereferenced. No matter what uglyness lies beneath. It is quite possible to iterate into other areas of memory and write to other areas that might keep other objects. I have been looking at code, watching variables change for no particular reason. That is a bug that is really hard to detect.

    Also it is wise to remember that inserting and removing elements might potentially invalidate all references, pointers and iterators.

    My best advice would be to keep you iterators under control, and always keep an "end" iterator at hand to be able to test if you are at the "end of the line" so to speak.

提交回复
热议问题