Boost库学习随记四 pool内存池使用示例:pool、object_pool、singleton_pool、pool_alloc内存池

#include <iostream>
#include <vector>
#include <boost/pool/pool_alloc.hpp>
#include <boost/pool/object_pool.hpp>
#include <boost/pool/pool.hpp>
#include <boost/pool/singleton_pool.hpp>
using namespace std;
using namespace boost;
//pool内存池使用示例:pool
void pool_pool_fun()
{
	pool<>pl(sizeof(int));    //一个可分配int的内存池
	int *p = (int*)pl.malloc(); //必须把void*转换成需要的类型
	assert(pl.is_from(p));

	pl.free(p);               //释放内存池分配的内存块
	for (int i = 0; i < 100; ++i) //连续分配大量的内存
	{
		pl.ordered_malloc(10);
	}                               //内存池对象析构,所有分配的内存在这里都被释放
}

//pool内存池使用示例:object_pool  
struct demo_class  
{  
public:  
 int a, b, c;  
 demo_class(int x = 1, int y = 2, int z = 3) :a(x), b(y), c(z){}  
 
};  
void pool_fun()  
{  
  boost::object_pool<demo_class>pl;  
   
 
  demo_class *p = pl.malloc();  
  assert(pl.is_from(p));  
  
  //P指向的内存未经过初始化  
  assert(p->a != 1 || p->b != 2 || p->c != 3);  
  p = pl.construct(7, 8, 9);  
  assert(p->a == 7);  
  
  boost::object_pool<string>pls;  
  for (int i = 0; i < 10; ++i)  
  {  
     string *ps = pls.construct("hello object_pool");  
      cout << *ps << endl;  
  }  
}  

//singleton_pool内存池
struct pool_tag{};                                 //仅仅用于标记的空类
typedef singleton_pool<pool_tag, sizeof(int)>spl;  //内存池定义
void singleton_pool_fun()
{
	int *p = (int *)spl::malloc();   //分配一个整数内存块
	assert(spl::is_from(p));
	spl::release_memory();        //释放所有未被分配的内存
}                                 //spl的内存直到程序结束才完全释放,而不是退出作用域
//pool_alloc内存池
void pool_alloc_fun()
{
	vector<int, pool_allocator<int>>v;  //使用pool_allocator代替标准容器默认的内存分配器
	v.push_back(10);                    //vector将使用新的分配器良好工作
	cout << v.size();
}
int main()
{
	pool_fun();
	pool_pool_fun();
	singleton_pool_fun();
	pool_alloc_fun();
	std::system("pause");
	return 0;
}

你可能感兴趣的:(Boost库学习随记四 pool内存池使用示例:pool、object_pool、singleton_pool、pool_alloc内存池)