Domanda

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

È stato utile?

Soluzione

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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top