In debug build, MFC defines a preprocessor macro that expand the new and delete operators to the overloaded new and delete operators
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
this will effects two extra parameter for the new and delete operator in the debug build of the MFC application
see the declartion in afx.h
void* AFX_CDECL operator new(size_t nSize, LPCSTR lpszFileName, int nLine);
MFC use this information to report memory leaks.
in debug mode, DEBUG_NEW keeps the track of file name and line number for each object that allocates.
this information will be displayed when using the function CMemoryState::DumpAllObjectsSince()
Because of this expansion done by the preprocessor, it will affect the usage of new and delete operators.
if any non MFC classes used in this project, their new and delete operators is also expanded, this will make the issue in the overloading of new operator in MFC application
for resolving this issue, overload new and delete operators like the following, for the classes in an MFC application
class CFoo
{
public:
CFoo(void){}
virtual ~CFoo(void){}
// for release mode
void*operator new(size_t nSize);
void operator delete(void* p);
// for debug mode
void* operator new(size_t nSize, LPCSTR lpszFileName, int nLine);
void operator delete(void* p, LPCSTR lpszFileName, int nLine);
};
void* CFoo :: operator new(size_t nSize)
{
return malloc(nSize);
}
void CFoo :: operator delete(void* p)
{
free(static_cast(p));
}
void* CFoo :: operator new(size_t nSize, LPCSTR lpszFileName, int nLine)
{
return malloc(nSize);
}
void CFoo :: operator delete(void* p, LPCSTR lpszFileName, int nLine)
{
free(static_cast(p));
}
Cheers,
No comments:
Post a Comment