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:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes