Extension of Rvalue Lifetime by Const References
In C , const references not only serve as immutable aliases but also extend the lifetime of temporaries. Why did the C committee decide to implement this behavior?
One rationale for this feature is to conceal implementation details from classes and functions. Consider a matrix class that can return row vectors or column vectors. To optimize performance, the class may choose to return a reference to an internal value based on its row-major or column-major organization. By requiring clients to accept return values as const references, the class can switch between references and values seamlessly, shielding clients from implementation details.
Historically, the decision to extend rvalue lifetime stemmed from the desire to address inconsistencies in how references handled temporaries in 1993. At that time, RVO (return value optimization) did not exist. Prohibiting the binding of temporaries to references would have penalized performance significantly. Thus, the committee opted for a solution that allowed the binding while extending the lifetime of temporaries to ensure their availability during reference use.
This rationale is documented in proposal N0345.pdf, submitted to the C standards committee in 1993. By extending the lifetime of rvalues, const references facilitate better abstraction, maintain code flexibility, and optimize performance when returning objects from functions.
The above is the detailed content of Why Do Const References Extend the Lifetime of Temporaries in C ?. For more information, please follow other related articles on the PHP Chinese website!