一:嵌入式指针(embedded pointer)
嵌入式指针概念
一般应用在内存池相关的代码中; 成功使用嵌入式指针有个前提条件:(类A对象的sizeof必须不小于4字节)
嵌入式指针工作原理:借用A对象所占用的内存空间中的前4个字节,这4个字节用来 链住这些空闲的内存块;
但是,一旦某一块被分配出去,那么这个块的 前4个字节 就不再需要,此时这4个字节可以被正常使用;
嵌入式指针演示
sizeof()超过4字节的类就可以安全的使用嵌入式指针,因为,在当前的vs2017环境下,指针的sizeof值是4
struct里放了一个指针,它的大小为4个字节。这个指针的值,存着下一个内存的地址。
class TestEP
{
public:
int m_i;
int m_j;
public:
struct obj //结构 //定义一个类型,不放在外部,污染全局变量
{
//成员,是个指针
struct obj *next; //这个next就是个嵌入式指针
//自己是一个obj结构对象,那么把自己这个对象的next指针指向 另外一个obj结构对象,最终,把多个自己这种类型的对象通过链串起来;
};
};
void func()
{
TestEP mytest;
cout << sizeof(mytest) << endl; //8
TestEP::obj *ptemp; //定义一个指针
ptemp = (TestEP::obj *)&mytest; //把对象mytest首地址给了这个指针ptemp,这个指针ptemp指向对象mytest首地址;
cout << sizeof(ptemp->next) << endl; //4
cout << sizeof(TestEP::obj) << endl; //4
ptemp->next = nullptr;
}
二:内存池代码的改进
单独的为内存池技术来写一个类
专门的内存池类
class myallocator //必须保证应用本类的类的sizeof()不少于4字节;否则会崩溃或者报错;
{
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字节,老师演示时定义了两个int成员变量;
};
IMPLEMENT_POOL_ALLOC(A)
void func()
{
A *mypa[100];
for (int i = 0; i < 15; ++i)
{
mypa[i] = new A(); //调用重载的operator new/delete
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];
}
}
}