嵌入式指针(内存管理)2.0

最近学习内存管理方面的知识用到了一个概念 嵌入式指针(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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DyingLive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值