c++ - 我们应该在使用 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
应用后会崩溃。我们应该做什么?我们需要在绑定之前检查一个函数吗?
解决方案
似乎在
null
这里调用函数输入代码f
是可以的,而std::bind
应用后它会崩溃。我们应该做什么?
不,两者都
f(true);
binded_f();
将通过异常,您会看到第一个函数调用(即f(true);
)本身的异常。来自cppreference.com std::function::operator()
例外
std::bad_function_call
if*this
不存储可调用函数目标,即!*this == true
.
意思是,调用f
显然是一个例外。
例外
仅当从throws构造
std::decay<F>::typ
e 或 从相应 throws构造i 是第 i 个类型并且 是 in 中的第 i 个参数的任何构造函数时才抛出。std::forward<F>(f)
std::decay<Arg_i>::type
std::forward<Arg_i>(arg_i)
Arg_
arg_i
Args... args
由于f
throws/ 的构造失败,绑定的对象也会在调用时出现异常。
我们需要在绑定之前检查一个函数吗?
是的,出于上述原因。
推荐阅读
- laravel - 如何计算范围之间的平均created_at?
- jquery - 减少堆叠选项卡中的 padding-left
- mongodb - 如何使用 $elte 和 $gte 日期和 $elemMatch 更新 mongoDB 多个对象?
- ffmpeg - ffmpeg 为什么不打印元数据
- java - Java:计算单词的出现次数,程序计算“空”单词
- java - 从 jar 文件加载资源文件的问题
- android - 当前维护的cordova-plugin-crosswalk-webview 有什么替代方案吗?
- java - 从 MQ 消费消息
- c# - 将 WPF 窗口保持在任务栏上方而不获得焦点
- android - 无法在三星 S20、S20+ 和 S20 Ultra 上生成用于生物特征验证的密钥对