0

One thing has been bugging me for quite a while now. When passing a reference rvalue to a function parameter, I need to forward it explicitly when passing it to another function, otherwise the reference rvalue is lost.

void foo(const string&);
void foo(string&&);

void bar1(string&& x) { foo(std::move(x)); } // Calls foo(string&&)
void bar2(string&& x) { foo(std::forward<string>(x)); } // Calls foo(string&&)
void bar3(string&& x) { foo(x); } // Calls foo(const string&), why not foo(string&&)?

» Sample program «

I have no doubt about how and why bar1 and bar2 work.

What bugs me in bar3 is that its parameter is of type string&&, so when I call foo(x) I would expect the compiler to set a higher priority for a function with a signature that matches exactly the parameter, i.e. foo(string&&) instead of foo(const string&).

I’ve read this topic (which really looks like my problem) and this one (which is supposed to be a duplicate, except it’s not) but the answers weren’t very helpful.

What am I missing?

vdavid
  • 2,434
  • 1
  • 14
  • 15

0 Answers0