1. 程式人生 > >STL源碼剖析之allocator(1)

STL源碼剖析之allocator(1)

bsp 初始 參數 使用 分配 最大 bin 初始化 pre

空間配置器(allocator)這個概念在閱讀源碼之前我根本沒有聽過,原以為內存分配都是使用new和delete運算符(註意和operator new、placement new、operator delete以及placement delete不同)。在實際使用STL編程時也很少會遇到自己去實現一個空間配置器的情況。事實上,STL容器背後都要依靠空間配置器去分配空間。在閱讀容器等STL組件的實現之前如果不了解空間配置器的原理,就會造成閱讀上的困難。在侯捷的《STL源碼剖析》一書中說道:為什麽不說allocator是內存配置器而說它是空間配置器呢?因為空間不一定是內存,空間也可以是磁盤或其他輔助介質。但是目前我還沒遇到過除內存外的資源配置情況,下文介紹SGI STL中的源碼也都是對內存的配置。

根據STL的規範,allocator必須實現以下接口:

allocator::value_type  
allocator::pointer
allocator::const_pointer
allocator::reference
allocator::const_reference
allocator::size_type
allocator::difference_type

定義了用於iterator traits的相關型別,具體到iterator traits技術再介紹。

allocator::rebind

一個類模板,內部聲明了類型other,代表allocator<U>。如果有了allocator<T>,想要allocator<U>和allocator<T>有相同分配策略,那麽allocator<U>等同於allocator<T>::rebind<U>::other。

allocator::allocator()
allocator::allocator(const allocator&)
template<class U> allocator::allocator(const allocator<U>&)
allocator::~allocator()

alllocator的默認構造函數、復制構造函數、帶模板的復制構造函數,以及析構函數。

pointer allocator::address(reference x) const    //等同於&x
pointer allocator::address(const_reference x) const
//等同於&x

返回對象地址,區別在於傳入參數是否是const

void allocator::allocate(size_type n, const void* = 0)

分配空間但不初始化

void allocator::deallocate(pointer p, size_type n)

回收空間

void allocator::max_size() const

返回可成功配置的最大量

void allocator::construct(pointer p, const T& x)

等同於 new ((void *) p) T(x)

void allocator::destroy(pointer p)

等同於 p->~T()

SGI實際使用的配置器為alloc而不是allocator,且不接受任何參數。如果要在程序中使用SGI提供的配置器不能寫成類似於

vector<int, std::allocator<int> > iv

而是

vector<int, std::alloc> iv;

說明:在Visual Studio 2017中上面的定義沒有什麽問題,gcc/g++沒有測試過不知道可不可以。第二個vc++肯定不行,g++未知。

SGI STL為每個容器都指定了缺省的空間配置器為alloc,如下面vector的聲明:

template<class T, class Alloc = alloc>
class vector { ... };

STL源碼剖析之allocator(1)