标签:
代码结构 函数名 参照了cocos2dx风格
pool.h
#include <iostream>
#include"stack"
#include "vector"
using namespace std;
class MangerPool;
class autoreleasePool;
class Ref
{
private:
unsigned int _RefCount;
public:
Ref() :_RefCount(1){}
virtual ~Ref(){}
void retain();
void release();
void autorelease();
};
class MangerPool
{
public:
static MangerPool* getInstance();
void push(autoreleasePool*s);
stack<autoreleasePool*> data;
autoreleasePool*getCurrentPool()
{
return data.top();
}
};
class autoreleasePool
{
public:
autoreleasePool();
vector<Ref*> data;
void clear()
{
while (!data.empty())
{
Ref*ref = data.back();
ref->release();
data.pop_back();
}
}
void addObject(Ref*add)
{
data.push_back(add);
}
};
class TTF :public Ref
{
public:
long long testData[1000];
string name;
TTF(string name)
{
this->name = name;
cout << name.c_str()<<" create"<<endl;
}
~TTF()
{
cout << name.c_str() << " release"<<endl;
}
public:
static TTF*create(string name)
{
return new TTF(name);
}
};
pool.cpp
#include "pool.h"
#include "windows.h"
#include "stdlib.h"
MangerPool* MangerPool::getInstance()
{
static MangerPool*ref = NULL;
if (ref == NULL)
{
ref = new MangerPool;
new autoreleasePool;
}
return ref;
}
void MangerPool::push(autoreleasePool*s)
{
data.push(s);
}
autoreleasePool::autoreleasePool()
{
MangerPool::getInstance()->push(this);
}
void Ref::retain()
{
++_RefCount;
}
void Ref::release()
{
--_RefCount;
if (_RefCount == 0)
{
delete this;
}
}
void Ref::autorelease()
{
MangerPool::getInstance()->getCurrentPool()->addObject(this);
}
int main(int argc, char *argv[])
{
char str[100];
int i = 2;
while (i)
{
--i;
for (int x = 0; x < 1000; x++)
{
sprintf(str, "count is %d", x);
auto tmp = TTF::create(str);
tmp->autorelease();
}
cout << "after 3s all TTF‘s objects will be released " << endl;
Sleep(3000);
MangerPool::getInstance()->getCurrentPool()->clear();
Sleep(3000);
}
Sleep(1000);
system("pause");
return 0;
}
标签:
原文地址:http://my.oschina.net/kkkkkkkkkkkkk/blog/469902