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()操作
CCL