Cocos2d-x:0xC0000005:访问冲突读取位置0xCDCDCDD1

时间:2013-10-30 14:47:09

标签: c++ cocos2d-x

大家:

问题很奇怪。我先粘贴代码。

void GameObjectsLayer::updateEnemy(float interval)
{
    UNREFERENCED_PARAMETER(interval);
    Enemy *lpEnemy = new Enemy("enemy1.png", 1, 10, 8);
    lpEnemy->getSprite()->setAnchorPoint(CCPointZero);
        lpEnemy->setPosition(ccp(-30, 400));
    CCMoveTo *lpMoveAction = CCMoveTo::create(350.0f / ENEMY1_MOVE_SPEED, ccp(320, lpEnemy->getPosition().y));
    CCCallFuncND *lpCallback = CCCallFuncND::create(lpEnemy->getSprite(), callfuncND_selector(GameObjectsLayer::removeEnemy), lpEnemy);
    CCSequence *lpSeqActions = CCSequence::create(lpMoveAction, lpCallback, NULL);
    this->addChild(lpEnemy->getSprite(), 10);
    lpEnemy->getSprite()->runAction(lpSeqActions);
    // When I set the breakpoint here, the _vEnemies is valid and the application runs well.
    _vEnemies->push_back(lpEnemy);
}

void GameObjectsLayer::removeEnemy(CCNode *lpSender, void *lpParam)
{
    Enemy *lpEnemy = (Enemy*)lpParam;
    lpEnemy->getSprite()->stopAllActions();
    this->removeChild(lpSender);
    // When access the _vEnemies variable here, the exception occurs at "_vEnemies->begin()"
    // I set a breakpoint here, the address of _vEnemies is invalid, but I set a breakpoint in the previous function, the _vEnemies has a valid address, what happened? I really can't comprehend the behavior. _vEnemies is the member variable of this class.
    std::vector<Enemy*>::iterator iter = _vEnemies->begin();
    while (iter != _vEnemies->end())
    {
        if (lpEnemy == *iter)
        {
            this->removeChild(lpEnemy->getSprite());
            //delete *iter;
            iter = _vEnemies->erase(iter);
            continue;
        }
        ++iter;
    }
    delete lpEnemy;
}

这两个方法用于两个CCSchedules,它们在init()方法中初始化,代码如下:

bool GameObjectsLayer::init()
{
    bool bRet = false;
    do
    {
        /* not important, omit them */

        this->schedule(schedule_selector(GameObjectsLayer::updateEnemy), 5.0f);
        this->schedule(schedule_selector(GameObjectsLayer::enemyShoot), 1.0f);

        scheduleUpdate();

        bRet = true;
    }
    while (0);

    return bRet;
}

我头疼。我不知道发生了什么。我的cocos2d-x的版本是2.1.5,IDE是VS2012。谢谢你的帮助......

1 个答案:

答案 0 :(得分:0)

嗯,这是一个旧的,但对于那些可能在这里跌跌撞撞的人来说:

问题似乎在这一行

CCCallFuncND *lpCallback = CCCallFuncND::create(lpEnemy->getSprite(), callfuncND_selector(GameObjectsLayer::removeEnemy), lpEnemy);

此签名(来自docs)是

static CCCallFuncND* create ( CCObject *pSelectorTarget, 
                              SEL_CallFuncND selector,
                              void * d 
                            )   

*pSelectorTarget是调用selector的对象。因此,在此示例中,它应为this而不是lpEnemy->getSprite()

坦率地说,我觉得它早些时候没有崩溃似乎有点奇怪。