首页 > 解决方案 > 我们应该在使用 std::bind 之前检查一个不为空的函数吗?

问题描述

std::function<void(bool)> f;
std::function<void()> binded_f = std::bind(f, true);
std::cout << (f != nullptr) << " " << (binded_f != nullptr) << "\n";
f(true);
binded_f();

上面的代码给出了输出0 1,并在 MSVC 中binded_f()崩溃。Unhandled exception at 0x00007FFE7B63A388 in: Microsoft C++ exception: std::bad_function_call at memory location 0x00000096960FA660. occurred

好像调用null函数f没问题,std::bind应用后会崩溃。我们应该做什么?我们需要在绑定之前检查一个函数吗?

标签: c++c++11lambdastd-functionstdbind

解决方案


似乎在null这里调用函数输入代码f是可以的,而std::bind 应用后它会崩溃。我们应该做什么?

不,两者都

f(true);
binded_f();

将通过异常,您会看到第一个函数调用(即f(true);)本身的异常。来自cppreference.com std::function::operator()

例外

std::bad_function_callif*this不存储可调用函数目标,即!*this == true.

意思是,调用f显然是一个例外。

也为std::bind

例外

仅当从throws构造std::decay<F>::type 或 从相应 throws构造i 是第 i 个类型并且 是 in 中的第 i 个参数的任何构造函数时才抛出。std::forward<F>(f)std::decay<Arg_i>::typestd::forward<Arg_i>(arg_i)Arg_arg_iArgs... args

由于fthrows/ 的构造失败,绑定的对象也会在调用时出现异常。


我们需要在绑定之前检查一个函数吗?

是的,出于上述原因。


推荐阅读