1.內存池是預先分配一塊大的內存空間,然後可以再其中使用某種算法實現高效快速的自定製內存分配。內存池能夠管理大量的對象,而且在需要大量地分配/釋放小對象時很有效率,完全不用考慮delete,它近似於一個小型的垃圾回收機制。
一、pool類
pool類是一個可以返回POD的內存指針。位置:#include <boost/pool/pool.hpp>
類摘要:
template <typename UserAllocator = default_user_allocator_new_delete>
class pool
{
private:
pool(const pool &);
void operator=(const pool &);
public:
explicit pool(size_type requested_size);//構造函數接受一個size_type類型的整數,表示分配內存塊的大小(不是pool的大小)
~pool();
bool release_memory();
bool purge_memory();m
bool is_from(void * chunk) const;
size_type get_requested_size() const;
void * malloc();
void * ordered_malloc();
void * ordered_malloc(size_type n);
void free(void * chunk);
void ordered_free(void * chunk);
void free(void * chunks, size_type n);
void ordered_free(void * chunks, size_type n);
};
int main()
{
pool<> p1(sizeof(int));//設定每次分配的大小爲int大小。
int *p = (int*)p1.malloc();//內存分配函數。用void*返回。
p1.free(p);//規劃內存給內存池。
p1.is_from(p); //測試是否是從該pool中分配出去的。
p1.ordered_malloc(10);//連續分配n塊內存。
}
2.(最有用的) object_pool是用於類實例對象的內存池,與pool類似,但是析構時對所有分配的內存塊調用析構函數。但是它的特殊之處在於:construct()和destroy()函數,construct()有多個參數的重載形式,它調用malloc()分配內存,然後在內存池中出入參數調用類的構造函數,返回的是一個已經初始化的對象的指針,destory()則先調用對象的析構函數,然後再用free()釋放內存塊。位置:#include <boost/pool/object_pool.hpp>
template <typename ElementType, typename UserAllocator = default_user_allocator_new_delete>
class object_pool
{
public:
object_pool();
~object_pool();
element_type * malloc();
void free(element_type * p);
bool is_from(element_type * p) const;
element_type * construct();
// other construct() functions
void destroy(element_type * p);
};類似pool的用法。
#include <iostream>
#include <boost/smart_ptr.hpp>
#include <boost/pool/pool.hpp>
#include <boost/pool/object_pool.hpp>
using namespace boost;
using std::cout;
using std::endl;
using std::string;
class test
{
public:
int a, b, c;
test(int a1=1, int b1=2, int c1=3) : a(a1), b(b1), c(c1){}
void display()
{
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
~test()
{
cout<<"test, destory()"<<endl;
}
};
int main()
{
object_pool<test> p1;
test *p = p1.malloc();
p->a = 11, p->b = 22, p->c = 33;
p->display();//11 22 33
test *t = p1.construct(7, 8, 9);//調用構造函數構造一個初始化的對象。
t->display();//7 8 9
p1.destroy(p);//先調用析構函數,然後free內存返回給pool。
}