Reference Lifetime Extension
This lesson deals with the lifetime of temporary objects.
We'll cover the following...
What happens in the following case:
Press + to interact
#include <iostream>#include <vector>using namespace std;std::vector<int> GenerateVec() {return std::vector<int>(5, 1);}int main() {const std::vector<int>& refv = GenerateVec();cout << refv.size();}
Is the above code safe?
Yes - the C++ rules say that the lifetime of a temporary object bound to a const
reference is prolonged to the lifetime of the reference itself.
Here’s a full example quoted from the standard (Draft C++17 - N4687) 15.2 Temporary objects [class.temporary]:
Example:
struct S { S(); S(int); friend S operator+(const S&, const S&); ~S(); }; S obj1; const S& cr = S(16)+S(23); S obj2;
The expression
S(16) + S(23)
creates three temporaries: a first temporary ...