Home > database >  Why function with rvalue parameter can't be forwarded in this way (without explicit type cast)?
Why function with rvalue parameter can't be forwarded in this way (without explicit type cast)?

Time:01-19

#include <iostream>

using namespace std;

struct A{};

void bar(A& a) {
    cout << "in bar A&";
}

void bar(A&& a) {
    cout << "in bar A&&";
}

void foo(A&& a) {
    bar(a);
}

int main()
{
    foo(A());
    return 0;
}

This pogram prints

in bar A&

instead of

in bar A&&

Regarding to the forwarding problem, void bar(A&& a) is a better choice than void bar(A& a) in this code. But why compiler doesn't pick it? How to properly explain it?

CodePudding user response:

when writing

void foo(A&& a) {
    bar(a);
}

you say that foo receives a rvalue, but as you do not move it to bar, foo remains owner of the a thus the only possible bar() call is a A&

If you want bar to take ownership, then move it (actually a cast to rvalue...):

void foo(A&& a) {
    bar(std::move(a));
}

should do what you expect...

CodePudding user response:

The && in the declaration of

void foo(A&& a)

only has an effect to the outside (caller) of the function, but (almost) not inside the function. To the caller, it says "I only accept rvalues".

Inside the function, there is almost no difference between && and &, in particular, a is an lvalue. For this reason, bar(A& a) is the only viable candidate.

  •  Tags:  
  • Related