07 June, 2013

Tricky macro to add file name and line number in C++ operator new

Header file:

#if defined(_DEBUG)

  #include <crtdbg.h>

  extern __declspec(thread) char const * t_File;
  extern __declspec(thread) int t_Line;

  inline void * __CRTDECL operator new  (size_t const size) { return ::operator new  (size, _NORMAL_BLOCK, t_File, t_Line); }
  inline void * __CRTDECL operator new[](size_t const size) { return ::operator new[](size, _NORMAL_BLOCK, t_File, t_Line); }

  #define new (t_File = __FILE__, t_Line = __LINE__, false) ? nullptr : new
Source file:
#if defined(_DEBUG)
  __declspec(thread) char const * t_File = "???";
  __declspec(thread) int t_Line = 0;

This macro doesn't work with direct operator call like operator new(...) in code.

P.S. This macro tested only on Visual Studio 2012

1 comment:

Unknown said...

This code doesn't work under Windows XP and Windows Server 2003 (http://msdn2.microsoft.com/en-us/library/ms684175.aspx). Please use TlsAlloc/TlsSetValue/TlsGetValue instead of __declspec(thread)!