dwelch91
dwelch91

Reputation: 23

vector::at reference

Given this definition:

vector<some_struct_t> lots_of_stuff;

And the fact that vector::at returns a reference, this code makes sense to me:

some_struct_t & ref_element = lots_of_stuff.at(0);

But, this code also compiles and seems to work:

some_struct_t val_element = lots_of_stuff.at(0);

How can a non-reference work here? Is a copy constructor being invoked? Why does this work?

Upvotes: 2

Views: 178

Answers (2)

sellibitze
sellibitze

Reputation: 28097

A reference of type T is simply an lvalue expression of type T just like a variable's name of type T is an lvalue expression of T. So, ...

vector<T> v = ...;
T a = ...;
T b = a;
T c = v.at(0);

there is little difference between how b and c are initialized because on the right hand side is simply an lvalue expression of type T and this leads to a copy-initialization.

I think the reason why you ask this question is that you think a reference is itself an object-type like the type of a pointer is an object type. But this is not the case. Expressions never have a reference type. Reference types are simply used to turn rvalue into lvalue expressions. The type of the expressions is the same. But its "value category" changes.

Upvotes: 0

Stephen Chu
Stephen Chu

Reputation: 12832

The non-reference one does a copy from the returned reference to your object. Changes to your object will not be applied to the object in the vector, as the reference version does.

Upvotes: 6

Related Questions