开发者

C++, workaround for macro using 'this' in static member functions

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开发者_Python百科 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...


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜