macro.h
#include <iostream>
using namespace std;
#ifndef _MACRO_H_
#define _MACRO_H_
namespace liuqi {
class allocator {
private:
struct obj {
struct obj* next; //embedded pointer
};
public:
void* allocate(size_t);
void deallocate(void*, size_t);
private:
obj* freeStore = nullptr;
const int CHUNK = 5; //
};
void* allocator::allocate(size_t size) {
obj* p;
if(!freeStore) {
size_t chunk = CHUNK * size;
freeStore = p = (obj*)malloc(chunk);
for(int i=0; i<(CHUNK-1); ++i) {
p->next = (obj*)((char*)p + size);
p = p->next;
}
p->next = nullptr; // last
}
p = freeStore;
freeStore = freeStore->next;
return p;
}
void allocator::deallocate(void* p, size_t size) {
((obj*)p)->next = freeStore;
freeStore = (obj*)p;
}
};
//DECLARE_POOL_ALLOC -- used in class definition
#define DECLARE_POOL_ALLOC() \
public:\
void* operator new(size_t size) { \
return myAlloc.allocate(size); \
} \
void operator delete(void* p) { \
myAlloc.deallocate(p, 0); \
} \
protected: \
static liuqi::allocator myAlloc;
//IMPLEMENT_POOL_ALLOC -- used in class implementation
#define IMPLEMENT_POOL_ALLOC(class_name) \
liuqi::allocator class_name::myAlloc;
#endif // _MACRO_H_
main.cpp
#include <iostream>
#include <complex>
#include "macro.h"
using namespace std;
class Foo {
DECLARE_POOL_ALLOC()
public:
long L;
string str;
public:
Foo(long l): L(l) {
}
};
IMPLEMENT_POOL_ALLOC(Foo)
class Goo {
DECLARE_POOL_ALLOC()
public:
complex<double> c;
string str;
public:
Goo(const complex<double> x): c(x) {
}
};
IMPLEMENT_POOL_ALLOC(Goo)
int main() {
Foo* p[100];
cout << "sizeof(Foo)= " << sizeof(Foo) << endl;
for(int i=0; i<23; ++i) {
p[i] = new Foo(i);
cout << p[i] << ' ' << p[i]->L << endl;
}
for(int i=0; i<23; ++i) {
delete p[i];
p[i] = NULL;
}
Goo* pp[100];
cout << "sizeof(Goo)= " << sizeof(Goo) << endl;
for(int i=0; i<17; ++i) {
pp[i] = new Goo(complex<double>(i, i));
cout << pp[i] << ' ' << pp[i]->c << endl;
}
for(int i=0; i<17; ++i) {
delete pp[i];
pp[i] = NULL;
}
return 0;
}