1. 程式人生 > >cocos2dx 3.x記憶體管理原始碼追蹤

cocos2dx 3.x記憶體管理原始碼追蹤

cocos2dx的記憶體管理,我有空追蹤一下原始碼 理解一下。
我們都知道 cocos2dx是靠引用計數實現的,順便加入了物件池的管理。

涉及到一下幾個類,AutorealsePool,PoolManager,Ref,DisplayLinkDirector.
函式:
mainLoop,retain,release,autoRealse.

1.首先跳轉到Application::run()

,,,
int Application::run()
{
PVRFrameEnableControlWindow(false);

// Main message loop:
LARGE_INTEGER nLast;
LARGE_INTEGER nNow;

QueryPerformanceCounter(&nLast);
initGLContextAttrs();

// Initialize instance and cocos2d.
if (!applicationDidFinishLaunching())
{
    return 0;
}

auto director = Director::getInstance();
auto glview = director->getOpenGLView();

// Retain glview to avoid glview being released in the while loop
glview->retain();
//如果視窗未關閉  就是一個while死迴圈
while(!glview->windowShouldClose())
{
    QueryPerformanceCounter(&nNow);
    if (nNow.QuadPart - nLast.QuadPart > _animationInterval.QuadPart)
    {
        nLast.QuadPart = nNow.QuadPart - (nNow.QuadPart % _animationInterval.QuadPart);

        director->mainLoop();
        glview->pollEvents();
    }
    else
    {
        Sleep(1);
    }
}

// Director should still do a cleanup if the window was closed manually.
if (glview->isOpenGLReady())
{
    director->end();
    director->mainLoop();
    director = nullptr;
}
glview->release();
return true;

}
,,,

2.跳轉到mainLoop函式中

void DisplayLinkDirector::mainLoop()
{
    if (_purgeDirectorInNextLoop)
    {
        _purgeDirectorInNextLoop = false;
        purgeDirector();
    }
    else if (_restartDirectorInNextLoop)
    {
        _restartDirectorInNextLoop = false;
        restartDirector();
    }
    else
if (! _invalid) { drawScene(); // release the objects auto count = PoolManager::getInstance()->getPoolCount();//這個函式我自己加的,方便列印 CCLOG("$$$$$$$$$$=========== %d",count); CCLOG("&&&&&&&&&&=========== %s",PoolManager::getInstance()->getCurrentPool()->getName())
;//這個函式我自己加的,方便列印 auto pool = PoolManager::getInstance()->
getCurrentPool(); CCLOG("前面pool count is %d",pool->getCount()); PoolManager::getInstance()->getCurrentPool()->clear(); CCLOG("後面pool count is %d",pool->getCount()); } }

其他的先不管 ,就看PoolManager::getInstance()->getCurrentPool()->clear();這行程式碼。

PoolManager這個類,從字面上的意思它是個管理類,所以它被寫成單例模式。單例的程式碼:

PoolManager* PoolManager::getInstance()
{
    if (s_singleInstance == nullptr)
    {
        s_singleInstance = new (std::nothrow) PoolManager();
        // Add the first auto release pool
        new AutoreleasePool("cocos2d autorelease pool");
    }
    return s_singleInstance;
}

以上程式碼是個典型的單例模式寫法,但是有行程式碼
new AutoreleasePool(“cocos2d autorelease pool”);我從沒看過生成一個物件 卻不用其他的引用或者指標指向它,寫的好奇怪。

3.檢視AutoreleasePool這個類

檢視他的建構函式:

AutoreleasePool::AutoreleasePool(const std::string &name)
: _name(name)
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
, _isClearing(false)
#endif
{
    _managedObjectArray.reserve(150);
    PoolManager::getInstance()->push(this);
}

原來AutoreleasePool類生成物件的時候,在建構函式中呼叫
PoolManager::getInstance()->push(this)。

void PoolManager::push(AutoreleasePool *pool)
{
    _releasePoolStack.push_back(pool);
}

看懂了吧,原來push函式原來在這裡呼叫了,但是這種寫法很奇怪,可能是我c++功力太淺了,要是我直接在單例getInstance函式中push了。

PoolManager類成員變數:
std::vector 《AutoreleasePool*》 _releasePoolStack
其實這個_releasePoolStack斷點的時候,只有在生成單例模式的push了一個AutoreleasePool物件,_releasePoolStack的size() = 1。
所以在mainLoop中:

auto count = PoolManager::getInstance()->getPoolCount();
CCLOG("$$$$$$$$$$===========  %d",count);

定義如下
int PoolManager::getPoolCount()
{
    return _releasePoolStack.size();
}

列印始終都是size等於1

AutoreleasePool* PoolManager::getCurrentPool() const
{
    return _releasePoolStack.back();
}

這個函式返回的是_releasePoolStack的末尾引用
而_releasePoolStack的資料size其實只有一條,既然是一條,那幹嘛用vector呢?這點沒弄明白 難道是因為喜歡用vector存貯資料?

接下來看AutoreleasePool::clear()函式

void AutoreleasePool::clear()
{
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
    _isClearing = true;
#endif
    std::vector<Ref*> releasings;
    releasings.swap(_managedObjectArray);
    for (const auto &obj : releasings)
    {
        obj->release();
    }
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
    _isClearing = false;
#endif
}

_managedObjectArray資料被清空,這個函式中有個重要的知識點 那就是vector的swap的用法,swap可以清空vector申請的記憶體,而clear卻不一定。詳情可參照:

追蹤release程式碼:

void Ref::release()
{
    CCASSERT(_referenceCount > 0, "reference count should be greater than 0");
    --_referenceCount;

    if (_referenceCount == 0)
    {
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
        auto poolManager = PoolManager::getInstance();
        if (!poolManager->getCurrentPool()->isClearing() && poolManager->isObjectInPools(this))
        {
        CCASSERT(false, "The reference shouldn't be 0 because it is still in autorelease pool.");
        }
#endif

#if CC_REF_LEAK_DETECTION
        untrackRef(this);
#endif
        delete this;
    }
}

release函式 就是將計數自減一,將0的Ref析構掉。

每個集成了Ref的物件 都有屬性_referenceCount,那它在哪裡自增呢?

舉個例子,去看看Sprite的create函式

Sprite* Sprite::create(const std::string& filename)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && sprite->initWithFile(filename))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

autorelease函式的定義

Ref* Ref::autorelease()
{
    PoolManager::getInstance()->getCurrentPool()->addObject(this);
    return this;
}

再追蹤addObject函式

void AutoreleasePool::addObject(Ref* object)
{
    _managedObjectArray.push_back(object);
}

奇怪 不是說好 一個精靈建立的時候 引用計數就加1嗎?但是我們找了半天沒發現,原來是Ref構造的時候就預設設定成1了,如下程式碼:

Ref::Ref()
: _referenceCount(1) // when the Ref is created, the reference count of it is 1
{
#if CC_ENABLE_SCRIPT_BINDING
    static unsigned int uObjectCount = 0;
    _luaID = 0;
    _ID = ++uObjectCount;
    _scriptObject = nullptr;
#endif

#if CC_REF_LEAK_DETECTION
    trackRef(this);
#endif
}

我們知道 cocos2dx 中node sprite都是繼承Ref,C++中物件生成的時候,先呼叫父類的建構函式 ,再呼叫自己的建構函式。

4.引用計數 自增和自減 在哪些地方出現?

  1. addChild()函式
    Node下面好幾個addChild函式,都是函式過載,最終都用到這個函式:
    addChildHelper()
void Node::addChildHelper(Node* child, int localZOrder, int tag, const std::string &name, bool setTag)
{
    if (_children.empty())
    {
        this->childrenAlloc();
    }

    this->insertChild(child, localZOrder);

    if (setTag)
        child->setTag(tag);
    else
        child->setName(name);

    child->setParent(this);
    child->setOrderOfArrival(s_globalOrderOfArrival++);

#if CC_USE_PHYSICS
    // Recursive add children with which have physics body.
    auto scene = this->getScene();
    if (scene && scene->getPhysicsWorld())
    {
        scene->addChildToPhysicsWorld(child);
    }
#endif

    if( _running )
    {
        child->onEnter();
        // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
        if (_isTransitionFinished)
        {
            child->onEnterTransitionDidFinish();
        }
    }

    if (_cascadeColorEnabled)
    {
        updateCascadeColor();
    }

    if (_cascadeOpacityEnabled)
    {
        updateCascadeOpacity();
    }
}

找到insertChild函式:

void Node::insertChild(Node* child, int z)
{
    _transformUpdated = true;
    _reorderChildDirty = true;
    _children.pushBack(child);
    child->_localZOrder = z;
}

接著找到pushBack函式,開始以為就是vector中的函式呢,其實不然:

    void pushBack(T object)
    {
        CCASSERT(object != nullptr, "The object should not be nullptr");
        _data.push_back( object );
        object->retain();
    }

終於找到retain函數了啊!

  1. setParent函式:
void Node::setParent(Node * parent)
{
    _parent = parent;
    _transformUpdated = _transformDirty = _inverseDirty = true;
}

發現這個函式根本沒有使引用計數增加,而我在專案中使用setParent的時候 根本一個節點沒有顯示出來,所以這個函式只是一個指向關係,並未將孩子真正加入到父節點中,所以我基本不使用它,我都是使用addChild函式。

所以當你生成一個Sprite並把它加入到layer之後,他的引用計數是2。

  1. removeFromParent函式:
void Node::removeFromParent()
{
    this->removeFromParentAndCleanup(true);
}

void Node::removeFromParentAndCleanup(bool cleanup)
{
    if (_parent != nullptr)
    {
        _parent->removeChild(this,cleanup);
    } 
}

我們可以看到這兩個函式幾乎等同,接著removeChild:

void Node::removeChild(Node* child, bool cleanup /* = true */)
{
    // explicit nil handling
    if (_children.empty())
    {
        return;
    }

    ssize_t index = _children.getIndex(child);
    if( index != CC_INVALID_INDEX )
        this->detachChild( child, index, cleanup );
}

接著detachChild:

void Node::detachChild(Node *child, ssize_t childIndex, bool doCleanup)
{
    // IMPORTANT:
    //  -1st do onExit
    //  -2nd cleanup
    if (_running)
    {
        child->onExitTransitionDidStart();
        child->onExit();
    }

#if CC_USE_PHYSICS
    child->removeFromPhysicsWorld();
#endif

    // If you don't do cleanup, the child's actions will not get removed and the
    // its scheduledSelectors_ dict will not get released!
    if (doCleanup)
    {
        child->cleanup();
    }

    // set parent nil at the end
    child->setParent(nullptr);

    _children.erase(childIndex);
}

接著cleanup函式:

void Node::cleanup()
{
    // actions
    this->stopAllActions();
    this->unscheduleAllCallbacks();

#if CC_ENABLE_SCRIPT_BINDING
    if ( _scriptType != kScriptTypeNone)
    {
        int action = kNodeOnCleanup;
        BasicScriptData data(this,(void*)&action);
        ScriptEvent scriptEvent(kNodeEvent,(void*)&data);
        ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
    }
#endif // #if CC_ENABLE_SCRIPT_BINDING

    // timers
    for( const auto &child: _children)
        child->cleanup();
}

可以看到 遞迴呼叫了cleanup函式 子節點都是處理一些事情,detachChild函式最後將子節點的父節點設定為空,最後看erase函式:

    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);
    }

終於找到了release函數了。

有時候我容易將 std::vector和cocos2dx封裝的Vector搞混淆,真是眼睛不好啊!現在記憶體管理的基本思路搞清楚了。