tags:

views:

100

answers:

2

I've overridden new so that I can track memory allocations. Additional parameters such as __FILE__, __LINE__, module name etc are added in the #define.

However I want to add the address of the calling object to the parameters so that I can backtrack up allocations when hunting down problems. The easiest way is to add 'this' to those additional parameters (which means the address of the caller is passed into my custom alloc stuff).

Unfortunately there's plenty of singletons in our code, which means a bunch of static member functions calling new. The compiler throws up the error C2671: '...' : static member functions do not have 'this' pointers

Is there a workaround where I can get the address of the object without using this, which would also realize it's in a static method and pass null say?

Or maybe is there a way that my #define new would recognize it's in a static method and switch to a different definition?

It's important that I don't affect the existing project code though - I don't want to force developers to use a custom method like staticnew just because it's in a static method - they should carry on using new like normal and this memory tracking stuff is all going on in the background...

+5  A: 

You definitely cannot determine if a #define macro is inside a static method or not. You even shouldn't be using #define new as it violates the standard (even though all compilers support it). Your macro will also cause trouble to those who want to overload operator new for their class.

Generally, I would suggest not using this kind of memory debugging. There are many mature memory debuggers that do a better work when debugging memory errors. The most famous one is Valgrind.

To give a simple answer to your question - there is no clean solution in the way you are approaching the problem.

dark_charlie
I think you're right. I'm just going to have to take a different approach, somehow...
Mush
A: 

Well, once you're going down the "hack" path, you could throw portability out the window and get close to the compiler.

You could put some inline assembler in your macro that called a function with a pointer to the string generated by __FUNCDNAME__, and if it looks like a member function get the this pointer in the assembler, and if not just use null.

janm