Per-class allocator 2

#include <iostream>
#include <cstddef>

using namespace std;


//ref. Effective C++ 2e,item 10
//1.malloc效率
//2.cookie管理
//per-class allocator,2


class Airplane {
private:
	struct AirplaneRep {
		unsigned long miles;
		char type;	
	};
private:
	union {
		AirplaneRep rep;  //此处针对使用中的objects
		Airplane* next;  //处针对free list上的object
				//embeded pointer 嵌入式指针
	};
public:
	unsigned long getMiles() {
		return rep.miles;
	}
	char getType() {
		return rep.type;
	}
	void set(unsigned long m, char t) {
		rep.miles = m;
		rep.type = t;
	}
public:
	static void* operator new(size_t size);
	static void operator delete(void* deadObject, size_t size);
private:
	static const int BLOCK_SIZE;	
	static Airplane* headOfFreeList;
};

Airplane* Airplane::headOfFreeList = 0;
const int Airplane::BLOCK_SIZE = 512;	


void* Airplane::operator new(size_t size) {
	//如果大小有误,转交给::operator new()
	//继承体系中
	if(size != sizeof(Airplane)) {
		return ::operator new(size);
	}
	
	Airplane *p = headOfFreeList;
	if(p) {
		//如果p有效,就把list头部下移一个元素
		headOfFreeList = p->next;
	} else {
		//free list是空的,所以申请一大块
		Airplane* newBlock = static_cast<Airplane*>
			(::operator new(BLOCK_SIZE * sizeof(Airplane)));		

		//将小块串成一个free list,
		//但跳过 #0, 因它将被传回做为本次成果
		for(int i=1; i<BLOCK_SIZE-1; ++i) {
			newBlock[i].next = &newBlock[i+1];
		}
		newBlock[BLOCK_SIZE-1].next = 0;
		p = newBlock;
		headOfFreeList = &newBlock[1];
	}
	return p;
}


void Airplane::operator delete(void* deadObject, size_t size) {
	if(deadObject == 0) return;
	if(size != sizeof(Airplane)) {
		::operator delete(deadObject);
		return ;
	}

	Airplane* carcass = 
		static_cast<Airplane*>(deadObject);
	
	carcass->next = headOfFreeList;
	headOfFreeList = carcass;
}


int main() {
	
	cout << "sizeof(Airplane)" << sizeof(Airplane) << endl;
		
	size_t const N = 100;
	Airplane* p[N];
	
	for(int i=0; i<N; ++i) {
		p[i] = new Airplane;
	}
	
	p[1]->set(1000, 'A');
	p[5]->set(2000, 'B');
	p[9]->set(500000, 'C');

	for(int i=0; i<10; ++i) {
		cout << p[i] << endl;
	}
	
	cout << p[1]->getType() << " " << p[1]->getMiles() << endl;
	for(int i=0; i<N; ++i) {
		delete p[i];
		p[i] = NULL;
	}
	return 0;
}

使用member operator/delete的结果,相邻的地址之间没有cookie


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值