CS 70

Example: An Iterator-Validity Violation

How about this code?

bool createList = true;       //  1
StringList::iterator iter;    //  2

if (createList) {             //  3
    StringList l;             //  4
    l.push_back("Moo");       //  5
    iter = l.begin();         //  6
    cout << *iter << endl;    //  7
}                             //  8

cout << *iter << endl;        //  9

iter ceases to be valid on line

Key Idea

  • If a container is destroyed, all of its iterators cease to be valid.

(When logged in, completion status appears here.)