Search code examples
c++containersinvalidation

What does container invalidation in C++ mean?


I learned today about the term invalidation in context of C++ containers. Can anyone explain what it means?

It seems like you're not allowed to modify elements of a container in some way when looping over the container. But what way exactly?

Please help me understand this topic.

Thanks, Boda Cydo.


Solution

  • Containers don't become invalidated -- iterators referring to elements in containers become invalidated.

    An iterator is a handle to a particular item within a container. The iterator is valid so long as that item remains inside the container, and the container does not internally rearrange itself. An iterator is invalidated when one of those two things happens, since afterwords the iterator is no longer valid as a handle into the container.

    The most obvious way to invalidate an iterator is to remove its referred-to item from the collection, e.g.:

    std::set<int> s;
    
    s.insert(4);
    s.insert(2);
    
    std::set<int>::iterator itr = s.find(4); // itr is a handle to 4
    
    std::cout << *itr << std::endl; // prints 4
    
    s.erase(4); // removes 4 from collection, invalidates itr
    
    std::cout << *itr << std::endl; // undefined behavior
    

    The more subtle way to invalidate an iterator is to cause the container to internally rearrange itself (e.g. reallocate its internal storage). This can be done, for example, by causing certain types of containers to expand:

    std::vector<int> v;
    
    v.push_back(4);
    v.push_back(2);
    
    std::vector<int>::iterator itr = v.begin(); // itr is a handle to 4
    
    std::cout << *itr << std::endl; // prints 4
    
    v.push_back(12); // MIGHT invalidate itr, if v expands its internal allocation
    

    You can prevent this in some containers by pre-reserving space:

    std::vector<int> v;
    
    v.reserve(3); // Pre-allocate 3 elements
    
    v.push_back(4);
    v.push_back(2);
    
    std::vector<int>::iterator itr = v.begin(); // itr is a handle to 4
    
    std::cout << *itr << std::endl; // prints 4
    
    v.push_back(12); // WILL NOT invalidate itr, since it will never cause v to expand
    

    The documentation for each STL container should describe under what circumstances iterator invalidation will or might occur.