Checking if an iterator is valid

后端 未结 11 543
耶瑟儿~
耶瑟儿~ 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:39

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

    No, there isn't. Instead you need to control access to the container while your iterator exists, for example:

    • Your thread should not modify the container (invalidating the iterator) while it is still using an instantiated iterator for that container

    • If there's a risk that other threads might modify the container while your thread is iterating, then in order to make this scenario thread-safe your thread must acquire some kind of lock on the container (so that it prevents other threads from modifying the container while it's using an iterator)

    Work-arounds like catching an exception won't work.

    This is a specific instance of the more general problem, "can I test/detect whether a pointer is valid?", the answer to which is typically "no, you can't test for it: instead you have to manage all memory allocations and deletions in order to know whether any given pointer is still valid".

提交回复
热议问题