2

I've overridden the global new and delete operators for my project, but I'm having trouble making it all work with the Boost libraries. I've implemented the solution here: Macro to replace C++ operator new to get around the problem that I was having with multiple overloads. However, the Boost libraries have an annoying habit of using operator new rather than simply using new leaving the preprocessor to expand:

::operator new(n);

to:

::operator (__file__ = "someFile.cpp", __line__ = 123) && 0 ? NULL : new(n);

Is it possible to write another macro to remove these "undesired" expansions? For example, I tried writing:

#define (operator (file, line) && 0 ? NULL :) operator new

But apparently parenthesis are not allowed in the identifier portion of the macro. How can I use the Boost libraries, but still get my memory allocation tracking?

Community
  • 1
  • 1
Wagan8r
  • 468
  • 5
  • 18
  • I think modifying Boost might be a heck of a lot easier than dealing with this mess. It's open-source and header-only, after all. – user541686 Aug 21 '12 at 03:28
  • @Mehrdad What about upgrades? – curiousguy Aug 21 '12 at 03:32
  • @curiousguy: Just re-apply your changes after the upgrade... it's not that hard. A diff/patch or a regex might do (not sure if a regex will work, but worth a try). – user541686 Aug 21 '12 at 03:35
  • @Mehrdad Yes, but... it seems risky. I would only do that if it was absolutely needed. (F.ex. to correct a bug in some library.) – curiousguy Aug 21 '12 at 03:38
  • The "annoying habit" is because `operator new` has different behaviour to a new-expression, and sometimes, especially in low-level library code, that's the behaviour you need. You'll find the same "habit" in the Standard Library implementation, since allocators use `operator new` to allocate raw memory. – Mike Seymour Aug 21 '12 at 10:10

1 Answers1

1

A good answer depends on what you need this for, but apparently it's to reduce the time spent on debugging (by having information about which blocks were allocated where).

Then, first of all, the best general way to reduce the time spent on debugging allocations and deallocations, is to use smart pointers such as std::shared_ptr. Let smart pointers manage your deallocations automatically and correctly. That can really reduce time spent on debugging.

That said, one way to get the info you want is to be explicit about it. In your code, write e.g. TRACKING_NEW instead of just new, in new-expressions. Then define TRACKING_NEW accordingly.

Don’t define a macro called new.

Apart from the formal problem (you have UB if you include any standard header after that), it is almost guaranteed to trap you. So, do define e.g. TRACKING_NEW if you find that it is still desirable after changing the code to use smart pointers. But don’t define a macro called new.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331