覆盖“新”和记录有关调用者的数据 [英] Overriding "new" and Logging data about the caller

查看:106
本文介绍了覆盖“新”和记录有关调用者的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个内存分析器,迄今为止已经能够得到我的自定义函数工作malloc,自由,新的和删除。
我尝试使用 __ FILE __ __ LINE __ 在重载的新方法中记录创建者, )它只是给出了重载函数的位置的细节。
有一种方法可以获得发件人的详细信息到重载的函数,而不对被测试的组件的现有代码做任何更改(如#define for malloc)?

I'm trying to write a memory profiler and so far have been able to get my custom functions to work for malloc, free, new and delete. I tried using __FILE__ and __LINE__ to log the originator inside the overloaded new method, but (as expected) it just gives the details of where the overloaded function is. Is there a way to get the details about the originator to the overloaded functions without doing any changes to existing code of the component being tested (like #define for malloc)?

我使用的函数是:

void* operator new (size_t size)
{
    if(b_MemProfStarted)
    {
    	b_MemProfStarted = false;
    	o_MemLogFile << "NEW: " << "| Caller: "<< __FILE__ << ":"
    			<< __LINE__ << endl;
    	b_MemProfStarted = true;
    }

    void *p=malloc(size);
    if (p==0) // did malloc succeed?
    throw std::bad_alloc(); // ANSI/ISO compliant behavior

    return p;
}

bool b_MemProfStarted用于避免onstream和map.insert的递归调用。

The bool b_MemProfStarted is used to avoid recursive calls on ofstream and map.insert.

推荐答案

您可以写

new(foo, bar) MyClass;

在这种情况下,调用以下函数

In this case the following function is called

void*operator new(std::size_t, Foo, Bar){
    ...
}

您现在可以拨打

new(__LINE__, __FILE__) MyClass;

并使用

void*operator new(std::size_t, unsigned line, const char*file){
    ...
}

添加宏

#define new new(__LINE__, __FILE__)

将捕获大多数调用而不需要更改源代码。

to the code being monitored will catch most invocations without needing source code changes.

这不完美,你可以直接调用操作符new。在这种情况下,预处理器会把你的代码变成垃圾。我知道没有更好的方法。

It's not perfect as you could call the operator new directly for example. In that case the preprocessor will turn your code into garbage. I know of no better way though.

这篇关于覆盖“新”和记录有关调用者的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆