内存池自动释放
pool.h #include <iostream> #include"stack" #include "vector" using namespace std; class autoreleasePool; class Ref { protected: unsigned int _RefCount; public: Ref() :_RefCount(1){} virtual ~Ref()/*必须virtual 不然子类部分不能析构 导致内存泄露*/ { cout<<"~ref"<<endl; } 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<Ref*> data; void clear() { for (int i = 0;i<data.size();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 << 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" 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 < times; x++) { sprintf(str, "count is %d", x); auto tmp = TTF::create(str); tmp->autorelease(); } cout << "after 100ms all TTF's objects will be released " << endl; 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 ~~~