Past-the-end iterator invalidation in C++11

后端 未结 3 1336
说谎
说谎 2020-12-29 04:05

The most popular post on C++ Iterator invalidation rules claims that it\'s not clear if the past-the-end iterators (i.e., those returned by end(), cend()<

相关标签:
3条回答
  • 2020-12-29 04:45

    You should be able to trust it if the standard says the operation will not invalidate iterators. Anything else should be treated as a bug in the standard library implementation.

    0 讨论(0)
  • 2020-12-29 04:51

    My question is about all containers:

    • In C++11, are there any container operations that may invalidate a past-the-end iterator, and where this behavior is ambiguous in the language specification?

    I am not sure what you mean with "where this behavior is ambiguous in the language specification", but there certainly are operations that invalidate past-the-end operators (like insert into a std::vector or std::string).

    Said differently,

    • Can I trust the validity of a past-the-end iterator after performing a container operation that does not say it may invalidate the past-the-end iterators?

    You can trust the past-the-end iterator like any other iterator: Any operation that does not (potentially) invalidate iterators won't invalidate them. Except for the possibility of the standard sporting a bug, that is all operations where it doesn't say that they (potentially) invalidate operators.

    0 讨论(0)
  • 2020-12-29 04:58

    At least in GCC end iterator gets invalidated for std::map:

    #include <set>
    #include <stdlib.h>
    #include <assert.h>
    int main() {
      std::set<int> a;
      a.insert(1);
      std::set<int>::reverse_iterator rit(a.rbegin());
      ++rit;
      assert(rit==a.rend());
      a.erase(a.begin());
      assert(a.rend()==rit); // FAIL
    }
    
    0 讨论(0)
提交回复
热议问题