一:嵌入式指针(embedded pointer)
-
一般应用在内存池相关的代码中; 成功使用嵌入式指针有个前提条件:(类A对象的sizeof必须不小于4字节)
-
嵌入式指针工作原理:借用A对象所占用的内存空间中的前4个字节,这4个字节用来作为链表的next指针域;
-
但是,一旦某一块被分配出去,那么这个块的 前4个字节 就不再需要,此时这4个字节可以被正常使用;
-
sizeof()超过4字节的类就可以安全的使用嵌入式指针,因为,在当前的vs2017环境下,指针的sizeof值是4
针对单个对象的内存池代码
namespace _nmsp4
{
class myallocator
{
public:
//分配内存接口
void *allocate(size_t size)
{
obj *tmplink;
if (m_FreePosi == nullptr)
{
//为空,我要申请内存,要申请一大块内存
size_t realsize = m_sTrunkCout * size; //申请m_sTrunkCout这么多倍的内存
m_FreePosi = (obj *)malloc(realsize);
tmplink = m_FreePosi;
//把分配出来的这一大块内存(5小块),彼此用链起来,供后续使用
for (int i = 0; i < m_sTrunkCout - 1; ++i) //0--3
{
tmplink->next = (obj *)((char *)tmplink + size);
tmplink = tmplink->next;
} //end for
tmplink->next = nullptr;
} //end if
tmplink = m_FreePosi;
m_FreePosi = m_FreePosi->next;
return tmplink;
}
//释放内存接口
void deallocate(void *phead)
{
((obj *)phead)->next = m_FreePosi;
m_FreePosi = (obj *)phead;
}
private:
//写在类内的结构,这样只让其在类内使用
struct obj
{
struct obj *next; //这个next就是个嵌入式指针
};
int m_sTrunkCout = 5;//一次分配5倍的该类内存作为内存池子的大小
obj* m_FreePosi = nullptr;
};
//封装成宏函数
#define DECLARE_POOL_ALLOC()\
public:\
static myallocator myalloc;\
static void *operator new(size_t size)\
{\
return myalloc.allocate(size);\
}\
static void operator delete(void *phead)\
{\
return myalloc.deallocate(phead);\
}\
//封装
#define IMPLEMENT_POOL_ALLOC(classname)\
myallocator classname::myalloc;
class A
{
DECLARE_POOL_ALLOC()
public:
int m_i;
int m_j; //为了保证sizeof(A)凑够4字节
};
IMPLEMENT_POOL_ALLOC(A)
void func()
{
A *mypa[100];
for (int i = 0; i < 15; ++i)
{
mypa[i] = new A();
mypa[i]->m_i = 12;
mypa[i]->m_j = 15;
printf("%p\n", mypa[i]);
}
for (int i = 0; i < 15; ++i)
{
delete mypa[i];
}
}
}
int main()
{
_nmsp4::func();
return 1;
}