C++ Iterator lifetime and detecting invalidation

Posted by DK. on Programmers See other posts from Programmers or by DK.
Published on 2012-06-27T08:48:59Z Indexed on 2012/06/27 9:22 UTC
Read the original article Hit count: 293

Filed under:
|
|
|

Based on what's considered idiomatic in C++11:

  • should an iterator into a custom container survive the container itself being destroyed?
  • should it be possible to detect when an iterator becomes invalidated?
  • are the above conditional on "debug builds" in practice?

Details: I've recently been brushing up on my C++ and learning my way around C++11. As part of that, I've been writing an idiomatic wrapper around the uriparser library. Part of this is wrapping the linked list representation of parsed path components. I'm looking for advice on what's idiomatic for containers.

One thing that worries me, coming most recently from garbage-collected languages, is ensuring that random objects don't just go disappearing on users if they make a mistake regarding lifetimes. To account for this, both the PathList container and its iterators keep a shared_ptr to the actual internal state object. This ensures that as long as anything pointing into that data exists, so does the data.

However, looking at the STL (and lots of searching), it doesn't look like C++ containers guarantee this. I have this horrible suspicion that the expectation is to just let containers be destroyed, invalidating any iterators along with it. std::vector certainly seems to let iterators get invalidated and still (incorrectly) function.

What I want to know is: what is expected from "good"/idiomatic C++11 code? Given the shiny new smart pointers, it seems kind of strange that STL allows you to easily blow your legs off by accidentally leaking an iterator. Is using shared_ptr to the backing data an unnecessary inefficiency, a good idea for debugging or something expected that STL just doesn't do?

(I'm hoping that grounding this to "idiomatic C++11" avoids charges of subjectivity...)

© Programmers or respective owner

Related posts about learning

Related posts about c++