一、boost库中pool库-类图概要
1、概览
2、概述
2.1、struct default_user_allocator_new_delete 与 struct default_user_allocator_malloc_free
struct default_user_allocator_new_delete中定义两个静态函数用于内存的分配与释放,分别为static char * malloc (const size_type bytes)及static void free (char * const block),同样的struct default_user_allocator_malloc_free也定义了两个同样的函数用于内存的分配和内存的释放,只是实现的方式不同。
2.2、PODptr类
PODptr类是定义的一个“虚拟”指针类,含有两个成员变量指针ptr(void *)及sz(size_type),之后用于管理分配内存块(block)。
2.3、simple_segregated_storage类(简单的隔离存储)
simple_segregated_storage类定义了一个 void* first指针,它总指向下一个可用的内存区块,分配内存或删除内存时,first指针通常来说会改变。
2.3、pool类(内存池)
pool类保护继承simple_segregated_storage类,即所有simple_segregated_storage类中成员函数或成员变量在pool类中属性都被声明为protected,外界不能直接访问。pool类中含有一个PODptr*的指针名为list,它被之后用于帮助内存块之间产生联系。
二、boost内存池前置声明文件(boost/pool/poolfwd.hpp)
我们来仔细看看poolfwd.hpp关于pool类的一些内容即可:要注意的是模板的默认取值,SizeType = std::size_t及UserAllocator=default_user_alloccator_new_delete
//
// Location: <boost/pool/simple_segregated_storage.hpp>
//
template <typename SizeType = std::size_t>
class simple_segregated_storage;
//
// Location: <boost/pool/pool.hpp>
//
struct default_user_allocator_new_delete;
struct default_user_allocator_malloc_free;
template <typename UserAllocator = default_user_allocator_new_delete>
class pool;
三、 simple_segregated_storage类实现文件( boost/pool/simple_segregated_storage.hpp)
1、simple_segregated_storage类概览
2、成员变量(void* first)
simple_segregated_storage.hpp中含有快差不多400行代码,成员函数众多但成员变量只有一个void* first,我们简单看它的定义及boost库中对它的注释:
protected:
void * first;
它的作用是指向未被使用的内存区块(chunk),当没有可以用来使用的内存区块时,它的值为零。
3、成员函数
(1) static void * & extof(void * const ptr),作用是得到ptr指向的指针,并返回引用
static void * & nextof(void * const ptr)
{
return *(static_cast<void **>(ptr));
}
(2) simple_segregated_storage(),作用是初始化first指针,使得first == 0
simple_segregated_storage()
:first(0)
{
}
(3)static void * segregate(void * block, size_type nsz, size_type npartition_sz,void * end 0)
template <typename SizeType>
void * simple_segregated_storage<SizeType>::segregate(
void * const block,//内存块首部地址
const size_type sz,//内存块大小
const size_type partition_sz,//内存块分区大小
void * const end)//内存块尾部指针
{
// Get pointer to last valid chunk, preventing overflow on size calculations
// The division followed by the multiplication just makes sure that
// old == block + partition_sz * i, for some integer i, even if the
// block size (sz) is not a multiple of the partition size.
char * old = static_cast<char *>(block)
+ ((sz - partition_sz) / partition_sz) * partition_sz;
// Set it to point to the end
nextof(old) = end;
// Handle border case where sz == partition_sz (i.e., we're handling an array
// of 1 element)
if (old == block)
return block;
// Iterate backwards, building a singly-linked list of pointers
for (char * iter = old - partition_sz; iter != block;
old = iter, iter -= partition_sz)
nextof(iter) = old;
// Point the first pointer, too
nextof(block) = old;
return block;
}
利用此函数可将一块内存块(block)分解为多块内存区块(chunk),用简图描述如下: