I understand the use of foo(const int& a)
. This can be used to call something like foo(1)
where for foo(int& a)
will fail.
Now experimenting I created this class:
class temp {
public:
int a;
temp(int x = 5) : a(x) {}
void foo_val(temp a) { /* ... */ }
void foo_ref(temp& a) { /* ... */ }
};
void main() {
temp temp1(6);
temp1.foo_val(temp1); // foo_val(temp a) is called
temp1.foo_ref(temp()); // foo_ref (temp& a) is called
}
What I don't understand is why does the temp1.foo_ref(temp())
succeed. How can we have a reference with a rvalue (temp()
in this case). I was expecting it to succeed only with foo_ref(const temp& a)
. Am I thinking about rvalue incorrectly.