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
,并且binded_f()
在MSVC中由于Unhandled exception at 0x00007FFE7B63A388 in: Microsoft C++ exception: std::bad_function_call at memory location 0x00000096960FA660. occurred
崩溃。
似乎调用null函数f
很好,而在应用std::bind
之后,它将崩溃。我们应该做什么?我们需要在绑定之前检查一个函数吗?
std::bad_function_call
已经发生在f(true)
。
[在调用f
时和在其上调用f
之前,都需要检查std::bind
是否在两种情况下都具有功能。
std::bind
需要一个Callable对象,并且std::function<void(bool)> f
本身是可调用对象。但是仅当调用f
拥有目标时才有效,因为调用std::forward时它将使用f
将调用转发到存储的目标。
似乎在调用
null
函数,在此处输入代码f
没问题,而在std::bind
之后应用,它将崩溃。我们该怎么办?
都不,都
f(true);
binded_f();
将通过例外。您会从f(true);
调用中看到异常。来自cppreference
例外
[
std::bad_function_call
,如果*this
不存储可调用项功能目标,即!*this == true
。
意味着,f
的调用显然是一个例外。
也用于std::bind
例外
仅抛出如果从[]构造
std::bind
e,则>std::decay<F>::typ
throws,或用于std::forward<F>(f)
来自相应std::decay<Arg_i>::type
引发,其中std::forward<Arg_i>(arg_i)
i是第i个类型,Arg_
是arg_i
中的第i个参数。