Now, I have a problem with lambdas, as you can see in the codes below, if this pointer ( the HelloWorld node) destroy, the code in lambdas will crash the app.
Could I solve this problem with std::shared_ptr? Could someone give me some suggestions regarding this problem? Thanks,
bool HelloWorld::init()
{
if ( !Scene::init() )
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
auto label = Label::createWithTTF("Hello World", "fonts/arial.ttf", TITLE_FONT_SIZE);
label->setPosition(Vec2::ZERO);
this->addChild(label, 1);
auto downloader = new (std::nothrow) network::Downloader();
downloader->setOnTaskError([this](const network::DownloadTask& task, int error_code, int error_internal_code, const std::string& error_string) {
});
downloader->onTaskProgress = [this](const network::DownloadTask& task,int64_t /*bytesReceived*/,int64_t totalBytesReceived, int64_t totalBytesExpected) {
};
downloader->onDataTaskSuccess = [this,label,origin,visibleSize](const cocos2d::network::DownloadTask& task, std::vector<unsigned char>& buffer) {
Director::getInstance()->getScheduler()->performFunctionInCocosThread([=]() {
//the "this" pointer destroyed before that lambda is invoked.
//so the app will crash here
if (auto image = utils::findChild<ui::ImageView*>(this, "image")) {
image->loadTexture("test.png");
}
//same with above
if(label) {
label->setPosition(origin.x + visibleSize.width/2,origin.y + visibleSize.height - label->getContentSize().height);
}
});
};
}
1 post - 1 participant