STL 空間配置器 allocator《一》

2021-08-13 23:21:59 字數 1417 閱讀 3845

stl的操作物件(所有的數值)都存放在容器之中,而容器則需要配置空間以置放資料。最近在看侯捷的《stl原始碼剖析》,所以做了筆記。

為什麼不說allocator是記憶體配置器而說他是空間配置器呢?

因為空間不一定是記憶體,空間也可以是磁碟或其他輔助儲存介質。

一般意義上理解:

- 物件構造的分解: 物件記憶體開闢allocator | 物件構造 construct

- 物件析構的分解: 物件記憶體釋放deallocate | 物件析構destroy

1.具備次配置力的sgi空間配置器

1.1 構造和析構:construct() 和 destroy()

/*構造construct*/

template

inline

void construct(t1* p, const t2& value)

// destroy() 第1版本,接受1個指標。

template

inline

void destroy(t* pointer)

// 以下是 destroy() 第2版本,接受兩個迭代器。此函式設法找出元素的數值型別,

// 進而利用 __type_traits<> 求取最適當措施。

template

inline

void destroy(forwarditerator first, forwarditerator last)

// 判斷元素的數值型別( value type)是否有 trivial destructor

template

inline

void __destroy(forwarditerator first, forwarditerator last, t*)

// 如果元素的數值型別( value type)有 non-trivial destructor…

template

inline

void

__destroy_aux(forwarditerator first, forwarditerator last, __false_type)

// 如果元素的數值型別( value type)有 trivial destructor…

template

inline

void __destroy_aux(forwarditerator, forwarditerator, __true_type) {}

// 以㆘是 destroy() 第㆓版本針對迭代器為 char* 和 wchar_t* 的特化版

inline

void destroy(char*, char*) {}

inline

void destroy(wchar_t*, wchar_t*) {}

STL原始碼剖析 空間配置器(allocator)

一般容器都需要一定空間存放資料,allocator就是用來配置空間的,sgi的allocator配置的物件時記憶體。乙個allocator通常包含兩個部分,一是記憶體配置和記憶體釋放 allocate的deallocate 二是物件構造和析構 construct和destory ifndef jja...

STL 空間配置器

stl有6大元件 容器 演算法 迭代器 仿函式 配接器 分配器。它們之間的密切關係是stl的精髓所在,容器用來存放資料,而容器存在的前提是要有分配器給它分配記憶體,接下來需要實現演算法,迭代器便作為演算法來對容器資料操作的橋梁,演算法可以使用仿函式完成不同的策略變化,配接器可修飾或套接仿函式。說了麼...

STL 空間配置器

stl空間配置器的底層原理 維護了乙個狹義的記憶體池,並且用乙個自由鍊錶來維護該記憶體池。該自由鍊錶比較類似於雜湊的開鏈法的儲存結構。源 pragma once using namespace std define throw bad alloc cerr out of memory endl ex...