2.空间配置器
2.1具备次配置力(sub-allocation)的SGI空间配置器
SGI含有两个空间配置器类,std::allocator内存分配类符合标准,但是仅仅是对operator new和operator delete简单封装一下而已;其次是SGI特殊的内存分配器std::alloc,其中实现采用了内存池,对于分配大量小容量的对象,可以大大减少内存碎片。
SGI标准的空间配置器std::allocator

这是对应的模板内联内存分配函数。实现起来也很简单,注意这里分配的内存仅仅是一块没有使用的空间而已,在上面并没有构造对象,后面讲解如何在上面构造对象。

模板内联内存释放函数,直接调用全局的operator delete释放对应的内存。

SGI特殊的空间配置器Std::alloc
class Foo{…}
Foo* pf = new Foo;//配置内存,然后构造对象
delete pf;//将对象析构,然后释放内存
new的算是包含两个阶段:
1) 调用::operator new 配置内存
2) 调用Foo::Foo()构造对象内容
Delete算式也包含两个阶段
1) 调用Foo::~Foo()将对象析构
2)调用::operator delete释放内存
为了精密分工,STL allocator将两个阶段的操作分开来,内存配置操作由alloc::allocate()负责,内存释放操作由alloc::deallocate()负责;对象构造由::construct()负责,对象析构由::destroy()负责。


2.stl_alloc.h 内存空间的分配和释放
内部使用malloc在堆中申请内存,其中制造了一个内存池,可以减少小型区块过多而造成的内存碎片问题。
SGI设计了双层级配置器,第一级配置器直接使用malloc()和free(),第二级配置器则视情况采用不同的策略:当配置区块超过128bytes时,采用第一级配置器,当配置区块小于128bytes时,采用第二级配置器,采用复杂的memory pool。它内存池实际上就是内部维护了16个自由链表,预先已经分配好了,当需要从内存池中取内存时候,直接从对应链表取出即可;当释放内存到内存池时候,直接将内存插入链表即可。每个链表中节点分别占用8、16、24、32、40、48、52、64、72、80、88、96、104、112、120、128字节。



举例:


2.2 内存操作全局函数

1、uninitialized_copy
将迭代器[first ,
last)范围内的内容拷贝到result指定的区域。如果first是char 或wchar 那么直接使用memmove拷贝即可,如果first不是上述类型,则通过辨别是否是POD类型来选择构造函数或者copy拷贝。


uninitialized_copy使我们能够将内存的配置和对象的构造行为分离。

2、uninitialized_fill
将[first , last)迭代器指定范围的内存,通过x初始化。换句话说,该函数会针对操作范围内的每个迭代器i,调用construct(&*I,x),在i所指之处产生x的复制品。与uninitialied_copy()一样,该函数具备“commit or rollback”语义,要么产生所有必要元素,要么不产生任何元素。如果任何一个copy constructor丢出异常(exception),该函数能够将已产生的所有元素析构掉。

3、uninitialized_fill_n
将[first , first+n)范围内的每一个迭代器都设定为x,总共设定了n个,当是pod类型,则直接拷贝x到指定的迭代器,不是pod类型,那么在每一个迭代器上以x为初值进行构造。
上述是uninitialized_fill_n对应的简单函数调用关系,重点在于理解POD类型。POD意思就是Plain
Old Data,也就是标量类型以及传统的C struct类型。POD类型必须含有无用的构造函数、析构函数、拷贝构造、赋值运算符函数。因此堆POD类型可以直接进行字节拷贝初始化,而非POD类型采用最安全的做法,也就是通过对应的构造函数初始化。


总结图:三个内存基本函数的泛型版本与特化版本

网友评论