Leonid Volnitsky Leonid Volnitsky - 4 months ago 35
C++ Question

When not to use std::forward with r-values?

What are the cases when

is not needed? It is used to wrap inner function argument which is templated-rvalue (that is, it can be lvalue or named-rvalue). Like in:

template<class T>
void outer(T&& t) {

I am guessing one case is when inner function parameters are passed by value. Are there other cases? I've got this question when I was writing
where Ct is templated-rvalue-ref.

EDIT about possible duplicate

If I remember correctly, this is 3rd attempt to close this 4yr old question as duplicate by some newbie who don't understand the question.

"Advantages of using forward?" and "When not to use std::forward with r-values?" are very different questions. First is introduction into r-values for beginners and second is discussion of perfect forwarding for advanced C++ user. I am author of meta-template library and lambda library, who don't need verbose description of basics. Information in answer is very different from other question.


I am answering to my own question as I didn't get satisfactory answer so far. If I will get even small improvement/addition to this - I will chose your answer as accepted.

In general std::forward will be beneficial with inner function if effect of perfect forwarding will be achieved. Otherwise it is superfluous.

Use std::forward to wrap inner function arg only if any of below is true:

  • inner function parameter is templated-rvalue-ref (now called "forwarding reference");
  • inner function has multiple overloads which differentiate based on parameter r/l-valueness;
  • inner function has multiple overloads which differentiate lvalue parameter based on constness;