Back to questions
JuniorDebuggingVery common
What happens if you return a reference to a local object?
#include <iostream>
const int& make_counter() {
int count = 0;
return count;
}
int main() {
const int& c = make_counter();
std::cout << c;
}Undefined behavior: count dies at return, so c refers to a dead variable
- Expecting the reference to keep
countalive: nothing extends a local's lifetime pastreturn, so readingcis undefined behavior. - Expecting a compile error: GCC and Clang warn by default, even without
-Wall, but the program still builds.
- How does copy elision (RVO/NRVO) make returning a large object by value cheap?
- Is returning a reference to a
staticlocal variable safe in a multithreaded program?
Fix
The reference c denotes count, and count is destroyed when make_counter returns. Return the int by value: main then gets a copy that lives as long as it is needed.
#include <iostream>
int make_counter() {
int count = 0;
return count;
}
int main() {
int c = make_counter();
std::cout << c; // 0
}