Sub topic 2
Lifetime and dangling references
Lifetime and dangling references
An object holds a value. Its lifetime is the time during which it exists. A reference lets you access an object through another name, but it does not keep that object alive.
A dangling reference is a reference that can no longer safely access its object. This can happen when the object’s lifetime ends. For example, a function must not return a reference to a local variable: the variable stops existing when the function returns.
Using a dangling reference causes undefined behavior. C++ does not specify what the program will do.
References bound to temporaries
A temporary is a short-lived object, often created while evaluating an expression. Normally, it lasts until the end of the statement that created it.
There is an important exception: when a local const reference binds directly to a temporary, the temporary lasts as long as that reference. The example below uses this rule for view.
Passing a temporary to a function does not give it the same extension. It normally lasts only until the end of the statement containing the call. A reference returned by that function does not extend its lifetime.
References in range-based loops
A range-based loop visits each element in a collection. Use auto& to access each original element and change it. Use const auto& to read each element without copying it.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int main() {
const std::string& view = std::string("hello");
std::vector<int> values{1, 2, 3};
for (auto& value : values) {
value *= 2;
}
for (const auto& value : values) {
std::cout << value << ' ';
}
std::string name = "Ada";
std::cout << '\n' << view << ' ' << std::move(name) << '\n';
}A reference to a vector element can become dangling even while the vector still exists. For example, adding an element may make the vector move its elements to new storage. Avoid changing a vector’s size during a range-based loop over it.
Lvalues, xvalues, and prvalues
A value category describes how an expression refers to an object or produces a value.
- An lvalue identifies an object. In the example,
nameis an lvalue. - A prvalue produces a value or initializes an object.
std::string("hello")is a prvalue. - An xvalue identifies an object whose resources may be reused.
std::move(name)is an xvalue. Callingstd::movedoes not itself move anything.
Exercise
If a function returns a reference to its local variable, why is the reference unsafe?
Show answer
The local variable’s lifetime ends when the function returns, so the reference is dangling.