Tom
Tom

Reputation: 799

Auto reference and iterators

What happens if std::vector::begin() is called but the returned iterator is assigned to a reference? Why does it work and where is the iterator value stored?

std::vector<int> v;
auto a = v.begin(); //I assume iterator is stored on the stack in variable "a".
auto& b = v.begin(); //What happens here?

Upvotes: 3

Views: 1196

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64308

This line

auto& b = v.begin();

is an error, because v.begin() returns a temporary, and you can't bind a temporary to a non-const reference.

Upvotes: 8

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

Nowhere. You have a dangling reference. Don't do this.

Most compilers will reject this, though certain versions of Visual Studio will pretend that you wrote const auto& and extent the temporary's lifetime. Where that temporary is stored is irrelevant.

Upvotes: 4

Related Questions