C++ 内存管理03-内存池02

本文深入探讨了内存池设计中的优化技巧,通过使用匿名联合体和嵌入式指针,避免了额外的内存开销。具体介绍了如何在C++中实现内存池,包括自定义new和delete操作符,以及如何利用联合体特性节省空间。

内存池02

通过上一节的介绍,你应该能够对内存管理有个大概的了解,上一节提到为了设计内存池增加了一个指针next,但它额为增加了4个字节,这不是我们所需要的。于是对它进行了优化,先看代码和云心结果

#define   _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class foo{
public:
	struct MyStruct
	{
		int a;
		int b;
	};
	union 
	{
		MyStruct re;
		foo *next;
	};
	

	void setData(int x,int y)
	{
		re.a = x;
		re.b = y;

	}

	void showmsg()
	{
		cout << re.a << "  " << re.b << endl;
	}

	static void *operator new(size_t size)
	{
	
		foo *p;
		if (!freestore)
		{
			size_t nsize = size*ncount;
			freestore = p = reinterpret_cast<foo *>(new char[nsize]);
			for (int i = 0; i < ncount; i++)
			{
				p->next = p + 1;
				p++;
			}
			p->next = NULL;
		}
		p = freestore;
		freestore = freestore->next;
		return p;
	}
	
	static void operator delete(void *p)
	{
		//将回收的内存放到头节点。
		(static_cast<foo *>(p))->next = freestore;
		
		//将第一个内存指向回收的内存
		freestore = static_cast<foo *>(p);
		
	}

	
	~foo()
	{
		cout << "~foo()\n";
	}
public:
	

	static const int ncount;
	static foo *freestore;
};

const int foo::ncount = 24;
foo *foo::freestore = NULL;

void main()
{
	cout << sizeof(foo) << endl;
	foo *pfoo[100];
	for (int i = 0; i < 100; i++)
	{
		pfoo[i] = new foo;
		pfoo[i]->setData(i + 1, i + 2);

	}

	for (int i = 80; i < 90;i++)
	{
		cout << pfoo[i] << "  ";
		pfoo[i]->showmsg();
	}
	system("pause");
}

运行结果;
在这里插入图片描述
和上一个例子的最大区别就在于将数据部分写在一个结构体中,然后使用了匿名union,这样为了节省next指针的内存空间。因为联合体同时只能存在一个变量。这也叫做嵌入式指针。从运行结果可以看出间隔为8.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

发如雪-ty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值