c++ - 如何检测我的 std::function 仍然可用?

标签 c++ c++11

我正在使用 std::function 和 std::bind 作为我的异步线程回调系统。 但有时我的系统会删除我的对象,即使某些线程尚未完成。 这是一些示例代码

#include <iostream>
#include <functional>

using namespace std;

class Character {
public:
    Character() { a = 10; }

    void Print() { cout << a << endl; }

private:
    int a;

};

void main() {
    Character* pChar = new Character();

    std::function<void()> callback = std::bind(&Character::Print, pChar);
    callback(); // it's fine

    delete pChar;


    callback(); // fail


    if (callback)   // this if doesn't work
        callback();

    // i want to check callback is still available
}

请帮我做到这一点。

最佳答案

您可以使用 std::weak_ptr 代替原始指针,例如:

void safePrint(std::weak_ptr<Character> w)
{
    auto pChar = w.lock();
    if (pChar) {
        pChar->Print();
    }
}

int main() {
    auto pChar = make_shared<Character>();

    auto callback = std::bind(&safePrint, std::weak_ptr<Character>(pChar));
    callback(); // it's fine

    pChar.reset(); 

    callback(); // won't print, and don't crash :)
}

关于c++ - 如何检测我的 std::function 仍然可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47346180/

相关文章:

c++ - 为什么 C++ 模板使用尖括号语法?

c++ - 比较和交换 : synchronizing via different data sizes

c++ - 大括号封闭的初始化列表构造函数

c++ - 使用 SFINAE 检查类型是否可以绑定(bind)到模板模板参数

c++ - protobuffer 可以自动填充新创建对象的默认值

c++ - 在 C++ 中调用参数作为对未知边界数组的引用

c++ - 快速随机字符串

c++ - 使用后自动释放内存

c++ - 减少持久数据结构中的shared_ptr数量

c++ - 错误地使用 move 的值