3

我正在尝试追踪内存泄漏,并认为为此创建一个简单的设备会很好,所以我做了这个。

struct alloc_t
{ 
};
extern alloc_t g_Alloc;

inline 
void* operator new (size_t size, alloc_t, const char* file, int line)
{
    return _malloc_dbg(size, _NORMAL_BLOCK, file, line);
}

然后我使用一个宏来扩展这个特定的重载,如下所示:

#define DEBUG_NEW new (g_Alloc, __FILE__, __LINE__)

虽然,我必须在g_Alloc某个地方定义,但我认为有更好的方法来确保重载解决方案是可悲的,但不使用struct. 但是,我注意到在不与or混淆的情况下,enum或将在多大程度上就足够了?typedefvoid*int

此外,任何人都可以从经验中说出这种g_Alloc情况是否会影响如此严重的问题,或者编译器是否只是在完成重载决议后将其删除?

4

1 回答 1

0

With the help of @ipc's comment I made this adjustment, it's fundamentally the same but with a const qualifier and pass-by-reference. This is also identical to the trick used by the new overload by nothrow that allow you to not get exceptions when allocations fail in C++ (this I did not know about).

struct alloc_t
{ 
};
extern const alloc_t g_Alloc;

inline 
void* operator new (size_t size, const alloc_t&, const char* file, int line)
{
    return _malloc_dbg(size, _NORMAL_BLOCK, file, line);
}
于 2013-01-09T12:24:08.020 回答