delete overload, recursive overflow

自闭症网瘾萝莉.ら 提交于 2019-12-11 07:48:06

问题


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).

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;
}

回答1:


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.

In the general case an overloaded operator delete must match the operator new. In your case:

B *p = new D;

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;
    }
};



回答2:


You should not be overriding delete. Especially not to a function that ends up calling delete. Any memory freeing that you need to do (and you don't need to do any in this example) should be done in a destructor.




回答3:


You are probably better off just having a Destroy() method that your clients are expected to call... this will protect your lib from differences in the heap.



来源:https://stackoverflow.com/questions/443009/delete-overload-recursive-overflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!