在MFC项目中,我使用的是一个外部库TTL,即过载 operator new
。我的问题是内存泄漏,我想利用DEBUG_NEW
提供的诊断信息。但是,我只能用DEBUG_NEW
注释来编译它,否则我会得到下面的错误。
以下说明了这一点。当Visual项目作为控制台应用程序使用made 时,它是一个MCVE。
// The problem is when this is uncommented
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
struct HandleId
{
HandleId() {}
void* operator new (size_t t) {
return HandleId::operator new(t, 0, 0, 0);
};
void* operator new (size_t t, int, const char* file, int line) {
HandleId* tmp = (HandleId*)calloc(1, t);
return tmp;
};
void operator delete (void* v) {
free(v);
}
};
namespace hed
{
struct Node : public virtual HandleId
{
Node() {};
Node(double x, double y, double z = 0.0) {}
};
}
struct DtmNode : public hed::Node
{
DtmNode() {};
DtmNode(short pntRef, double x, double y, double z)
: hed::Node(x, y, z)
{};
};
int main()
{
DtmNode* pNode = new DtmNode(0, 1.0, 2.0, 3.0);
return 0;
}
使用DEBUG_NEW
取消注释,上面的编译将失败(VS2019)。
错误C2661:
HandleId::operator new
:没有重载函数有3个参数
到目前为止,我已经经受住了宏的评论。但我现在确实希望在调试构建中使用它,原因很明显是在调试过程中帮助捕获内存泄漏。DtmNode
是我可以改变的班级。HandleId
和hed
命名空间属于库。
我的问题是:
DEBUG_NEW
未注释的方式编译它?DtmNode
在_DEBUG模式下不要使用重载的operator new
,以便按照“正常”方式使用DEBUG_NEW
?发布于 2020-03-10 15:37:43
你第一个问题的答案是“不”。
您可以通过选择性地取消使用#语用推送宏/pop_宏定义新的内容来编译这类内容:
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
...
int main()
{
#pragma push_macro("new")
#undef new
DtmNode* pNode = new DtmNode(0, 1.0, 2.0, 3.0);
#pragma pop_macro("new");
return 0;
}
它不允许您使用MFC的调试分配器从库中跟踪对象(为此您必须完全替换库的分配器)。但是它至少会允许你的程序在一个不匹配的操作符出现的情况下工作。
https://stackoverflow.com/questions/60620263
复制相似问题