最近学习内存管理方面的知识用到了一个概念 嵌入式指针(embedded pointer)
嵌入式指针工作原理:
借助对象占用内存的空间 在用户获取到该内存时先用指针(pointer) 连接整个内存块,当用户通过new占用该内存时自然可以覆盖该内存中的数据进行使用union中的对象,当用户释放这块内存时,又可以将其中内存数据覆盖为指针(pointer)使用连接到内存块链表上
//大致流程
//先创建内存块链表
for (int i = 0; i < BLOCK_SIZE; i++)
{
newBlock[i].next = &newBlock[i + 1];
}
//用户创建对象
MemoryPool p = new MemoryPool;
//用户释放对象
delete p;
//使用next在将该内存连接到内存块链表上
MemoryPool* p = static_cast<MemoryPool*>(pdead);
p->next = headOfFreelist;
headOfFreelist = p;
MemoryPool 版本 2
#pragma once
#include<cstddef>
#include<iostream>
using namespace std;
class MemoryPool
{
public:
char gettype() { return rep.type ; }
unsigned long getmiles() { return rep.miles; }
void set(char type,unsigned long d) {
rep.miles = d;
rep.type = type;
}
private:
struct AirPlaneRep{
unsigned long miles;
char type;
};
private:
union { //object
AirPlaneRep rep;
MemoryPool* next; //嵌入式指针(embedded pointer) 分配内存时用 在new出来之后
// union对象使用内部对象 而在delete之后重新使用指针进行内存池的连接
};
public:
static void* operator new (size_t size);
static void operator delete(void* pdead, size_t size);
private:
static const int BLOCK_SIZE;
static MemoryPool* headOfFreelist;
};
const int MemoryPool::BLOCK_SIZE = 512;
MemoryPool* MemoryPool::headOfFreelist;
void* MemoryPool::operator new(size_t size)
{
if (size != sizeof(MemoryPool))
return ::operator new(size);
MemoryPool* p = headOfFreelist;
if (p)
{
headOfFreelist = headOfFreelist->next;
}
else
{
MemoryPool* newBlock = static_cast<MemoryPool*>
(::operator new(BLOCK_SIZE * sizeof(MemoryPool)));
for (int i = 1; i < BLOCK_SIZE; i++)
{
newBlock[i].next = &newBlock[i + 1];
}
newBlock[BLOCK_SIZE - 1].next = nullptr;
p = newBlock;
headOfFreelist = &newBlock[1];
}
return p;
}
void MemoryPool::operator delete(void* pdead, size_t size)
{
if (pdead == nullptr) return;
if (size != sizeof(MemoryPool)) {
::operator delete(pdead);
}
MemoryPool* p = static_cast<MemoryPool*>(pdead);
p->next = headOfFreelist;
headOfFreelist = p;
}