我厂内存次神马的通常都本身实现。我曾经也本身写过一个demo(mempool)。后来发现boost库里面有一个内存池库boost pool,貌似很好用,使用挺好,例子能够贴出来。 ios
boost一共有4种内存池,为pool, object_pool, singleton_pool, pool_alloc。其中前三种应该应用都不少,我这里仅仅只有前2个demo. git
pool是最简单的内存池类,能够返回一个无符号的内存指针。由于我平时C用的远比C++多,因此这个类其实更适合我使用。 github
它的原理我没有细看。理论上也是每次分配一大块内存,这个内存卡会被分红小块,经过链表进行相连。链表至少记录当前能够分配的内存以及已经分配过正在使用的内存。每次分配都从能够分配链表分配便可。 shell
他只要有2个函数能够供你们使用:malloc和free。听说free不用程序猿本身搞,pool类能够自行回收。anyway,本身显示调用free确定没问题。 vim
下面是调用例子 数组
typedef struct _my_pool_test_t { int a; int b[]; } my_pool_test_t; void test_pool() { pool<> pl( sizeof(my_pool_test_t) + 5* sizeof(int) ); my_pool_test_t* test = (my_pool_test_t*)pl.malloc(); test->a = 100; for(int i=0; i<5; i++) { test->b[i] = i+2; } cout << "pool a:\t" << test->a << endl; cout << "pool b2:\t" << test->b[2] << endl; pl.free(test); }其中my_pool_test_t内部使用了 柔性数组。就是申请一个 my_pool_test_t,赋值并使用。
从名字也能够看出来,这个内存池是对象内存次,是分配object的。 函数
他和pool最大的区别也在此。 pool每次须要指定分配大小,它不须要,可是他须要指定分配的类型(其实经过类型能算出大小)。 spa
示例代码以下: .net
class Class_Demo { public: int a; int b; Class_Demo(int ia=1, int ib =2 ) : a(ia), b(ib) {} }; void test_object_pool() { object_pool <Class_Demo> pclass; Class_Demo *cl = pclass.malloc(); cl = pclass.construct(2,3); cout << "object pool a:\t" << cl -> a << endl; cout << "object pool b:\t" << cl -> b << endl; }这个就是直接分配一个类Class_Demo的内存池,赋值打印完事。
test_mem.cpp 指针
/*************************************************************************** * * Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved * **************************************************************************/ /** * @file test_mem.cpp * @author liujun05(com@baidu.com) * @date 2014/02/26 14:04:16 * @brief * **/ #include<boost/pool/object_pool.hpp> #include<boost/pool/pool.hpp> #include<iostream> using namespace std; using namespace boost; typedef struct _my_pool_test_t { int a; int b[]; } my_pool_test_t; class Class_Demo { public: int a; int b; Class_Demo(int ia=1, int ib =2 ) : a(ia), b(ib) {} }; void test_pool() { pool<> pl( sizeof(my_pool_test_t) + 5* sizeof(int) ); my_pool_test_t* test = (my_pool_test_t*)pl.malloc(); test->a = 100; for(int i=0; i<5; i++) { test->b[i] = i+2; } cout << "pool a:\t" << test->a << endl; cout << "pool b2:\t" << test->b[2] << endl; pl.free(test); } void test_object_pool() { object_pool <Class_Demo> pclass; Class_Demo *cl = pclass.malloc(); cl = pclass.construct(2,3); cout << "object pool a:\t" << cl -> a << endl; cout << "object pool b:\t" << cl -> b << endl; } int main() { test_pool(); test_object_pool(); return 0; } /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */编译(请自行指定boost库地址)
g++ test_mem.cpp -o mem -I ../include/ -L../lib -lboost_system -lboost_thread执行,发现一切预期以内
liujun05@cq01-rdqa-dev012.cq01:~/test/boost/test$ ./mem pool a: 100 pool b2: 4 object pool a: 2 object pool b: 3