Questions / Quant development, C++ ownership & memory
Return a dead object
What is wrong with this C++ function?
const int& value() {
int x = 7;
return x;
}
Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.
Show the answer and worked solution
Answer: C. The returned reference outlives its local referent.
- x is an automatic local, so its lifetime ends when value returns. The return type asks the caller to keep referring to that object.
- The caller receives a dangling reference. Reading through it cannot be used to obtain a defined value of 7.
Interview shortcut. Never return a reference to a local.
Takeaway. A returned reference needs a referent that survives the call.
Why the other choices fail
- The const reference can extend x’s lifetime. Binding or returning a reference to this local does not extend the lifetime of x beyond its scope.
- The local can be copied to static storage on return. A reference return carries access to the existing object. It does not implicitly allocate a replacement in static storage.
- It may only fail if the caller stores the reference. Even an immediate read through the returned reference is undefined.
In the app this has a follow-up where one thing about the setup changes. Try the follow-up.