以下代碼在y = anotherFunctor()
行上產生Segmentation Fault
。據我所知,發生這種情況是因爲當創建anotherFunctor
時globalFunctor
變量不存在。但是,如果我用GlobalFunctor
代替std::function<int(int)>
,它爲什麼會起作用?我將如何解決它?引用另一個全局仿函數中的全局仿函數
#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
創建一個臨時參考?