4

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. Per translation unit
  2. Per linked application with at least one object file overloading these operators

What about dynamic linkage?

Can there be multiple definitions of these operators? If which one is taken.

user877329
  • 6,717
  • 8
  • 46
  • 88

1 Answers1

4

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).

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • @cheers-and-hth-alf: if a library is dynamically loaded at runtime, it is not possible to override global `new` only for the objects present in this library. Did I get this right? Because I need to redefine `new` in a plugin library for debugging purposes, which then seems to be impossible. – MKroehnert Sep 01 '14 at 15:13
  • @MKroehnert: A Windows DLL is much like an executable (it's the same file format, a Portable Executable). So the DLL code is unaffected by any overriding you do in the client code. However, if you have some control over the DLL interface then you can make it accept an allocator object to use, or if you have the source code then you can recompile it, with an override. – Cheers and hth. - Alf Sep 01 '14 at 15:33
  • @cheers-and-hth-alf: in my case I have to deal with a `.so` file on Linux. The problem is that an override of `new` in this library does not seem to be used at all, although it is defined and compiled with the code. – MKroehnert Sep 01 '14 at 15:36