2
如果我通過引用將一個從std :: function派生的對象傳遞給另一個函數,那麼程序在運行時總是會因bad_function_call錯誤而崩潰。如以下代碼表示:爲什麼通過引用傳遞從std :: function派生的對象會使程序崩潰?
#include<functional>
#include<iostream>
class foo :public std::function<int(void)> {
public:
int operator()(){return 1;}
};
void bar(const std::function<int(void)>& f) {std::cout << f() << std::endl;}
int main(){
foo f;
bar(f);
}
然而,如果功能對象是以值傳遞這樣的:
void bar(std::function<int(void)> f)
程序運行正常。我已經在gcc,clang和visual studio上測試過這個程序,結果是一樣的。什麼導致這個bad_function_call?
你爲什麼從'std :: function'派生。 AFAIK函數調用操作符不是虛擬的。 – NathanOliver
我知道派生自'std :: function'不是一個好習慣。我只是想知道爲什麼程序的行爲如此。 – qft