A reference is an alias. An alternate name for the referred to object.
Ask yourself, what is the lifetime of object t?
When is it created?
When is it destroyed?
One can either create a copy (a new object) or refer to existing object.
Making a copy is cheap for simple objects.
Modifying a copy does not modify the original object.
A reference is valid only as long as the referred to object is valid.
There is also move semantics since C++11.
The function that you have posted should not return a reference. Not only does the reference lack any benefit, but the construct is dangerous.
In this code there are calls to functions that return a reference. Do you know where?
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <vector>
#include <iostream>
int main() {
std::vector<int> foo(7, 0);
foo[0] = 42;
for ( const auto & x : foo )
std::cout << x << '\n';
return 0;
}
|