From d8748d5c545a428eaeded92708f1e4e5d8cc8249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Wed, 17 Sep 2014 09:56:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Alloc=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=99=A8=E7=9A=84=E7=B1=BB=E5=A3=B0=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/Alloc.h | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 TinySTL/Alloc.h diff --git a/TinySTL/Alloc.h b/TinySTL/Alloc.h new file mode 100644 index 0000000..b474787 --- /dev/null +++ b/TinySTL/Alloc.h @@ -0,0 +1,49 @@ +#ifndef _ALLOC_H_ +#define _ALLOC_H_ + +namespace TinySTL{ + + /* + **空间配置器 + */ + class alloc{ + private: + enum EAlign{ ALIGN = 8};//小型区块的上调边界 + enum EMaxBytes{ MAXBYTES = 128};//小型区块的上限 + enum ENFreeLists{ NFREELISTS = (EMaxBytes::MAXBYTES / EAlign::ALIGN)};//free-lists的个数 + private: + //free-lists的节点构造 + union obj{ + union obj *next; + char client[1]; + }; + + static obj *free_list[ENFreeLists::NFREELISTS]; + private: + static char *start_free;//内存池起始位置 + static char *end_free;//内存池结束位置 + static size_t heap_size;// + private: + //将bytes上调至8的倍数 + static size_t ROUND_UP(size_t bytes){ + return ((bytes + EAlign::ALIGN - 1) & ~(EAlign::ALIGN - 1)); + } + //根据区块大小,决定使用第n号free-list,n从0开始计算 + static size_t FREELIST_INDEX(size_t bytes){ + return (((bytes)+EAlign::ALIGN - 1) / EAlign::ALIGN - 1); + } + //返回一个大小为n的对象,并可能加入大小为n的其他区块到free-list + static void *refill(size_t n); + //配置一大块空间,可容纳nobjs个大小为size的区块 + //如果配置nobjs个区块有所不便,nobjs可能会降低 + static char *chunk_alloc(size_t size, size_t& nobjs); + + public: + static void *allocate(size_t bytes); + static void deallocate(void *ptr, size_t bytes); + static void *reallocate(void *ptr, size_t old_sz, size_t new_sz); + }; + +} + +#endif \ No newline at end of file