Why is the object I'm passing to ClassA
's constructor considered an rvalue (temporary)? I'm aware that setting the parameter to const
will make the error go away but I want to understand what's going on.
This behavior works fine for a function call but not for a constructor?
#include <iostream>
using namespace std;
class ClassA {
public:
ClassA() {}
ClassA(ClassA&) {}
};
void f(ClassA&) {}
int main() {
ClassA a;
// Invalid initialization of non-const reference of type 'ClassA&' from an
// rvalue of type 'ClassA'
ClassA b = ClassA(a);
// Works fine
f(a);
return 0;
}