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:
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