Cocos2dx 内存管理机制
来源:未知 责任编辑:责任编辑 发表时间:2014-03-23 22:25 点击:次
1.引用计数机制
要了解cocos2dx引用计数的机制,首先我们来看看CCObject这个类
class CC_DLL CCObject : public CCCopying { public: // object id, CCScriptSupport need public m_uID unsigned int m_uID; // Lua reference id int m_nLuaID; protected: // count of references unsigned int m_uReference; // count of autorelease unsigned int m_uAutoReleaseCount; public: CCObject(void); /** * @lua NA */ virtual ~CCObject(void); void release(void); void retain(void); CCObject* autorelease(void); CCObject* copy(void); bool isSingleReference(void) const; unsigned int retainCount(void) const; virtual bool isEqual(const CCObject* pObject); virtual void acceptVisitor(CCDataVisitor &visitor); virtual void update(float dt) {CC_UNUSED_PARAM(dt);}; friend class CCAutoreleasePool; };
说明:
● 当m_uReference=0时会自动释放该对象,每引用一次对象的时候,m_uReference会+1,当object被创建,会初始化为1.
● 当m_uAutoReleaseCount !=0时表示该对象自动释放(autorelease)。
●void
retain(void) 对m_uReference+1操作,可以防止对象被释放
●retainCount()
返回m_uReference值
● 跟踪一下void release()方法,我们会发现是对引用计数m_uReference进行-1操作,为0时删除对象
void CCObject::release(void) { CCAssert(m_uReference > 0, "reference count should greater than 0"); --m_uReference; if (m_uReference == 0) { delete this; } }
2.使用引用计数手动管理内存
因此,如果我们想手动来管理内存的释放,我们可以使用这样子,
CCSprite* sprite1=new CCSprite(); sprite1->initWithFile("CloseNormal.png"); CCLOG("sprite1 retain:%d",sprite1->retainCount());//sprite1 retain:1 this->addChild(sprite1); //addChild会对引用计数+1,可以跟踪看一下,最后会对object->retain()操作 CCLOG("sprite1 retain:%d",sprite1->retainCount());//sprite1 retain:2 sprite1->release(); CCLOG("sprite1 retain:%d",sprite1->retainCount());//sprite1 retain:1 this->removeChild(sprite1); //对m_uReference进行-1,跟踪一下会发现对object进行CC_SAFE_RELEASE()安全释放操作 CCLOG("sprite1 retain:%d",sprite1->retainCount());//sprite1 retain:-17891602
3.自动管理autorelease
还记得helloWorld里面怎么创建一个Sprite吗?
CCSprite* pSprite = CCSprite::create("HelloWorld.png");
跟踪CCSprite::create()
CCSprite* CCSprite::create(const char *pszFileName) { CCSprite *pobSprite = new CCSprite(); if (pobSprite && pobSprite->initWithFile(pszFileName)) { pobSprite->autorelease(); return pobSprite; } CC_SAFE_DELETE(pobSprite); return NULL; }
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>