首页 > 解决方案 > std::bind 与 nullptr 指针

问题描述

如果我将 传递nullptrstd::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;
}

上面的程序抛出了分段错误。

标签: c++stdbind

解决方案


无法访问由返回的函数对象的绑定参数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"

推荐阅读