有人可以帮我理解为什么下面的代码会导致错误吗?使用std ::函数来包装一个函数对象
class A
{
public:
float& operator()()
{
return _f;
}
private:
float _f = 1;
} a;
auto& foo()
{
std::function<float()> func = a;
return func();
}
int main()
{
std::cout << foo() << std::endl;
}
错误:
error: non-const lvalue reference to type 'float' cannot bind to a temporary of type 'float'
return func();
^~~~~~
1 error generated.
在这里,operator()
,我回到_f
参考,因此,我认为func()
不是暂时的。 如果有人帮助我理解,那将会很棒。
我也这么认为,因为它编译得很好,但恐怕它是UB,因为它看起来没有正确运行(例如它崩溃或打印0)。 –
我发现这个问题很有趣:如果你使它成为'auto&'和'',它可以工作;如果你使它成为'auto'并且''它也可以。哪一个是正确的?我觉得'auto'和''是正确的,因为你不应该通过引用返回本地变量,对吧? –
@MarsonMao是的,我们不应该返回引用绑定到本地,点'foo'应该通过复制在这里返回。 (为什么OP需要通过引用返回,这仍然是未知的。) – songyuanyao