Ref也就是以前的CCObject,是所有cocos2dx节点的终极父类,由它来进行内存的管理
它主要有以下函数retain()、release()、autorelease()、及引用计数变量_referenceCount和友元类内存池AutoreleasePool
在2dx中,内存管理就是靠引用计数_referenceCount来管理
void Ref::retain() { CCASSERT(_referenceCount > 0,"reference count should greater than 0"); ++_referenceCount; } 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)) { 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; } }可以看出,retain()时_referenceCount加1、release()时减1,当计数为0时,释放自己!
Ref* Ref::autorelease() { PoolManager::getInstance()->getCurrentPool()->addObject(this); return this; }autorelease()则是把自身放入内存池中,有内存池来处理,跟进去看看
void AutoreleasePool::addObject(Ref* object) { _managedObjectArray.push_back(object); }把对象放入容器中。那什么时候处理掉这个容器呢!
我们都知道,2dx它在工作时运行着一个大循环,这个循环中处理着图片的绘制,定时器,按钮点击事件等等,也在这个循环中,对无用内存进行释放!
在mian.cpp中开始
Application::getInstance()->run()
...... 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); } } .....mainLoop()函数
void DisplayLinkDirector::mainLoop() { if (_purgeDirectorInNextLoop) { _purgeDirectorInNextLoop = false; purgeDirector(); } else if (! _invalid) { drawScene(); // 就是在这处理的 PoolManager::getInstance()->getCurrentPool()->clear(); } }在跟clear()函数
void AutoreleasePool::clear() { #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) _isClearing = true; #endif for (const auto &obj : _managedObjectArray) { obj->release(); } _managedObjectArray.clear(); #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) _isClearing = false; #endif }其中的obj->release();也就是上面Ref的release()函数,当引用计数为0时释放,也就是2dx的内存管理机制!!! 原文链接:https://www.f2er.com/cocos2dx/345215.html