Malvineous Malvineous - 1 year ago 77
C++ Question

Do C++ iterators hold a reference to the underlying object?

I can't seem to find much information about whether iterators keep hold of the underlying object they are iterating over.

If I create an iterator, then the object that supplied it goes out of scope, does the presence of the iterator prevent it from being destroyed?

Here is a very simple example just to illustrate the scenario:

// This class takes a copy of iterators to use them later
class Data {
Data(std::vector<int>::iterator start, std::vector<int>::iterator end)
: start(start),

void show() {
// Use this->start and this->end for some purpose

std::vector<int>::iterator start;
std::vector<int>::iterator end;

Data test() {
std::vector<int> v{1, 2, 3};
Data d(v.begin(), v.end());; // this would be ok
return d;

int main(void) {
Data d = test();; // What happens here?

In this example, the
object is storing a copy of the iterators, which is fine for the first
call. However by the time of the second
call, the original object that supplied the iterators no longer exists.

Do the iterators keep the object around until such time as they are all themselves destroyed, or are the iterators invalidated as soon as the original object goes out of scope?

Here is one reference of many which doesn't say what happens one way or the other (or even whether the result of this is 'undefined'.)

Answer Source

Iterators typically don't own the data over which they iterate, no. In fact, they're rarely (if ever) even aware of the object that owns the data; vector iterators, for example, are often just pointers, which have no knowledge of any vector or of its lifetime. Even those iterators that are not implemented as pointers (which is most of them) may be considered a kind of "pointer", and treated as such: they can quite easily become dangling.

Your example has UB because you'll dereference invalid iterators inside show() the second time.

If your container goes out of scope then all your iterators become invalidated. In fact, there are all manner of reasons why an iterator may become invalidated, such as adding to a vector when that operation results in a capacity expansion.

It's possible to find iterators that do kind of "own" data, instead of iterating over some collection found elsewhere (such as Boost's counting iterators), but these are magical properties that take advantage of C++ to provide a magical function, not an inherent property of iterators as defined by C++.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download