JuniorDebuggingVery commonNot answered yet
What happens if you return a reference to a local object?
This function returns a reference, and the caller reads garbage or crashes intermittently. The compiler emits a warning under -Wall.
const std::string& greet() {
std::string msg = "hello";
return msg;
}
void use() {
const std::string& r = greet();
std::cout << r << '\n';
}
Identify the bug and explain the cause.
The local object is destroyed when the function returns. The returned reference is immediately dangling — any dereference is UB. Compilers warn with -Wall.
- ✗Thinking the reference 'might' work because the stack memory wasn't yet reused — it is still UB
- ✗Returning
const std::string&from a getter that builds the string locally — the temporary is destroyed - ✗Not noticing the compiler warning — it is almost always correct about dangling references
- →How does RVO/NRVO eliminate the cost of returning by value for large objects?
- →Is returning a
staticlocal reference safe in a multithreaded program?