内存管理中最常用的就是对象池了
boost的object_pool设计概念是好的,但是中间的排序逻辑消耗非常大,所以我都是使用pool修改来使用
1 #pragma once 2 #include <boost/pool/pool.hpp> 3 #include <boost/smart_ptr.hpp> 4 #include <boost/bind.hpp> 5 6 //暂时不考虑线程安全 7 template<class obj_type> 8 class enable_obj_pool: 9 public boost::enable_shared_from_this<obj_type> 10 { 11 static boost::pool<> m_pool; 12 13 public: 14 static boost::shared_ptr<obj_type> malloc() 15 { 16 void * mem = m_pool.malloc(); 17 if(!mem) 18 return nullptr; 19 20 obj_type* pobj = new(mem) obj_type(); 21 22 return boost::shared_ptr<obj_type>(pobj, boost::bind(&obj_type::free, _1));; 23 } 24 25 static void free(obj_type* pobj) 26 { 27 pobj->~obj_type(); 28 m_pool.free(pobj); 29 } 30 31 static void release() 32 { 33 m_pool.release_memory(); 34 } 35 }; 36 37 #define enable_obj_pool_init(c_type) boost::pool<> enable_obj_pool<c_type>::m_pool(sizeof(c_type));
下面是对比测试结果:
1 // CPPlusTest.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include "enable_object_pool.h" 6 #include <string> 7 #include <list> 8 #include <boost/timer.hpp> 9 #include <boost/pool/object_pool.hpp> 10 11 class A : public enable_obj_pool<A> 12 { 13 public: 14 A() 15 { 16 s=""; 17 }; 18 ~A() 19 { 20 } 21 std::string s; 22 }; 23 enable_obj_pool_init(A); 24 25 boost::object_pool<A> oap; 26 27 void oap_free(A* pa) 28 { 29 oap.destroy(pa); 30 } 31 32 int _tmain(int argc, _TCHAR* argv[]) 33 { 34 const int testcount = 100000; 35 std::list<boost::shared_ptr<A>> sl; 36 boost::timer t; 37 { 38 printf("\ntest 1\n"); 39 t.restart(); 40 for (int i = 0;i<testcount;i++) 41 { 42 sl.push_back(A::malloc()); 43 } 44 printf("new time:%lf\n",t.elapsed()); 45 } 46 47 t.restart(); 48 sl.clear(); 49 printf("del time:%lf\n",t.elapsed()); 50 51 printf("\ntest 2\n"); 52 t.restart(); 53 for (int i = 0;i<testcount;i++) 54 { 55 sl.push_back(boost::shared_ptr<A>(oap.construct(), boost::bind(&oap_free, _1))); 56 } 57 printf("new time:%lf\n",t.elapsed()); 58 59 t.restart(); 60 sl.clear(); 61 printf("del time:%lf\n",t.elapsed()); 62 63 getchar(); 64 return 0; 65 }
原文:http://www.cnblogs.com/zhangchengxin/p/3653946.html