Is ‘delete this;’ a good idea?

Is ‘delete this;’ a good idea?

We have a use counted object with addRef() and removeRef() functions. When the reference count gets to 0, we want the object to be deleted. Is { delete this; return; } safe?

Well, I guess my best answer is that it depends.

Deleting an instance of a class that is executing is certainly dangerous. Any further attempt to access class members would be accessing freed memory.

If you can be sure that the code just returns and that no additional members are called, then you should be able to escape any trouble. But you must be very careful. For starters, what if another developer comes along to work on this class? You could have trouble if they didn’t realize what you’ve done. Also, I would review your destructor for possible conflicts. You might trace through the code to verify the compiler isn’t calling any “hidden” code that could be affected, too.

In summary, I would avoid this approach for the maintanence problems alone, but I don’t see any reason it wouldn’t work.


Share the Post: