I am trying to figure what happens in the code below (it was inspired by shared_ptr(unique_ptr&&)
constructor).
#include <iostream>
using namespace std;
class A {};
class B {
public:
B(const A&) {
cout << "ctor from A&\n";
}
};
void f(B&&) { cout << "f(B&&)\n"; };
void f(const B&) { cout << "f(const B&)\n"; }
int main() {
A a;
f(a);
}
I am trying to understand how it works. Why is an rvalue a result of the conversion and f(B&&)
called?
The function does not accept an object of type A
. However, it does accept an object of type B
, and A
is convertible to B
by virtue of the implicit converting constructor. The result of the conversion is a prvalue. The rvalue reference overload is a better match than the const lvalue reference when the argument is a prvalue.