#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