Would you ever mark a C++ RValue reference parameter as const
So, the question. Does it make any sense to mark an rvalue reference as const when passing as a parameter?
Here is one place this is done in the C++11 standard:
template <class T> reference_wrapper<T> ref(T&) noexcept;
template <class T> reference_wrapper<const T> cref(const T&) noexcept;
template <class T> void ref(const T&&) = delete;
template <class T> void cref(const T&&) = delete;
I.e. A const T&&
is used to capture all rvalues, const or not, and toss them to a compile-time error, while allowing lvalues, even const
lvalues to bind and work.
Now this could also probably be done with T&&
and an enable_if
constraint. But if there's one thing that C++ has taught us over the past few decades: Don't burn any bridges in language design. The C++ programmer will often find a clever way to use a language feature that was initially thought useless. And it is in that spirit that const T&&
was left as a legal option.
Another possible use case, that was not taken by the language, but could have been, is smart pointers constructor from raw pointer, e.g.:
// this is NOT the actual ctor in the language but could have been
// see explanation in above link
unique_ptr(T* const&& p) : ptr{p} {}