delete this

Apr 7, 2011 at 5:15pm
Is it safe to to "delete this" from within a member function? For example, one might want to implement the release() method of a reference counted object as so:

1
2
3
4
5
6
7
8
9
10
class Foo
{
    int count;
    
    void release()
    {
        if( --count )
            delete this;
    }
};


Would such a construct be safe? Provided, of course, that the delete call was the last line of code to execute in the method, and also provided that the caller ceased to use the object.
Apr 7, 2011 at 5:16pm
Yes, as long as you don't touch the object anywhere after that...but you would have to be sure that this was dynamically allocated.
Apr 7, 2011 at 8:42pm
It typically corresponds to objects created with a placement new. The actual memory where the object resides is managed seperately.
Apr 7, 2011 at 10:18pm
To elaborate on the previous posts, the following code would cause an error:
Foo bar;
while the following code wouldn't:
Foo* bar = new Foo;
Because you shoudn't deallocate memory from the stack.
Apr 8, 2011 at 12:09am
firedraco's comment was spot on. Generally, a class does not know if it has been allocated dynamically or on the stack or with placement new, thus "delete this;" opens you up to potential memory corruption issues.
Apr 8, 2011 at 2:08am
Perfect guys, thanks.

And yeah, I might have mentioned that what I'm doing is writing a wrapper for a C library which itself uses reference counted objects (which are always heap allocated in the C version of the library). So the C++ wrapper objects will implicitly need to be heap allocated as well.

Over and out,
-Patrick
Topic archived. No new replies allowed.