c++ std::function 回调

c++ std::function callback

我有以下五个文件。

我正在尝试使用 std::function 回调从 one_a.cpp 调用 two_b.cpp 中的函数,但出现以下错误:

terminate called after throwing an instance of 'std::bad_function_call'
  what():  bad_function_call
Aborted (core dumped)

one_a.h

#include <functional>

using CallbackType = std::function<void()>;

class Car {
  public:
    void car_run(void);
    void car_stop(void);

    CallbackType f1;

private:
  CallbackType callbackHandler;
};

one_a.cpp

#include "one_a.h"
#include <iostream>

void Car::car_run(void)
{
    std::cout<<"Car running"<<std::endl;
}

void Car::car_stop(void)
{
    std::cout<<"Car stopping"<<std::endl;
}

two_b.h

#include "one_a.h"

class Boat {
  public:
    Boat(Car& car_itf);
    static void boat_run(void);
    static void boat_stop(void);
 private:
    Car& car_itf_;
};

two_b.cpp

#include "two_b.h"
#include <iostream>

Boat::Boat(Car& car_itf):car_itf_{car_itf}{
    car_itf_.f1 = std::bind(&Boat::boat_run);
}

void Boat::boat_run(void)
{
    std::cout<<"Boat running"<<std::endl;
}

void Boat::boat_stop(void)
{
    std::cout<<"Boat running"<<std::endl;
}

main.cpp

#include "two_b.h"

int main()
{
    Car bmw;
    bmw.car_run();
    bmw.f1();

    return 0;
}

可以在此处找到一个 运行 示例:

https://www.onlinegdb.com/_uYHXfZsN

std::function 如果您在未分配可调用目标的情况下尝试调用它,则会抛出 std::bad_function_call 异常。

因此,在尝试将 f1 作为函数调用之前,您需要实际将目标分配给 f1。您正在 Boat 的构造函数中进行该赋值,因此您需要先创建一个 Boat 对象,例如:

int main()
{
    Car bmw;
    Boat ferry(bmw); // <--
    bmw.car_run();
    bmw.f1();

    return 0;
}

Online Demo

此外,确保在 Boat 的析构函数中清除 f1,这样你就不会让 f1 悬空,例如:

Boat::~Boat(){
    car_itf_.f1 = nullptr;
}