Per-class allocator 1

#include <iostream>
#include <cstddef>

using namespace std;


//ref. C++Primer 3/e.p.765
//1.malloc效率
//2.cookie管理
//per-class allocator


class Screen {
public:
	Screen(int x): i(x) {
	}
	
	int get() {
		return i;
	}	
	
	void* operator new(size_t);
	void operator delete(void*, size_t);
private:
	//这种设计会引发多好用一个next的疑虑
	Screen* next;
	static Screen* freeStore;
	static const int screenChunk;	
private:
	int i;
};

Screen* Screen::freeStore = 0;
const int Screen::screenChunk = 24;	


void* Screen::operator new(size_t size) {
	Screen *p;
	if(!freeStore) {
		//linked list是空的,所以申请一大块
		size_t chunk = screenChunk * size;
		freeStore = p = 
			reinterpret_cast<Screen*>(new char[chunk]);
		
		//将一大块,当做linked list串起来
		for(; p != &freeStore[screenChunk-1]; ++p) {
			p->next = p + 1;
		}
		p->next = 0;
	}
	
	p = freeStore;
	freeStore = freeStore->next;
	return p;
}


void Screen::operator delete(void* p, size_t size) {
	//将deleted object插回到 free list前端
	(static_cast<Screen*>(p))->next = freeStore;
	freeStore = static_cast<Screen*>(p);
}


int main() {
	
	cout << "sizeof(Screen)" << sizeof(Screen) << endl;
		
	size_t const N = 100;
	Screen* p[N];
	
	for(int i=0; i<N; ++i) {
		p[i] = new Screen(i);
	}
	
	for(int i=0; i<10; ++i) {
		cout << p[i] << endl;
	}

	for(int i=0; i<N; ++i) {
		delete p[i];
		p[i] = NULL;
	}
	return 0;
}


使用member operator/delete的结果,不一定地址间隔差别8,但是结果差别8更好的显示没有cookie



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值