垃圾回收(GC)
垃圾回收器将之前使用過的,但是現在不在使用(或者沒有指針再指向)的記憶體空間稱為“垃圾”,将這些“垃圾”收集起來以便再次利用的機制即稱為“垃圾回收”。
Cocos2dx的GC機制
Cocos2dx使用基于引用計數的方式實作“垃圾回收”機制。簡單了解為系統為每個對象記錄了一個值,這個值用來表示對應的對象被引用的次數,當對象被引用的次數為0時,該對象被視為垃圾而被系統回收。
引用計數
Cocos2dx中的幾乎所有對象都繼承自Ref基類。Ref類的主要職責就是進行引用計數管理。下面是Ref類的頭檔案中的内容。
//CCRef.h
class CC_DLL Ref
{
public:
void retain();//調用一次引用計數+1
void release();//調用一次引用計數-1,在此方法中會判斷引用計數值_referenceCount是否等于0,如果等于0,則将該對象delete
Ref* autorelease();//加入自動釋放池
unsigned int getReferenceCount() const;//擷取對象引用計數值
protected:
Ref();//構造函數,在此處引用計數值_referenceCount被初始化為1
public:
virtual ~Ref();
protected:
unsigned int _referenceCount;//引用計數值
friend class AutoreleasePool;
retain()和release()方法雖然能讓我們手動的對引用計數進行管理,但也可能會産生意想不到的結果,比如說如果在需要調用release()方法的地方我們忘記調用,則會導緻記憶體洩漏。AutoreleasePool(自動釋放池)很好的解決了這個問題。Ref基類中的autorelease()方法就是用來将對象加入到一個AutoreleasePool中。
autorelease()
//CCRef.cpp
Ref* Ref::autorelease()
{
PoolManager::getInstance()->getCurrentPool()->addObject(this);
return this;
}
autorelease()方法将對象加入到一個AutoreleasePool中。在每一幀結束的時候,這個AutoreleasePool中的對象會被清理(在這個AutoreleasePool中的每個對象都會被調用一次release()方法,如果對象引用計數值為0,那麼該對象被delete)。
//CCDirector.cpp
void Director::mainLoop()
{
if (_purgeDirectorInNextLoop)
{
_purgeDirectorInNextLoop = false;
purgeDirector();
}
else if (_restartDirectorInNextLoop)
{
_restartDirectorInNextLoop = false;
restartDirector();
}
else if (! _invalid)
{
drawScene();
PoolManager::getInstance()->getCurrentPool()->clear();//調用自動釋放池對象的clear()方法
}
}
//CCAutoreleasePool.cpp
void AutoreleasePool::clear()
{
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
_isClearing = true;
#endif
std::vector<Ref*> releasings;
releasings.swap(_managedObjectArray);
//swap交換技巧實作記憶體釋放思想:
//1.vector()使用vector的預設構造函數建立臨時vector對象
//2.在該臨時對象上調用swap成員,swap調用之後對象_managedObjectArray占用的空間就等于一個預設構造的對象的大小,臨時對象就具有原來對象_managedObjectArray的大小,而該臨時對象随即就會被析構,進而其占用的空間也被釋放。
for (const auto &obj : releasings)
{
obj->release();//引用計數-1
}
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
_isClearing = false;
#endif
}
UI元素的自動釋放
常用的Layer、Sprite等均繼承自Node類。以Node類為例看一下Node對象nodeObj的引用計數值的變化過程。
首先,在nodeObj被create的時候,引用計數值被初始化為1,并加入到自動釋放池。
//CCNode.cpp
Node * Node::create()
{
Node * ret = new (std::nothrow) Node();//此時引用計數為1
if (ret && ret->init())
{
ret->autorelease();//加入到自動釋放池
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
通過addChild方法将nodeObj添加到父節點上(addChild最終都是調用addChildHelper方法),nodeObj對象被pushBack進一個vector中,pushBack方法中調用了ration()方法,nodeObj對象引用計數值為2。
//CCNode.cpp
void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string &name, bool setTag)
{
auto assertNotSelfChild
( [ this, child ]() -> bool
{
for ( Node* parent( getParent() ); parent != nullptr;
parent = parent->getParent() )
if ( parent == child )
return false;
return true;
} );
(void)assertNotSelfChild;
CCASSERT( assertNotSelfChild(),
"A node cannot be the child of his own children" );
if (_children.empty())
{
this->childrenAlloc();
}
this->insertChild(child, localZOrder);
if (setTag)
child->setTag(tag);
else
child->setName(name);
child->setParent(this);
child->updateOrderOfArrival();
if( _running )
{
child->onEnter();
if (_isTransitionFinished)
{
child->onEnterTransitionDidFinish();
}
}
if (_cascadeColorEnabled)
{
updateCascadeColor();
}
if (_cascadeOpacityEnabled)
{
updateCascadeOpacity();
}
}
//CCNode.cpp
void Node::insertChild(Node* child, int z)
{
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->retainScriptObject(this, child);
}
#endif
_transformUpdated = true;
_reorderChildDirty = true;
_children.pushBack(child);//在此處child對象的引用計數被+1,此時child引用計數為2
child->_setLocalZOrder(z);
}
//CCVector.h
void pushBack(T object)
{
CCASSERT(object != nullptr, "The object should not be nullptr");
_data.push_back( object );
object->retain();//引用計數+1
}
通過之前autorelease()的介紹可以知道,在目前幀結束的時候,自動釋放池中的對象會調用一次release(),此時nodeObj的引用計數值為1。
最後,當nodeObj被remove的時候(最終調用detachChild方法),會再次調用nodeObj的release()方法,此時,引用計數值變為0,nodeObj被delete。
//CCNode.cpp
void Node::detachChild(Node *child, ssize_t childIndex, bool doCleanup)
{
if (_running)
{
child->onExitTransitionDidStart();
child->onExit();
}
if (doCleanup)
{
child->cleanup();
}
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->releaseScriptObject(this, child);
}
#endif
child->setParent(nullptr);
_children.erase(childIndex);//此處會調用一次release()方法,引用計數值變為0
}
//CCVector.h
iterator erase(ssize_t index)
{
CCASSERT(!_data.empty() && index >=0 && index < size(), "Invalid index!");
auto it = std::next( begin(), index );
(*it)->release();
return _data.erase(it);
}