这是我的代码:
void StoreHelper::buyProduct(int productId, const std::function<void()>& succeded, const std::function<void()>& failed) {
//dummy code to wait 2 seconds, it'll send a request here
Director::getInstance()->getRunningScene()->getChildren().at(0)->runAction(Sequence::createWithTwoActions(DelayTime::create(2.0f), CallFunc::create([&, succeded](){
succeded(); //EXC_BAD_ACCESS
})));
}
在buyProduct主代码中调用succeded()
即可。但是,当我在2秒后调用它时,即使我在捕获列表中传递了该函数,也使EXC_BAD_ACCESS使应用程序崩溃:
但是,如果我将std :: function存储在这样的类实例中:
void StoreHelper::buyProduct(int productId, const std::function<void()>& succeded, const std::function<void()>& failed) {
succededCallback = succeded;
//dummy code to wait 2 seconds, it'll send a request here
Director::getInstance()->getRunningScene()->getChildren().at(0)->runAction(Sequence::createWithTwoActions(DelayTime::create(2.0f), CallFunc::create([&](){
succededCallback();
})));
}
它有效,但并非总是如此。有时它还是会因相同的错误而崩溃。
这是什么原因?是因为它从内存中回收了吗?我该如何预防?最好不要将std::function
存储在类实例中,而只需将其传递给lambda函数即可。
编辑:
这是不使用cocos2d-x操作的简化代码:
void StoreHelper::buyProduct(int productId, const std::function<void()>& succeded, const std::function<void()>& failed) {
std::async(std::launch::async, [&, succeded] () {
std::this_thread::sleep_for( std::chrono::seconds{2});
succeded();
});
}
用法:
buyProduct(12345, [&]() {
//success
}, [&]() {
//failed
});
此简化版本有效!这可能是线程问题吗?