//
static void * operator new(size_t size);
...
private:
union {
airplanerep *rep; // 用于被使用的对象
airplane *next; // 用于没被使用的(在自由链表中)对象
};
// 类的常量,指定一个大的内存块中放多少个
// airplane对象,在后面初始化
static const int block_size;
static airplane *headoffreelist;
};
上面的代码增加了的几个声明:一个operator new函数,一个联合(使得rep和next域占用同样的空间),一个常量(指定大内存块的大小),一个静态指针(跟踪自由链表的表头)。表头指针声明为静态成员很重要,因为整个类只有一个自由链表,而不是每个airplane对象都有。
下面该写operator new函数了:
void * airplane::operator new(size_t size)
{
// 把“错误”大小的请求转给::operator new()处理;
// 详见条款8
if (size != sizeof(airplane))
return ::operator new(size);
airplane *p = // p指向自由链表的表头
headoffreelist; //
// p 若合法,则将表头移动到它的下一个元素
//
if (p)
headoffreelist = p->next;
e