8.定制new和delete

来源:互联网 发布:电脑的网络图标不见了 编辑:程序博客网 时间:2024/05/18 02:50

Item49:Understand the behavior of the new-handler.

set_new_handler允许客户指定一个函数,在内存无法获得满足时调用。

Item50:Understand when it makes sense to replace new and delete.

当需要改善效能,对heap运用错误进行调试,收集heap使用信息时。

Item51:Adhere to convention when writing new and delete.

  • operator new 应该内含无穷循环,并在其中尝试分配内存,如果它无法满足内存需求,就该调用new_handler,需有能力处理0bytes申请,还应该能处理更大内存的错误申请。
  • operator delete应该在收到null时不做任何事,也应该能处理更大内存的错误申请。

Item52:Write placement delete if you write placement new.

定位表达式new(p) A(…);通过调用placement new

void *operator new(size_t,void*)throw();

来实现在指定内存上构造对象。

  • placement delete只有在“伴随placement new调用而触发的构造函数”出现异常时才会被调用。
  • 当写了一个placement operator new时,一定要确保写了对应参数版本的placement operator delete,否则可能会引发内存泄漏。

Item53:Pay attention to compiler warnings.

Item54:Familiarize yourself with the standard library,including TR1.

Item55:Familiarize yourself with Boost.

0 0