The C programming language allows const references to extend the lifetime of temporary objects. This behavior has been the subject of much debate, with some arguing that it allows for improved performance and flexibility in code design.
The origin of this language feature dates back to 1993, when it was proposed as a solution to an inconsistency in the handling of temporaries when bound to references. In the absence of return value optimization (RVO), prohibiting the binding of a temporary to a reference would have imposed performance penalties.
By allowing const references to extend the lifetime of temporaries, the committee aimed to eliminate this inconsistency, while preserving the potential performance benefits. This design choice enabled member functions to seamlessly switch between returning a value or a const reference to an existing internal value, without requiring modifications to client code.
For instance, consider a matrix class that can return row vectors or column vectors. To optimize performance, one or the other type of vector could be returned as a reference, depending on the implementation's internal organization (row-major or column-major storage). This flexibility allows the library writer to modify the implementation in the future without affecting client code, which would otherwise require explicit handling of the return value's type.
As a result, the committee's decision to extend the lifetime of temporaries when bound to const references serves a dual purpose: it ensures consistency in reference binding behavior and enables the implementation of optimized and adaptable code designs.
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