What is iterator invalidation?

前端 未结 3 1686
名媛妹妹
名媛妹妹 2020-11-30 00:58

I see it referenced a lot but no clear answer of what exactly it is. My experience is with higher level languages, so I\'m unfamiliar about the presence of invalidity in a c

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 01:34

    Iterator invalidation is what happens when an iterator type (an object supporting the operators ++, and *) does not correctly represent the state of the object it is iterating. For example:

    int *my_array = new int[15];
    int *my_iterator = &my_array[2];
    
    delete[] my_array;
    
    std::for_each(my_iterator, my_iterator + 5, ...); // invalid
    

    That results in undefined behavior because the memory it is pointing to has been reclaimed by the OS.

    This is only one scenario, however, and many other things cause an iterator to be 'invalidated', and you must be careful to check the documentation of the objects you are using.

提交回复
热议问题