#include <iostream>
#include <functional>
using namespace std;
class Dispatcher
{
private:
std::function<void()> callback_;
public:
void addRequest(std::function<void()> callback)
{
callback_ = callback;
}
void start()
{
callback_();
}
};
class Worker
{
public:
void start(Dispatcher* dispatcher)
{
dispatcher->addRequest([=](){notifier();});
}
private:
void notifier()
{
bDone = true;
}
bool bDone{false};
};
int main()
{
Dispatcher* dispatcher = new Dispatcher();
Worker* worker = new Worker();
worker->start(dispatcher);
delete worker;//open this line to get a crash
dispatcher->start();
return 0;
}
如上代码所示:
- 虽然这行代码:dispatcher->addRequest([=](){notifier();});中使用了[=]这样的隐式值捕获,但是notifier这里其实还是引用到了this->notifier这样的。所以是隐式的引用到了this指针。
- delete worker以后this指针失效。
- dispatcher回调worker以后,走到worker的notifer中,操作成员数据bDone。
- 因为worker已经析构,crash。