#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