码迷,mamicode.com
首页 > 其他好文 > 详细

cocos3 内存管理机制

时间:2014-12-02 13:25:51      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   on   div   

内存管理,防止内存泄露

如果a类引用某个那么内存块加1,如果a类不在引用了,内存块减一,当计数为0的时候,清空这个内存块。

 

retain()函数

void Ref::retain()
{
    CCASSERT(_referenceCount > 0, "reference count should greater than 0");
    ++_referenceCount;
}

 

release()函数

void Ref::release()
{
    CCASSERT(_referenceCount > 0, "reference count should 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))
        {
            // Trigger an assert if the reference count is 0 but the Ref is still in autorelease pool.
            // This happens when ‘autorelease/release‘ were not used in pairs with ‘new/retain‘.
            //
            // Wrong usage (1):
            //
            // auto obj = Node::create();   // Ref = 1, but it‘s an autorelease Ref which means it was in the autorelease pool.
            // obj->autorelease();   // Wrong: If you wish to invoke autorelease several times, you should retain `obj` first.
            //
            // Wrong usage (2):
            //
            // auto obj = Node::create();
            // obj->release();   // Wrong: obj is an autorelease Ref, it will be released when clearing current pool.
            //
            // Correct usage (1):
            //
            // auto obj = Node::create();
            //                     |-   new Node();     // `new` is the pair of the `autorelease` of next line
            //                     |-   autorelease();  // The pair of `new Node`.
            //
            // obj->retain();
            // obj->autorelease();  // This `autorelease` is the pair of `retain` of previous line.
            //
            // Correct usage (2):
            //
            // auto obj = Node::create();
            // obj->retain();
            // obj->release();   // This `release` is the pair of `retain` of previous line.
            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;
    }
}

 

autorelease()相当于 自动的retain()和release()。采用了池的计数

object的定义

就是ref

 

还可以通过右键点击某个函数,计算层次结构和调用。

 

cocos3 内存管理机制

标签:style   blog   io   ar   color   os   sp   on   div   

原文地址:http://www.cnblogs.com/yufenghou/p/4137155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!