Question

Are there any situations where you would prefer void fun(const T&&) over void fun(T&&) and void fun(const T&)?

Was it helpful?

Solution

There are some situations for preferring const T&& over T&&. For example, suppose you have a method that should only be called with a const lvalue reference, because the method stores the reference. In this case, it is good to add a deleted override for rvalue references, to avoid that a temporary object can be bound to a const lvalue reference.

void foo(const bar& b) { ... }
void foo(const bar&&) = delete;

If you have a method returning a const bar, the second overload will be chosen. It wouldn't work with T&& instead of const T&&.

const bar make_bar() { ... }
foo(make_bar()); // ERROR, foo is deleted.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top