在应用std :: bind之前,我们应该检查一个不为空的函数吗?

问题描述 投票:1回答:1
  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之后,它将崩溃。我们应该做什么?我们需要在绑定之前检查一个函数吗?

c++ lambda functional-programming stdbind
1个回答
0
投票

std::bad_function_call已经发生在f(true)

[在调用f时和在其上调用f之前,都需要检查std::bind是否在两种情况下都具有功能。

std::bind需要一个Callable对象,并且std::function<void(bool)> f本身是可调用对象。但是仅当调用f拥有目标时才有效,因为调用std::forward时它将使用f将调用转发到存储的目标。


0
投票

似乎在调用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个参数。

© www.soinside.com 2019 - 2024. All rights reserved.