无法使用 Lambda 创建 MenuItemImage

Failed to create MenuItemImage with Lambda

我正在尝试使用 Lambda 创建一个 MenuItemImage 来捕获触摸回调: 这很好用:

MenuItemImage* mYouTube = MenuItemImage::create("en_block3.png", "en_block3_hover.png",
        // lambda function handle onClick event
        [=](cocos2d::Ref *pSender) -> bool {
        auto scale = ScaleBy::create(0.5f, 1.1f);
        mYouTube->runAction(scale);
        return true;

    });

但是当我在 lambda 之外定义动作 scale 时,它没有按预期工作,Visual Studio 编译没有任何问题但是应用在单击菜单项时崩溃:

auto scale = ScaleBy::create(0.5f, 1.1f);
MenuItemImage* mYouTube = MenuItemImage::create("en_block3.png", "en_block3_hover.png",
        // lambda function handle onClick event
        [&](cocos2d::Ref *pSender) -> bool {
            mYouTube->runAction(scale);
            return true;
            });

知道导致此错误的原因吗?非常感谢您的帮助。

因为 scale 是局部变量,所以你必须像这样将它传递给 lambda 函数:

auto scale = ScaleBy::create(0.5f, 1.1f);
scale->retain();
MenuItemImage* mYouTube = MenuItemImage::create("en_block3.png", "en_block3_hover.png",
        // lambda function handle onClick event
        [&, scale](cocos2d::Ref *pSender) -> bool {
            mYouTube->runAction(scale);
            return true;
            });

另外,ScaleByRef class 的后代,因此它是一个自动释放 class。因为你不立即使用 scale 它将从内存中释放(0 引用计数)并在单击 mYouTube 按钮后导致崩溃。

这就是为什么你必须打电话给 retain()。但是当你不再需要它时(例如离开场景),你必须记得调用 release()。在我看来,最好在 lambda 函数中创建这个比例动画。您也可以编写一个简单的函数,它将创建 return scale 到位。