重载新/删除 [英] overloading new/delete
问题描述
我在我的程序中创建一个小的内存泄漏查找程序,但
我的方式重载新和删除(以及新的[]和删除[])
似乎没有做任何事情。
I'm making a little memory leak finder in my program, but my way of overloading new and delete (and also new[] and delete[]) doesn't seem to do anything.
void* operator new (unsigned int size, const char* filename, int line)
{
void* ptr = new void[size];
memleakfinder.AddTrack(ptr,size,filename,line);
return ptr;
}
我重载的方式 new
显示在上面的代码段中。我想这是运算符返回void *的东西,但我不知道该怎么做。
The way i overloaded new
is shown in the code snippet above. I guess it's something with the operator returning void* but i do not know what to do about it.
推荐答案
void* ptr = new void[size];
不能这样做。修复它。
从不尝试全局重载新的/删除。可以将它们放在基类中,并从此类派生所有对象,或者使用命名空间或模板分配器参数。为什么,你可能会问。因为如果你的程序不止一个文件,并使用STL或其他库,你会拧紧。
Never ever try to overload new/delete globally. Either have them in a base class and derive all your objects from this class or use a namespace or a template allocator parameter. Why, you may ask. Because in case your program is more than a single file and using STL or other libraries you are going to screw up.
这是一个精简版的来自VS2005的新
运算符 new.cpp
:
Here's a distilled version of new
operator from VS2005 new.cpp
:
void * operator new(size_t size) _THROW1(_STD bad_alloc)
{ // try to allocate size bytes
void *p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{ // report no memory
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
这篇关于重载新/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!