Reputation: 113
Im using std::function and std::bind for my async thread callback system. but sometimes my system delete my object even some threads are not done. here some example code
#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
}
please help me to do this.
Upvotes: 2
Views: 241
Reputation: 218268
Instead of an raw pointer, you may use std::weak_ptr
, something like:
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 :)
}
Upvotes: 6
Reputation: 1547
This is because you are deleting pChar*
pointer which is used in your callback()
method. Delete pChar
after you are done with everything.
Upvotes: -1