Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
May 2, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date