1.why
because some class liked "cs::CSJsonDictionary" is not derive from CCObject,so when i new it,need manual release it later.
2. todo
implement one plan.that can auto release those class who are not derive from CCObject.
3. code
Single ton and Memory pool class
template<class _Ty>
class pkSingleTon{
public:
pkSingleTon(){}
public:
static _Ty* Instance(){
static _Ty s_val;
return &s_val;
}
};
#include <string>
#include <set>
#include <map>
#include <list>
#include <vector>
template<class _Ty>
class pkObserver : public std::set<_Ty>{
};
template<class _Ty>
class pkMemoryPool : private pkSingleTon<pkMemoryPool<_Ty> >{
private:
typedef pkObserver<_Ty*> CON;
CON mdatas;
private:
void _add(_Ty* v){
mdatas.insert(v);
}
void _remove(_Ty* v){
typename CON::iterator b = mdatas.find(v);
if(b == mdatas.end())
return;
delete (*b);
mdatas.erase(b);
}
public:
static _Ty* create(){
_Ty* ret = new _Ty();
add(ret);
return ret;
}
static void add(_Ty* v){
pkMemoryPool<_Ty>::Instance()->_add(v);
}
static void remove(_Ty* v){
pkMemoryPool<_Ty>::Instance()->_remove(v);
}
};
Auto memory pool code:
#include "cocos2d.h"
template<class _Ty>
class pkAutoMemoryPool{
private:
class pkObjectMemoryPool_Helper : public cocos2d::CCObject{
private:
_Ty* m_value;
public:
static void create(_Ty* v){
pkObjectMemoryPool_Helper* ret = new pkObjectMemoryPool_Helper();
ret->m_value = v;
ret->autorelease();
}
virtual ~pkObjectMemoryPool_Helper(){
pkAutoMemoryPool<_Ty>::remove(m_value);
}
};
public:
static _Ty* create(){
_Ty* ret = pkMemoryPool<_Ty>::create();
pkObjectMemoryPool_Helper::create(ret);
return ret;
}
static void remove(_Ty* v){
pkMemoryPool<_Ty>::remove(v);
}
};
4 used
cs::CSJsonDictionary* ret = pkAutoMemoryPool<cs::CSJsonDictionary>::create();