Questions / Quant development, C++ ownership & memory

Return a dead object

Foundation, about 6 minutes. Question D014.

What is wrong with this C++ function?

const int& value() {
    int x = 7;
    return x;
}
  1. AThe const reference can extend x’s lifetime.
  2. BThe local can be copied to static storage on return.
  3. CThe returned reference outlives its local referent.
  4. DIt may only fail if the caller stores the reference.

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.

  1. x is an automatic local, so its lifetime ends when value returns. The return type asks the caller to keep referring to that object.
  2. 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.

More c++ ownership & memory questions