设为首页 加入收藏

TOP

effectiveC++(十)(三)
2010-12-26 23:05:16 】 浏览:19572
Tags:effectiveC
//

  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

首页 上一页 1 2 3 4 5 6 7 下一页 尾页 3/14/14
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇effectiveC++(十一) 下一篇effectiveC++(九)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目