devxlogo

Is ‘delete this;’ a good idea?

Is ‘delete this;’ a good idea?

Question:
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?

Answer:
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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist