【发布时间】:2017-04-11 17:00:51
【问题描述】:
如果我通过引用将派生自 std::function 的对象传递给另一个函数,程序总是在运行时崩溃并出现 bad_function_call 错误。如下代码所示:
#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 函数调用运算符不是虚拟的。 -
我知道从
std::function派生不是一个好习惯。我只是想知道为什么程序会这样。
标签: c++ c++11 std-function