簡單說說何為之STL的記憶體管理Allocator

來源:才華庫 2.43W

1. 概述

簡單說說何為之STL的記憶體管理Allocator

STL Allocator是STL的記憶體管理器,也是最低調的部分之一,你可能使用了3年stl,但卻不知其為何物。

STL標準如下介紹Allocator

the STL includes some low-level mechanisms for allocating and deallocating memory. Allocators are very specialized, and you can safely ignore them for almost all purposes. Allocators encapsulate allocation and deallocation of memory. They provide a low-level interface that permits efficient allocation of many small objects; different allocator types represent different schemes for memory management.

將其描述為空間配置器,理由是allocator可以將其它儲存介質(例如硬碟)做為stl 容器的儲存空間。由於記憶體是allocator管理的主要部分,因此,本文以STL記憶體管理為出發點介紹allocator。

Allocator就在我們身邊,通常使用STL的.方式:

#include

std::vectorArray(100);

本質上,呼叫的是:

#include

std::vectorArray(100);

std::allocator就是一個簡單的Allocator

2. 使用

針對不同的應用場合,STL中實現了不同的Allocator,如下(gcc-3.4:~etsman/Docs/gcc-3.4-base/libstdc++/html/20_util/):

__gnu_cxx::new_allocatorSimply wraps ::operator new and ::operator .

__gnu_cxx::malloc_allocatorSimply wraps malloc and free. There is also a hook for an out-of-memory handler

__gnu_cxx::debug_allocatorA wrapper around an arbitrary allocator A. It passes on slightly increased size requests to A, and uses the extra memory to store size information.

__gnu_cxx::__pool_allocA high-performance, single pool allocator. The reusable memory is shared among identical instantiations of this type.

__gnu_cxx::__mt_allocA high-performance fixed-size allocatorthat was initially developed specifically to suit the needs of multi threaded applications

__gnu_cxx::bitmap_allocato A high-performance allocator that uses a bit-map to keep track of the used and unused memory locations

例如,在多執行緒環境下,可以使用:

複製程式碼 程式碼如下:

#include

#include

std::vectorArray(100);

3.一個簡單的Allocator實現

我們可以實現自己的allocator

複製程式碼 程式碼如下:

#include

template

class my_allocator : public std::allocator

{

public:

typedef std::allocatorbase_type;

// 必須要重新定義

template

struct rebind

{

typedef my_allocatorother;

};

// 記憶體的分配與釋放可以實現為自定義的演算法

pointer allocate(size_type count)

{

return (base_type::allocate(count));

}

void deallocate(pointer ptr, size_type count)

{

base_type::deallocate(ptr, count);

}

// 建構函式

my_allocator()

{}

my_allocator(my_allocatorconst&)

{}

my_allocator& operator=(my_allocatorconst&)

{

return (*this);

}

template

my_allocator(my_allocatorconst&)

{}

template

my_allocator& operator=(my_allocatorconst&)

{

return (*this); }

};

熱門標籤