2013-01-07 56 views
1

以下代碼在y = anotherFunctor()行上產生Segmentation Fault。據我所知,發生這種情況是因爲當創建anotherFunctorglobalFunctor變量不存在。但是,如果我用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創建一個臨時參考?

回答

1

g_(globalFunctor)globalFunctor必須被轉換到一個std::function,因爲它是GlobalFunctor類型。所以產生一個臨時的,這是必然的參考。您可以將代碼視爲g_(std::function<int()>(globalFunctor))。然而,這個臨時存在直到構造函數結束,因爲在C++中有一個特殊的規則,即成員初始化符列表中的臨時對象只存在於構造函數的末尾。這給你一個懸而未決的參考。

代碼在您將std::function<int(int)>替換爲GlobalFunctor時適用,因爲不涉及任何轉換。因此,不會產生臨時對象,而且引用直接指向全局對象。

您或者不需要使用引用並在內部存儲std::function或者創建一個全局std::function並且有一個引用。