转载请注明: http://blog.csdn.net/herm_lib/article/details/9316601
项目中用到了cocos2dx和box2d,cocos2dx的内存是基于引用计数的,新建的内存一般加到一个自动的内存回收池中;而box2d的对象,是直接new/delete。
基于引用计数的对象和基于new/delete对象生命周期的结束是不一样的,前者有时比后者延后一帧(或者一个逻辑循环)才被删除。看一下实际遇到问题的代码。
class GameLayer : public cocos2d::CCLayer { public: GameLayer(); ~GameLayer(); static GameLayer* create(); private: virtual void onEnter(); private: // static b2World* m_phyWorld; b2World* m_phyWorld; }; // b2World* GameLayer::m_phyWorld = nullptr; GameLayer::GameLayer() { m_phyWorld = nullptr; } GameLayer::~GameLayer() { delete m_phyWorld; } GameLayer* GameLayer::create() { GameLayer* layer = new GameLayer; layer->autorelease(); return layer; } void GameLayer::onEnter() { // 删除上一次进关卡生成的物理对象 // delete m_phyWorld; m_phyWorld = new b2World(b2Vec2(0.0f, -10.0f)); MonsterSprite* monsterSprite = Monster::create(m_phyWorld);
addChild(monsterSprite); CCLayer::onEnter(); }
class MonsterSprite : public cocos2d::CCSprite { private: b2World* m_phyWorld; b2Body* m_phyBody; }; MonsterSprite* MonsterSprite::create(b2World* phyWorld) { MonsterSprite* monsterSprite = new MonsterSprite(phyWorld); MonsterSprite->autorelease(); return MonsterSprite; } MonsterSprite::MonsterSprite(b2World* phyWorld) { m_phyWorld = phyWorld; m_phyBody = phyWorld->CreateBody(...); } MonsterSprite::~MonsterSprite() { m_phyWorld->DestoryBody(m_phyBody); }