在为我自己的内存管理器尝试一些内存跟踪和准备时,我尝试覆盖新的运算符。关于 Flipcode 的文章是我在此过程中的主要指导方针 ( http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml )。
在实现了该文章中描述的技术之后,我遇到的问题是,在 STL 中的某个地方,“crtdbg.h”被直接或间接地通过一些被包含的头文件包含(使用 Visual Studio 2010) .
这会导致错误:
[...]10.0\vc\include\crtdbg.h(1078): error C2365: 'operator new' : redefinition; previous definition was 'function'
[...]10.0\vc\include\crtdbg.h(1078): error C2078: too many initializers
[...]
通过放置“_CrtDumpMemoryLeaks()”而不包括头文件来进行快速检查,这证实了我怀疑头文件确实包含在 STL 文件中。
// The header files that should be included for using the CrtDumpMemoryLeaks:
//#define _CRTDBG_MAP_ALLOC
//#include <stdlib.h>
//#include <crtdbg.h>
//...
_CrtDumpMemoryLeaks()
撇开实现我自己的新/删除是一个好主意不谈,我想知道如何在仍然使用一些标准库功能并且没有这些重新定义错误的情况下拥有自己的新/删除实现。
代码如下所示:
内存调试.h
#ifndef _MEM_DEBUG_H
#define _MEM_DEBUG_H
#ifdef _DEBUG
void * operator new( unsigned int size, const char *filename, int line );
void operator delete( void *ptr );
#define DEBUG_NEW new(__FILE__, __LINE__)
#define new DEBUG_NEW
#endif
#endif
内存调试.c
#ifdef _DEBUG
void * operator new( unsigned int size, const char *filename, int line )
{
void *ptr = (void *)malloc(size);
//AddTrack((DWORD)ptr, size, filename, line);
return(ptr);
};
void operator delete( void *ptr )
{
//RemoveTrack( (DWORD)ptr );
free( ptr );
}
#endif
主文件
#include "memdebug.h"
#include <iostream>
void main()
{
Test *pTest = new Test();
std::cout << "end" << std::endl;
}
我解决它的方法是移动#define new DEBUG_NEW
下面的<iostream>
; 问题已解决,因为它不会重写crtdbg.h
; 但是,这确实使必须确保始终在包含该crtdbg.h
文件的可能标头之后执行此操作变得很麻烦。
我相信这只能通过为新操作员使用自定义名称并改用该名称来解决。我对么?