8.定制new和delete

Item49:了解new-handler的行为

Understand the behavior of the new-handler.

  • set_new_handler允许客户指定一个函数,在内存无法获得满足时调用。
  • operator new(size)重定义可以实现类自己的new操作

Item50:了解new和delete的合理替换时机

Understand when it makes sense to replace new and delete.
当需要改善效能,对heap运用错误进行调试,收集heap使用信息时。

Item51:编写new和delete时需固守常规

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 new仅是一种特例。

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

Item53:不要轻忽编译器的警告

Pay attention to compiler warnings.

Item54:让自己熟悉包括TR1在内的标准程序库

Familiarize yourself with the standard library,including TR1.

Item55:让自己熟悉Boost

Familiarize yourself with Boost.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值