删除重载,递归溢出 [英] delete overload, recursive overflow
问题描述
我写了一个快速测试.我想删除呼叫deleteMe,然后将其删除.这样做的目的是使我可以正常删除由lib分配的obj. (我不希望由于crt或w/e而导致任何崩溃).
Hey guys i wrote a quick test. I want delete to call deleteMe which will then delete itself. The purpose of this is so i can delete obj normally which are allocated by a lib. (i dont want any crashes due to crt or w/e).
与删除此我得到一个stackoverflow,没有它msvc说我泄漏了4个字节.当我不致电测试时,我泄漏0.如何删除不包含递归问题? -编辑- 使这一点更加清楚.我希望LIB调用delete(因此是deleteMe)而不是由于crt导致的程序
With delete this i get a stackoverflow, without it msvc says i leaked 4 bytes. When i dont call test i leak 0. How do i delete w/o a recursion problem? -edit- to make this more clear. I want the LIB to call delete (thus deleteMe) instead of the program due to crt
class B
{
public:
virtual void deleteMe()=0;
static void operator delete (void* p) { ((B*)p)->deleteMe(); }
};
class D : public B
{
public:
void deleteMe() {
delete this;
}
};
int test()
{
B *p = new D;
delete p;
return 0;
}
推荐答案
递归归因于deleteMe
调用delete
,后者又调用了B的operator delete
,后者又调用了deleteMe
.重载operator delete
是可以的(尽管通常也重载operator new
),尤其是在处理外来"对象(这很可能是您的情况)时,但是您又必须从自定义delete
中调用实际的清理例程.
The recursion is due to deleteMe
calling delete
, which calls B's operator delete
that calls deleteMe
again. It's OK to overload operator delete
(although you usually overload operator new
as well), especially when handling "foreign" objects which is likely your case, however you must in turn call the actual cleanup routine from within the custom delete
.
在一般情况下,重载的operator delete
必须与operator new
相匹配.就您而言:
In the general case an overloaded operator delete
must match the operator new
. In your case:
B *p = new D;
此处p
与全局new
一起分配,因此必须与全局delete
一起释放.所以:
Here p
is allocated with the global new
, so it must be freed with the global delete
. So:
class D : public B
{
public:
void deleteMe() {
::delete this;
}
};
这篇关于删除重载,递归溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!