Operator new and delete overloading scope

后端 未结 1 1920
暗喜
暗喜 2021-01-14 16:20

I stumbled over some questions about linkage and overloading of operator new and delete.

How far does an global overload of operator new/delete take effect

相关标签:
1条回答
  • 2021-01-14 17:16

    The global allocation and deallocation functions are for the whole application, not per translation unit. Since they're global there can't be multiple definitions, except to the degree that you consider new, new[] and the infinite number of possible placement new to be "multiple definitions". In particular there is, unfortunately, no portable way to call the original global allocation function when you define your own.

    You can however define class-specific allocation and deallocation functions.

    If you want to avoid picking up a class-specific allocation function in a new-expression you can use a :: prefix, i.e. writing ::new T, and that's a good idea for calling the standard library's placement new.


    Regarding "What about dynamic linkage?" it's unclear what you mean. C++ has static linkage, external linkage and no linkage, but not dynamic linkage. Possibly you're referring to dynamic libraries (like Windows DLLs), and that's a pretty thorny issue. The C++ standard has no direct support for dynamic libraries. One way to be safe in practice is to not provide your own global allocation/deallocation, and to link everything dynamically (in Windows this means using dynamically linked runtime library).

    0 讨论(0)
提交回复
热议问题