views:

150

answers:

4

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  A: 

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.

Paul Tomblin
A: 

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.

Jesse Pepper
+1  A: 

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;
    }
};
fbonnet
the cleanup routine is mostly in the dtor, i would like to delete the object with normal delete and allocate it with the normal new. How do i do this w/o a recursion problem?
acidzombie24
A: 

try doing a recursive monongahela back-test, dat should cure ur biopsy

DJ Nubbins