Reference Lifetime and Dangling References
Avoid dangling references by reasoning about object lifetimes carefully.
What is a Dangling Reference?
A reference becomes dangling when the object it refers to has been destroyed. Using it is undefined behavior — anything can happen.
The Classic Example
Returning a reference to a local variable. The local dies when the function returns; the caller holds a reference to dead memory.
// BUG
int& bad() {
int x = 10;
return x; // x dies here
}
int& r = bad();
std::cout << r; // UBAll lessons in this course
- Why References Aliases for Variables
- Pass-by-Value vs Pass-by-Reference
- const References and When to Use Them
- Reference Lifetime and Dangling References