1#include <iostream> 2#include <functional> 3using namespace std; 4class Dispatcher 5{ 6private: 7 std::function<void()> callback_; 8public: 9 void addRequest(std::function<void()> callback) 10 { 11 callback_ = callback; 12 } 13 void start() 14 { 15 callback_(); 16 } 17}; 18 19class Worker 20{ 21public: 22 void start(Dispatcher* dispatcher) 23 { 24 dispatcher->addRequest([=](){notifier();}); 25 } 26private: 27 void notifier() 28 { 29 bDone = true; 30 } 31 bool bDone{false}; 32}; 33 34int main() 35{ 36 Dispatcher* dispatcher = new Dispatcher(); 37 Worker* worker = new Worker(); 38 worker->start(dispatcher); 39 delete worker;//open this line to get a crash 40 dispatcher->start(); 41 return 0; 42}
如上代码所示:
- 虽然这行代码:dispatcher->addRequest([=](){notifier();});中使用了[=]这样的隐式值捕获,但是notifier这里其实还是引用到了this->notifier这样的。所以是隐式的引用到了this指针。
- delete worker以后this指针失效。
- dispatcher回调worker以后,走到worker的notifer中,操作成员数据bDone。
- 因为worker已经析构,crash。