c++ - std::bind 与 nullptr 指针
问题描述
如果我将 传递nullptr
给std::bind
函数,我如何检查 的有效性std::function
?
// Example program
#include <iostream>
#include <string>
#include <functional>
class A
{
std::string si;
public:
A(std::string s) : si(s) {}
int getData(std::string x) {
si += x;
return si.size(); }
};
A* getA()
{
return nullptr;
}
int main()
{
auto fun = std::bind(&A::getData, getA(), std::placeholders::_1);
if (getA() == nullptr)
std::cout << "nullptr";
std::cout << "output : " << fun("str");
return 0;
}
上面的程序抛出了分段错误。
解决方案
无法访问由返回的函数对象的绑定参数std::bind
。
您可以在绑定之前检查指针是否为空:
if(A* ptr = getA())
{
auto fun = std::bind(&A::getData, ptr, std::placeholders::_1);
如果您确实需要一个可以从外部访问其绑定参数的函数对象,那么您需要编写一个命名函数对象类型。例如:
struct Fun {
A* ptr;
int operator()(const std::string& x) {
return ptr->getData(x);
}
};
auto fun = Fun{ .ptr = getA() };
if (fun.ptr)
// is "valid"
推荐阅读
- json - 如何使用 $lte 从 json 中过滤掉字符串值
- javascript - 为什么使用“切片”复制的JS数组不等于其源数组
- python - 当我将 keras 导入 python 时,如何解决这个错误?
- angular - 侧边菜单中的更新指令 - Ionic4/Angular
- pine-script - 显示计算结果而不是输入
- c# - 如何使用 BoardCastReceiver 识别哪张 SIM 卡收到了短信?
- r - 如何在指定日期范围内获取 R 中时间序列的每小时平均值?
- python - 在 Pyspark 中选择日期相隔超过 6 个月的记录
- python - 如何制作与字符串值对应的整数索引?
- python - 如何使用fillna方法