From § 17.6.4.9 of ISO/IEC 14882:2011(E) (C++11):
Each of the following applies to all arguments to functions defined in the C++ standard library, unless explicitly stated otherwise.
[snip]
— If a function argument binds to an rvalue reference parameter, the implementation may assume that this parameter is a unique reference to this argument.
This specification only applies to standard library functions, but it seems like the whole point of rvalue references is for this kind of assumption to be possible. If I have a function that takes an rvalue reference and pass it one (either through a temporary or std::move
), can the implementation legally perform optimizations that assume it's unique? If not, do any implementations do so anyway?
The language does not itself mandate that an rvalue reference cannot alias any other object, this is simply a stated pre-condition of standard library functions. So if by "implementation" you mean the compiler, then no - the compiler will not perform any optimizations based on this requirement, certainly not in code that you write.
If a particular compiler has some kind of extensions that allow code to convey aliasing information, then that pre-condition makes it is possible for standard library functions to take advantage of such extensions. That kind of aliasing information may make it possible for the compiler to perform some optimizations.
In any case, the main consequence of the statement is that the standard library implementation does not need to behave reasonably in the face of unreasonable aliasing of function parameters. For example, if you construct a pair with
std::vector<int> some_vector(100, 42);
auto p = std::make_pair(std::move(some_vector), some_vector);
there's no guarantee that p.first == p.second
.
The absence of a requirement like this for lvalue reference parameters means that the standard library has to do some crazy things to make sure that code like vector.insert(vector.end(), vector[3])
works even if the vector has to be reallocated. I imagine the committee thought it was unrealistic for implementations to detect rvalue aliasing and have to maybe-move-only-sometimes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With