0Pricing
C++ Academy · Lesson

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;     // UB

All lessons in this course

  1. Why References Aliases for Variables
  2. Pass-by-Value vs Pass-by-Reference
  3. const References and When to Use Them
  4. Reference Lifetime and Dangling References
← Back to C++ Academy