class CC_DLL AutoreleasePool
{
public:
/**
* 提示:自动释放池对象要创建在栈里面 不能再堆里面
* 创建的时候就自动push进PoolManager里面
*/
AutoreleasePool();
{
_managedObjectArray.reserve(150);//vector扩大容量
PoolManager::getInstance()->push( this);
}
/**
* 用引用来创建 是为了调试
*/
AutoreleasePool( const std::string &name);
{
_managedObjectArray.reserve(150);
PoolManager::getInstance()->push( this);
}
// 枚举每一个加进对象池的obj去调用release 并且清空
~AutoreleasePool();
{
CCLOGINFO( "deallocing
AutoreleasePool: %p" , this);
clear();//
PoolManager::getInstance()->pop();
}
/**
* 添加对象到对象池中
* 对象池销毁的时候会调用
*/
void addObject( Ref *object);
{
_managedObjectArray.push_back( object);
}
/**
清理对象池 析构函数调用
*/
void clear();
{
#if defined (COCOS2D_DEBUG)
&& ( COCOS2D_DEBUG > 0)
_isClearing = true;
#endif
for (const auto &obj
: _managedObjectArray)
{
//枚举每一个加进对象池的obj去调用release
obj->release();
}
//把vector清空
_managedObjectArray.clear();
#if defined (COCOS2D_DEBUG)
&& ( COCOS2D_DEBUG > 0)
_isClearing = false;
#endif
}
#if defined (COCOS2D_DEBUG)
&& ( COCOS2D_DEBUG > 0)
/**
* Whether the pool is doing `clear` operation.
*/
bool isClearing() const { return _isClearing;
};
#endif
/**
* 检查是否包含
* 枚举一遍这个vector
*/
bool contains( Ref*
object) const ;
{
for (const auto&
obj : _managedObjectArray)
{
if (obj
== object )
return true ;
}
return false;
}
/**
* 用来调试
*
*/
void dump();
{
CCLOG("autorelease
pool: %s, number of managed object %d\n", _name.c_str(), static_cast<int >(_managedObjectArray.size()));
CCLOG("%20s%20s%20s", "Object
pointer", "Object id" , "reference
count");
for (const auto &obj
: _managedObjectArray)
{
CC_UNUSED_PARAM(obj);
CCLOG("%20p%20u\n" ,
obj, obj->getReferenceCount());
}
}
private:
/**
* The underlying array of object managed by the pool.
*
* Although Array retains the object once when an object is added, proper
* Ref::release() is called outside the array to make sure that the pool
* does not affect the managed object‘s reference count. So an object can
* be destructed properly by calling Ref::release() even if the object
* is in the pool.
*/
std::vector< Ref*>
_managedObjectArray;
std::string _name;
#if defined (COCOS2D_DEBUG)
&& ( COCOS2D_DEBUG > 0)
/**
* The flag for checking whether the pool is doing `clear` operation.
*/
bool _isClearing;
#endif
};