Search code examples
c++standardslanguage-designtemporary-objectsconst-reference

Why do const references extend the lifetime of rvalues?


Why did the C++ committee decide that const references should extend the lifetime of temporaries?

This fact has already been discussed extensively online, including here on stackoverflow. The definitive resource explaining that this is the case is probably this GoTW:

GotW #88: A Candidate For the “Most Important const”

What was the rationale for this language feature? Is it known?

(The alternative would be that the lifetime of temporaries is not extended by any references.)


My own pet theory for the rationale is that this behavior allows objects to hide implementation details. With this rule, a member function can switch between returning a value or a const reference to an already internally existent value without any change to client code. For example, a matrix class might be able to return row vectors and column vectors. To minimize copies, either one or the other could be returned as a reference depending on the implementation (row major vs column major). Whichever one cannot be returned by reference must be returned by making a copy and returning that value (if the returned vectors are contiguous). The library writer might want leeway to change the implementation in the future (row major vs column major) and prevent clients from writing code that strongly depends on if the implementation is row major or column major. By asking clients to accept return values as const ref, the matrix class can return either const refs or values without any change to client code. Regardless, if the original rationale is known, I would like to know it.


Solution

  • It was proposed in 1993. Its purpose was to eliminate the inconsistent handling of temporaries when bound to references.

    Back then, there was no such thing as RVO (return value optimization), so simply banning the binding of a temporary to a reference would have been a performance hit.

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0345.pdf