can someone help to understand why the following code causes an error:
float _f = 1;
std::function<float()> func = a;
std::cout << foo() << std::endl;
error: non-const lvalue reference to type 'float' cannot bind to a temporary of type 'float'
1 error generated.
std::function<float()> func, you're declaring
func as a functor returning a
float, not a
float&. As the error message said, the temporary
float returned by
func() can't be bound to non-const lvalue reference.
The above declaration doesn't match the signature of
A::operator() which being wrapped. But note that if change the type to
std::function<float&()> func to match the signature of
A::operator(), the compile error could be sovled, but then we'll return a reference bound to local variable, which leads to UB.
Note that for
std::function<float()> func = a;, std::function is initialized with a copy of
func() will return a reference bound to member of
A wrapped in
func, which is a local variable. And the reference will dangle when get out of function
How to fix it depends on your design, change
auto& foo() to
auto foo(), i.e. passing the return value by copy would avoid UB here.