title: Macro to replace C++ operator new
body: <p>Is it possible to create macros to replace all forms of <code>operator new</code> with overloads that include additional args...say <code>__FILE__</code> and <code>__LINE__</code>?</p>
  
  <p>The trouble appears to be that <code>operator new</code> can either be coded with or without parentheses, therefore:</p>
  
  <ul>
  <li><p><em>object-like</em> macros:</p>
  
  <pre><code>#define new new(__FILE__, __LINE__)
  </code></pre>
  
  <p>will replace declarations like:</p>
  
  <pre><code>A* a = new A();
  </code></pre></li>
  <li><p>and <em>function-like</em> macros:</p>
  
  <pre><code>#define new(A) new (A, __FILE__, __LINE__)
  </code></pre>
  
  <p>will replace declarations like:</p>
  
  <pre><code>A* a = new(std::nothrow) A();
  </code></pre></li>
  </ul>
  
  <p>Unfortunately it's an error to attempt to declare two macros with the same <em>identifier</em>, even if they are of different <em>types</em>, so the following fails:</p>
  
  <pre><code>#define new new(__FILE__, __LINE__)
  #define new(A) new (A, __FILE__, __LINE__) // Error: "new" already defined
  </code></pre>
  
  <p>Since I'm using g++ I was hopeful that employing their syntax of <a href="https://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gcc/variadic-macros.html" rel="noreferrer">variadic macros</a> would yield success, but unfortunately not. The following:</p>
  
  <pre><code>#define new(...) new(__FILE__, __LINE__, ## __VA_ARGS__)
  </code></pre>
  
  <p>only matches <code>new(xyx) A()</code>, not <code>new A()</code>.</p>
  
  <p>I know that <a href="http://web.archive.org/web/20090513070647/http://www.scs.cs.nyu.edu/~dm/c++-new.html" rel="noreferrer">essays have been written</a> 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?</p>