gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:53 26 4
gpt4 key购买 nike

我将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com