Returning a reference from a function in C++: which reasons are valid? The returned information is a large object, so returning a reference is more efficient than copying. The function's type must be an R-value.

Difficulty: Easy

Correct Answer: Only 1 is correct.

Explanation:

Introduction / Context:Functions in C++ may return by value, by lvalue reference, or by rvalue reference. Choosing to return a reference can avoid copying large objects or provide direct access to an existing object. This question evaluates two proposed reasons for returning a reference.

Given Data / Assumptions:

  • Returning a reference avoids copying and refers to an existing, still-valid object.
  • R-value refers to a temporary/prvalue, not a requirement for function return types.
  • Lifetime and aliasing safety must be considered.

Concept / Approach:Reason 1 is valid: returning a reference to an existing large object can be more efficient than copying (provided the referent outlives the use). Reason 2 is incorrect: a function's return type need not be an R-value; you explicitly choose a return type such as T, T&, or T&&. There is no rule that 'the type must be an R-value'.

Step-by-Step Solution:1) Evaluate 1: Large object → return T& when safe → avoids copying.2) Evaluate 2: Misconception; functions are free to return lvalues or rvalues depending on declared type.3) Conclude only statement 1 is correct.4) Choose 'Only 1 is correct.'

Verification / Alternative check:Inspect common APIs: 'operator[]' on std::vector returns T& for lvalue containers (to allow assignment). That leverages references for efficiency and semantics.

Why Other Options Are Wrong:Only 2 / Both 1 and 2 / Both incorrect: each incorrectly treats R-value as a mandate or denies the efficiency benefit of references.

Common Pitfalls:Returning a reference to a local variable (dangling). Ensure the referenced object's lifetime exceeds the caller's use.

Final Answer:Only 1 is correct.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion