Return Values
Lesson outline
Return Value Optimization (RVO)
Modern compilers use copy elision (including RVO and NRVO) to remove temporary objects when returning by value. Since C++17, copy elision is guaranteed in certain cases (e.g., returning a prvalue created in the return statement). In practice, returning large objects by value is usually efficient.
Multiple Return Values
C++ doesn't have native multiple return values, but several idioms provide this functionality. Prefer structs (named fields) for readability, or tuples/pairs for quick returns.
Return Type Deduction
Since C++14, functions can use auto return type deduction. If you need to preserve references or cv-qualifiers from the return expression, use decltype(auto).
Error Handling
Instead of special return values, C++17+ offers safer alternatives like std::optional. (In C++23, consider std::expected for value-or-error results.)
What Not to Return (Lifetimes)
Never return references or views to temporaries or to local variables. Prefer returning by value (leveraging RVO) or ensure the referenced data outlives the function.
Guidelines
- Prefer returning by value; rely on copy elision and moves.
- Use tuples/pairs for quick multi-values; prefer structs for named fields.
- Use
autofor simple deduction; usedecltype(auto)when you intend to return references. - Use
std::optional(and C++23std::expected) instead of sentinel error codes. - Avoid returning references/views to data that won't outlive the function.