operator new 和 operator delete只适合用来分配单一对象。Array所用的内存由operator new[] 分配出来,并由operator delete[] 归还。STL容器所使用的heap内存是由容器所拥有的分配器对象管理,不是被new和delete直接管理。
49 Understand the behavior of the new-handler
set_new_handler
允许客户指定一个函数,在内存分配无法获得满足时被调用;Nothrow new
是一个颇为局限的工具,因为它只适用于内存分配,后继的构造函数调用还是可能抛出异常;
50 Understand when it makes sense to replace new and delete
- 可以根据需要写个自定的
new
和delete
;
51 Adhere to convention when writing new and delete
- 当写一个
placement operator new
,请确定也写出相应的placement operator delete
.如果没有那样做,程序可能会发生隐微而时断时续的内存泄露; operator new
应该内含一个无穷循环,并在其中尝试分配内存,如果它无法满足内存需求,就应该调用new-handler
。它也应该有能力处理0 bytes
申请。class
专属版本则还应该处理“比正确大小更大的(错误)申请”;operator delete
应该在收到null
指针时不做任何事。class
专属版本则还应该处理“比正确大小更大的(错误)申请”;
52 Write placement delete if you write palcement new
- 当写一个
placement operator new
时,也要写对应版本的placement operator delete
。否则就可能造成隐蔽的内存泄露; - 应当避免
class
专属的new
掩盖客户期望的其他new
,如通用版本的new
或其基类中的new
,方法是在适当的作用域中使用using
声明式;