What are the reasons to override new and delete operator for a specific class?

The dynamic memory allocation operators - new and delete can be overridden for a specific class. I could define a different memory allocation scheme than the default that is provided by the C++ Run-time on windows. I have few questions related to it:

  • Is overriding new and delete operator for a specific class portable such that it also works on unix? Is it part of the C++ standard?

  • What are the cases that might require you to override memory allocation operators for a specific class? Only case that I could think of is - tracking memory allocations for leaks.


  • Yes, it is portable, but beware that MS compilers handle the 'nothrow' part of it different than the ANSI standard - got burned on that.

    As to why, yes track memory, tracking leaks, tracking allocations are all nice, but those can be done globally. You could overrride new/delete for something like VRAM allocations, but I usually see that sort of thing called out in different functions. The biggest reason to override new/delete is if you have a better understanding of how your memory system is going to be used, and can tailor your functions more efficiently than the nice, but generic versions of new/delete supplied by your vendor. Small object allocation comes to mind as something that is quite often overlooked or poorly implemented, along with just how much info you want to pass around with allocations for debug purposes.


    If you need to automatically use a different memory, for example a memory pool or a shared memory.

    And... many other reasons: Why would one replace default new and delete operators?


    If you want to align the addressees in an unusual way. for example some times ago i addressees to 8 and use last three bits for other goals

    if you want to locate new class instances in pre-initialized memory. For example if you want to add new node in the list from the list of empty nodes.

    链接地址: http://www.djcxy.com/p/73040.html

    上一篇: 为什么我们应该重载/覆盖新的和删除?

    下一篇: 覆盖特定类的新操作符和删除操作符的原因是什么?