I guess there is something about temporary objects that I don’t understand.
Given the relationships:
class C {};
class F {
public:
C getC() { return C(); };
};
class N {
public:
N( C & base ){};
};
This works:
N n(C());
This doesn’t work:
F f;
N n(f.getC()); //compile error
Why?
A non-const reference (like
B& base) can only bind to an lvalue.F::getC()returns aCobject by value, so the call expressionf.getC()is an rvalue, not an lvalue.The reason that
N n(C());works, however, is due to an unrelated problem.This does not declare an object. It declares a function named
nthat returnsNand takes a parameter of type “pointer to a function that has no parameters and returnsC.”This is one manifestation of a language peculiarity known as the most vexing parse. To change this to declare an object, you’d need one of the following:
Both of these would fail to compile, though, because both would attempt to bind the result of the rvalue expression
C()to the non-const referenceB& base.A const reference (like
B const& base) can bind to an rvalue, as can an rvalue reference (likeB&& base) in C++11.