Cocos2dx Memory Management Analysis

Source: Internet
Author: User

Cocos2dx Memory Management Analysis

I started to write a blog on the first day today. I think I will stick to it and share and communicate with everyone. This is also due to my passion for technology and the passion for games, I think I will devote my whole life to games. He is my career and a friend of my life. I will not talk much about this nonsense, for the first blog, let's talk about cocos2dx memory management. First, let's take a look at the following code snippet class Ref {public: void retain (); void release (); Ref * autorelease (); protected: unsigned int _ referenceCount ;}; the Node of all display objects in cocos2dx also inherits Ref from the public (CCObiect under cocos2dx3.0 ), therefore, all the display objects also have these three methods, while looking at the implementation void Ref: retain () {CCASSERT (_ referenceCount> 0, "reference count shocould greater than 0"); ++ _ referenceCount;} void Ref: release () {CCASSERT (_ referenceCount> 0, "reference count sh Ocould 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 autoreleasepool. ");} delete this;} Ref * Ref: autorelease () {PoolManager: getInstance ()-> getCurrentPool ()-> addObject (this); return this ;}

People who understand object-c should be able to understand the memory management of the cocos2dx-c through the above Code is actually the same as the object-c, the Reference Counter method is used to manage the memory of the user. when an object is created, the reference counter _ referenceCount will add one. Don't ask me why, because _ referenceCount is initialized in the constructor 1, see the following code to create a display object.

Layer *Layer::create(){    Layer *ret = new (std::nothrow) Layer();    if (ret && ret->init())    {        ret->autorelease();        return ret;    }    else    {        CC_SAFE_DELETE(ret);        return nullptr;    }}

This is the code for creating a Layer. The memory of the new Layer object is fast. init initializes the logic functions or variables in this class, and then autorelease returns the result. Why autorelease, let's look at the implementation of the autorelease function.

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

It turns out that this object, that is, the memory, is quickly added to a global PoolManager. Why do we need to add it to the PoolManager? Let's take a look at the PoolManager.

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

Is to get an AutoreleasePool object in the PoolManager and add the Display object to the set object in the AutoreleasePool object (here I do not quite understand the author's intention, the single-profit object has only one instance, whether it is a Mao _ releasePoolStack or a set, each time it takes the last AutoreleasePool of the set, and the framework adds an AutoreleasePool object only to the _ releasePoolStack set by the handler ); so long as the autorelease function goes through, it will be added to the PoolManager. Why? Of course, it must be to better manage the memory and where to manage it, we know that cocos2d has only one main thread. Where can we find it?

void DisplayLinkDirector::mainLoop(){    if (_purgeDirectorInNextLoop)    {        _purgeDirectorInNextLoop = false;        purgeDirector();    }    else if (! _invalid)    {        drawScene();        // release the objects        PoolManager::getInstance()->getCurrentPool()->clear();    }}

We can see the phrase "PoolManager: getInstance ()-> getCurrentPool ()-> clear ();". The other sections will explain their willingness in the future, in this chapter, we only look at the memory management module of the framework. We will continue to look at the clear method in PoolManager.

void AutoreleasePool::clear(){    for (const auto &obj : _managedObjectArray)    {        obj->release();    }    _managedObjectArray.clear();}

He will call all the release methods added to the AutoreleasePool object. It seems that release is very important. We will continue to study the release method.

    if (_referenceCount == 0)    {        auto poolManager = PoolManager::getInstance();        if (!poolManager->getCurrentPool()->isClearing() && poolManager->isObjectInPools(this))        {            delete this;        }    }

This should be clear at a glance. When the reference counter of the displayed object is 0, it will automatically delete itself, in this way, we can skillfully manage the objects created or new, and when the reference counter will add 1 and when will it be reduced by 1, we will continue to conduct in-depth research.

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

When an object is added to another object, the addChild method is called. addChild must call the insertChild method, and the _ children. pushBack (child) sentence in the insertChild Method

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

He will call the retain method, and retain will add the reference counter to 1 now _ referenceCount = 2. When the Display object is removed, he must call removeChild, and he will also call release () function. At this time, _ referenceCount will change-_ referenceCount to 1. When the program executes the next frame, it will continue-_ referenceCount; then this object will be deleted when _ referenceCount = 0
In this way, the entire process from object generation to destruction is formed. Therefore, we must pay attention to it when using it. After manual retain is used, you must manually call release (); otherwise, the memory will never be deleted, resulting in Memory leakage.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.