下面的代码产生一个Segmentation Fault
就y = anotherFunctor()
行了。据我了解,发生这种情况是因为创建globalFunctor
时变量不存在anotherFunctor
。std::function<int(int)>
但是,如果我用替换它为什么会起作用GlobalFunctor
?我将如何解决它?
#include <functional>
struct GlobalFunctor
{
int operator()() const { return 42; }
};
extern GlobalFunctor globalFunctor;
struct AnotherFunctor
{
AnotherFunctor() : g_(globalFunctor) {}
int operator()() const { return g_(); }
const std::function<int()>& g_;
} anotherFunctor;
GlobalFunctor globalFunctor;
int main()
{
AnotherFunctor af;
int x = af();
int y = anotherFunctor();
int z = x + y;
return 0;
}
编辑:我尝试用clang
而不是编译gcc
它,它警告我binding reference member 'g_' to a temporary value
——但是编译它时它崩溃了。演员会std::function
创建一个临时参考吗?