C++ for Embedded · Interview question

Is it safe to return a reference from a function?

A strong answer

Only if the referent outlives the function call. Returning a reference to a local variable is undefined behavior, the local's storage is reclaimed when the function returns, so the caller gets a dangling reference, exactly like returning a pointer to a local. It's safe and idiomatic to return a reference to something with a longer lifetime: a data member of the object (operator[] returning a reference into the object's array is the classic example, valid because the member lives as long as the object), a static, or an object the caller passed in. The danger is the same lifetime trap from C, just wearing reference syntax, and it can be subtler because there's no visible & at the call site to hint that you're holding an alias into something.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

References vs Pointers

References are aliases that can't be null and can't be reseated. When to reach for a reference, when you still need a pointer, and why const& is the default way to pass objects.

More References vs Pointers questions

Browse all 472 interview questions