内存池算法 linux,内存池自动释放 - 梦想游戏 - OSCHINA - 中文开源技术交流社区...

pool.h

#include 

#include"stack"

#include "vector"

using namespace std;

class autoreleasePool;

class Ref

{

protected:

unsigned int _RefCount;

public:

Ref() :_RefCount(1){}

virtual ~Ref()/*必须virtual 不然子类部分不能析构 导致内存泄露*/

{

cout<

}

void retain();

void release();

void autorelease();

};

class autoreleasePool

{

public:

static autoreleasePool*_autoreleasePool;

autoreleasePool(){}

~autoreleasePool(){ data.clear(); }

static autoreleasePool*getInstance()

{

if(_autoreleasePool==nullptr)

_autoreleasePool = new autoreleasePool;

return _autoreleasePool;

}

static  void destoryInstance()

{

if (_autoreleasePool != nullptr)

{

delete _autoreleasePool;

_autoreleasePool=nullptr;

}

}

vector data;

void clear()

{

for (int i = 0;i

{

data[i]->release();

}

data.clear();

data.reserve(10);

}

void addObject(Ref*add)

{

data.push_back(add);

}

};

autoreleasePool* autoreleasePool::_autoreleasePool = nullptr;

class TTF :public Ref

{

public:

long long testData[1000];

string name;

TTF(string name)

{

this->name = name;

cout <

}

~TTF()

{

cout <

}

public:

static TTF*create(string name)

{

return new TTF(name);

}

};

pool.cpp

#include "pool.h"

#include "windows.h"

#include "stdlib.h"

void Ref::retain()

{

++_RefCount;

}

void Ref::release()

{

--_RefCount;

if (_RefCount == 0)

{

delete this;

}

}

void Ref::autorelease()

{

autoreleasePool::getInstance()->addObject(this);

}

void run(int times)

{

char str[100];

int i = 2;

while (i)

{

--i;

for (int x = 0; x 

{

sprintf(str, "count is %d", x);

auto tmp = TTF::create(str);

tmp->autorelease();

}

cout <

Sleep(100);

autoreleasePool::getInstance()->clear();

Sleep(100);

}

}

int main(int argc, char *argv[])

{

run(5000);

system("pause");

return 0;

}

但是测试代码的时候发现,程序刚启动时,占用内存0.4m ,峰值 78.6m    跑完还占用3.6m 内存

问题来了,为什么还会占用3.6m内存,用内存泄露检测工具并没发现内存泄露

神奇的事情发生了,用内存清理工具一清理,马上恢复正常了

测试2,不加入自动释放(延后释放) ,而是马上释放,那就“正常”

很明显,猜测一: 当进程大量new内存时  程序delete时 操作系统并不会马上完全收回,

会预留一点 给程序,加速程序下次new时的执行速度,比较内存操作比较费时(相对)

和操作系统老师 讨论一下,他也估计是这个原因,比较windows不开源,只有猜测了

over ~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值