Chinaunix首页 | 论坛 | 博客
  • 博客访问: 298949
  • 博文数量: 148
  • 博客积分: 4365
  • 博客等级: 上校
  • 技术积分: 1566
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-05 21:38
文章分类
文章存档

2014年(2)

2013年(45)

2012年(18)

2011年(1)

2009年(54)

2008年(28)

我的朋友

分类: C/C++

2013-01-22 15:36:15

Item 51: Adhere to convention when writing new and delete


scott这里给了一个new的大致流程伪代码,非常有用:

void * operator new(std::size_t size) throw(std::bad_alloc)
{                                      // your operator new might take additional params
  using namespace std;     
  if (size == 0) {                     // handle 0-byte requests by treating them as 1-byte requests
    size = 1;
  } 
  while (true) {
   attempt to allocate size bytes;
    if (the allocation was successful)
       return (a pointer to the memory);


    // allocation was unsuccessful; find out what the
    // current new-handling function is (see below)

    new_handler globalHandler = set_new_handler(0);
    set_new_handler(globalHandler);
    if (globalHandler) (*globalHandler)();
    else throw std::bad_alloc();
  }
}
空类或结构都是会占据1字节的,前面的item讲过,调用 set_new_handler,其返回值是当前handler,回调之,如果已经是NULL了,异常之。

E文参考资料是这么说的:get_new_handler 是c++0x新增的

Allocates count bytes from free store. Calls the function pointer returned by std::get_new_handler on failure and repeats allocation attempts until new handler does not return or becomes a null pointer, at which time throws std::bad_alloc. 


scott在这个item强调的是new内部的无限循环,和其终止条件;对0内存申请的特殊处理;delete要对空指针进行保护。


阅读(373) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~