为C++标准库容器写自己的内存分配程序
根据sgi 的STL源码的二级分配算法改写的内存池分配程序,只要稍微修改就可以实现共享内存方式管理,使用C++标准库容器中的map,set,multimap,multiset测试通过,vector测试通不过,原因是在内存回收的时候考虑的比较简单,vector每次分配内存个数不固定,回收也不固定,这样的话,程序还需要继续完善。o0c(pZ(l&S*ENu8Iio!]'] ]3`
内存池管理程序源码如下:
以下是引用片段:
#ifndef MY_ALLOCATOR_H_
#define MY_ALLOCATOR_H_ k"au!o!l#K ?}
#include "stdafx.h"
#include <limits> ~uQ_}
#include <iostream>
namespace happyever
{ l-x![+F:U
enum { NODENUMS = 2 }; [VzUWHw [x~A
union _Obj
{ w{E:]"p w?6Q
union _Obj* M_free_list_link; IP/I6xJNSq
char M_client_data[1];
} ; 3z5rD6G-d]9S*f
typedef union _Obj Obj; .X~f-{ z Y y
struct _Cookie
{
int iShmKey; /* 共享内存键值 */
int iShmID; /* iShmKey对应的shmid */
int iSemKey; /* 锁信号键值 */ G4o*nK,yD{7Hu}
int iSemID; /* 锁信号标识 */ 3z7c&h0@CzK
int iTotalsize; /* 容器总容量 */
void* pStartall; /* 共享内存自身地址 */
char* pStartfree; /* 自由空间的开始地址*/ Lc4wap0B(H
char* pEndfree; /* 自由空间的结束地址*/
int iUseNum[NODENUMS];
/*用来存放free_list中节点的size*/
short sFreelistIndex[NODENUMS];
/*存放分配内存节点的链表*/ zK&{Yo
Obj* uFreelist[NODENUMS]; Pw e#Qn$d9F L
};
typedef struct _Cookie Cookie;
//Obj;
//Cookie; 'q(iF%C1iw
static Cookie *pHead = NULL; ;I2O2y(vS$`K$`,]
template <class T>
class MyAlloc
{ (u?*FN@/C.w |
private:
static const int ALIGN = sizeof(Obj); k5Q^)y j b:f
int round_up(int bytes);
int freelist_index(int bytes);
int freelist_getindex(int bytes);
char* chunk_alloc(int size, int *nobjs); ;{!e3S(F7YN*d
void* refill(int num,int n); d;jZ ~%z\
public: fc2Fp@O|
// type definitions
typedef T value_type;
typedef T* pointer; 'W.T;hT&u z
typedef const T* const_pointer; G q+Mu z'V:V
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
template <class U>
struct rebind
{
typedef MyAlloc<U> other;
};
pointer address (reference value) const S E0o3zg6]
{
return &value; 4U2q Zo7iw'F b
}
const_pointer address (const_reference value) const b4G @"~P.W
{ 9^rvaJf
return &value;