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 )
deletethis;
}
};
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.
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.
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.
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.