Cocos2d-x::内存管理

前端之家收集整理的这篇文章主要介绍了Cocos2d-x::内存管理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一、Cocos2d-x拷贝机制

1.CCCopying
CCObject从CCCopying继承而来,而CCCopying拥有唯一的一个成员函数copyWithZone,这个函数可以认为是拷贝的一个协议,所有继承CCObject需要实现拷贝功能可以通过它来实现,源码:
CCObject* CCCopying::copyWithZone(CCZone* pZone)
{
CC_UNUSED_PARAM(pZone);
CCAssert(0.”not implement”);
return 0;
}
2.CCObject子类拷贝
CCObject* CCObject::copy()
{
return copyWithZone(0);
}
3.CCArry
3.1 CCArray拷贝
CCArray* CCArray::createWithArray(CCArray* otherArray)
{
CCArray* pRet = (CCArray *)otherArray->copy();
pRet->autorelease();
return pRet;
}
3.2 copyWithZone实现
CCObject* CCArray::copyWithZone(CCZone* pZone)
{
CCAssert(pZone == NULL,”CCArray should not be inherited.”);
CCArray* pArray = new CCArray();
pArray->initWithCapacity(this->data->num>0?this->data->num:1);
CCObject* pObj = NULL;
CCObject* pTmpObj = NULL;
CCARRAY_FOREACH(this,pObj)//遍历CCArray成员
{
pTmpObj = pObj->copy();
pArray->addObject(pTmpObj);
pTmpObj->release();
}
return pArray;
}
3.3 深拷贝和浅拷贝
Cocos2d-x采用的都是深拷贝的方式,它们的区别在于当前对象是否包含了对其他资源的引用;在拷贝机制上采用深拷贝的方式,大大方便了我们对内存的管理,避免因资源的释放导致引用异常。

二、继续内存管理机制

1.源码:
CCObject::CCObject(void)
:m_nLuaID(0)
,m_uReference(1) //引用计数,初始为1,当引用计数为0,自动释放该对象
,m_uAutoReleaseCount(0)//自动释放对象计数,如果是手动new的,则为0,如果autoRelease的,则在AutoreleasePool会+1
//这里是保护成员,所以CCAutoreleasePool被声明为友元类
{
static unsigned int uObjectCount = 0;//静态成员,对象计数,只增不减,用于标识唯一一个对象实例
m_uID = ++uObjectCount;
}
CCObject::~CCObject(void)
{
if(m_uAutoReleaseCount>0)//如果是自动管理,则在PoolManager中删除
{
CCPoolManager::sharedPoolManager()->removeObject(this);
}
if(m_nLuaID)
{
CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptObjectByCCOb ject(this);
}
else
{
CCScriptEngineProtocol* pEngine = CCScriptEngineManager::sharedManager()->getScriptEngine();
if(pEngine != NULL && pEngine->getScriptType() == kScriptTypeJavascript)
{
pEngine->removeScriptObjectByCCOb ject(this);
}
}
}
void CCObject::release(void)
{
CCAssert(m_uReference>0,”reference count should greater than 0”);
—m_uReference;
if(m_uReference == 0)
{
delete this;
}
}
void CCObject::retain(void)
{
CCAssert(m_uReference > 0,”reference count should greater than 0”);
++m_uReference;
}
CCObject* CCObject::autorelease(void)
{
CCPoolManager::sharedPoolManager()->addObject(this);
return this;
}
bool CCObject::isSingleReference(void) const
{
return m_uReference == 1;
}
unsigned int CCObject::retainCount(void) const
{
return m_uReference;
}
bool CCObject::isEqual(const CCObject* pObject)
{
return this == pObject;
}
void CCObject::acceptVisitor(CCDataVisitor &visitor)
{
visitor.visitObject(this);
}

2.new和release是好基友,在手动内存管理中使用;
3.retain和release也是好基友,在自动内存管理中使用;
4.addChild(background)是要对引用计数进行操作的;
原文链接:https://www.f2er.com/cocos2dx/342955.html

猜你在找的Cocos2d-x相关文章