【纯代码解析 C++内存池的简单原理及实现】使用示例:
#include <IOStream>#include <thread>using namespace std;class Apple {public:Apple() {id_ = 0;cout << "Apple()" << endl;}Apple(int id) {id_ = id;cout << "Apple(" << id_ << ")" << endl;}~Apple() {cout << "~Apple()" << endl;}void SetId(int id) {id_ = id;}int GetId() {return id_;}private:int id_;};void ThreadProc(ppx::base::MemoryPool<char> *mp) {int i = 0;while (i++ < 100000) {char* p0 = (char*)mp->allocate();char* p1 = (char*)mp->allocate();mp->deallocate(p0);char* p2 = (char*)mp->allocate();mp->deallocate(p1);mp->deallocate(p2);}}int main(){ppx::base::MemoryPool<char> mp;int i = 0;while (i++ < 100000) {char* p0 = (char*)mp.allocate();char* p1 = (char*)mp.allocate();mp.deallocate(p0);char* p2 = (char*)mp.allocate();mp.deallocate(p1);mp.deallocate(p2);}std::thread th0(ThreadProc, &mp);std::thread th1(ThreadProc, &mp);std::thread th2(ThreadProc, &mp);th0.join();th1.join();th2.join();Apple *apple = nullptr;{ppx::base::MemoryPool<Apple> mp2;apple = mp2.newElement(10);int a = apple->GetId();apple->SetId(10);a = apple->GetId();mp2.deleteElement(apple);}apple->SetId(12);int b = -4 % 4;int *a = nullptr;{ppx::base::MemoryPool<int, 18> mp3;a =mp3.allocate();*a = 100;//mp3.deallocate(a);int *b =mp3.allocate();*b = 200;//mp3.deallocate(b);mp3.deallocate(a);mp3.deallocate(b);int *c = mp3.allocate();*c = 300;}getchar();return 0;}
推荐阅读
- 纯发面饼子的做法
- 马鞭草酮迷迭香作用,马鞭草酮迷迭香纯露
- 洋甘菊冰晶可以长期用吗,洋甘菊纯露不能长期敷吗
- FAT32文件系统解析
- 除湿气为什么会瘦20斤,马思纯个星期瘦10斤你想瘦多少
- 程序员年龄大了不想敲代码?看看国外同行能敲到多少岁
- 纯欲天花板是什么意思?
- C# 生成和解析二维码
- 洋甘菊纯露的功效,董欣洋甘菊纯露的功效以及作用怎么使用
- ts8280打印机故障代码,佳能ts8280如何清零-