zoukankan      html  css  js  c++  java
  • [Effective C++]定制new和delete

    本篇的两个主角是分配例程和归还例程(allocation and deallocation routines,也就是operator new和operator delete),配角是new_handler,这是当operator new无法满足客户的内存需求时所调用的函数。

    STL容器所使用的heap内存是由容器所拥有的分配器对象(allocator objects)管理,不是被new和delete直接管理。

    条款49:了解new-handler的行为(Understand the behavior of the new-handler.)

    请记住:

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

    2)Nothrow new是一个颇为局限的工具,因为它只适用于内存分配;后继的构造函数调用还是可能抛出异常。

    条款50:了解new和delete的合理替换时机(Understand when it makes sense to repace new and delete.)

    请记住:有很多理由需要写个自定的new和delete,包括改善效能、对heap运用错误进行调试、收集heap使用信息。

    条款51:编写new和delete时需固守常规(Adhere to convention when writing new and delete.)

    请记住:

    1)operator new应该包含一个无穷循环,并在其中尝试分配内存,如果它无法满足内存需求,就该调用new-handler。它也应该有能力处理0 bytes申请。Class专属版本则还应该处理“比正确大小更大的(错误)申请”。

    2)operater delete应该在收到null指针时不做任何事。Class专属版本则还应该处理“比正确大小更大的(错误)申请”。

    条款52:写了placement new也要写placement delete(Write placement delete if you write placement new.)

    请记住:

    1)当你写一个placement operator new,请确定也写出了对应的placement operator delete。如果没有这样做,你的程序可能会发生隐微而时断时续的内存泄露。

    2)当你声明placement new和placement delete,请确定不要无意识地遮掩了它们的正常版本。

  • 相关阅读:
    《代码整洁之道》读书笔记六
    第九周总结
    《构建之法》读后感(五)
    学习进度条-第十二周
    3. 统计数字
    《构建之法》读后感(四)
    学习进度条-第十一周
    4. 丑数 II
    《构建之法》读后感(三)
    学习进度条-第十周
  • 原文地址:https://www.cnblogs.com/kona/p/4660020.html
Copyright © 2011-2022 走看看