"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Do Const References Extend the Lifetime of Temporaries in C++?

Why Do Const References Extend the Lifetime of Temporaries in C++?

Published on 2024-11-07
Browse:680

Why Do Const References Extend the Lifetime of Temporaries in C  ?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3