#include <iostream>
class Foo { };
Foo createFoo() { return Foo(); }
void bar(Foo &&) { std::cout << "in bar(Foo &&)\n"; }
void bar(Foo const &) { std::cout << "in bar(Foo const &)\n"; }
void baz(Foo &&f) {
std::cout << "in baz, ";
bar(f);
// bar(std::move(f));
}
int main()
{
baz(createFoo());
return 0;
}
My expected output is: in baz, in bar(Foo &&), but I’m getting: in baz, in bar(Foo const &). If I switch the calls to bar (see the comment) I get the expected output, but this seems wrong to me. Is there some reason the compiler can’t call bar(Foo &&) without me converting a Foo&& to a Foo&&?
Thanks in advance!
Inside
baz(Foo&& f),fis an lvalue. Therefore, to pass it on tobaras an rvalue reference you have to cast it to an rvalue. You can do this with astatic_cast<Foo&&>(f), or withstd::move(f).This is to avoid accidentally moving things multiple times in the same function e.g. with multiple calls to
bar(f)insidebaz.