Accessing a dangling reference

suggest change

It is illegal to access a reference to an object that has gone out of scope or been otherwise destroyed. Such a reference is said to be dangling since it no longer refers to a valid object.

#include <iostream>
int& getX() {
    int x = 42;
    return x;
}
int main() {
    int& r = getX();
    std::cout << r << "\n";
}

In this example, the local variable x goes out of scope when getX returns. (Note that lifetime extension cannot extend the lifetime of a local variable past the scope of the block in which it is defined.) Therefore r is a dangling reference. This program has undefined behavior, although it may appear to work and print 42 in some cases.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Undefined behavior:
* Accessing a dangling reference

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
71 Undefined behavior
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype