Is it possible to create macros to replace all forms of operator new
with overloads that include additional args...say __FILE__
and __LINE__
?
The trouble appears to be that operator new
can either be coded with or without parentheses, therefore:
object-like macros:
#define new new(__FILE__, __LINE__)
will replace declarations like:
A* a = new A();
and function-like macros:
#define new(A) new (A, __FILE__, __LINE__)
will replace declarations like:
A* a = new(std::nothrow) A();
Unfortunately it's an error to attempt to declare two macros with the same identifier, even if they are of different types, so the following fails:
#define new new(__FILE__, __LINE__)
#define new(A) new (A, __FILE__, __LINE__) // Error: "new" already defined
Since I'm using g++ I was hopeful that employing their syntax of variadic macros would yield success, but unfortunately not. The following:
#define new(...) new(__FILE__, __LINE__, ## __VA_ARGS__)
only matches new(xyx) A()
, not new A()
.
I know that essays have been written about why it is impossible, but I feel like I'm so close that there must be a way. Is there anything obvious that I'm missing?