Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to `delete this`? [duplicate]

In my initial basic tests it is perfectly safe to do so. However, it has struck me that attempting to manipulate this later in a function that deletes this could be a runtime error. Is this true, and is it normally safe to delete this? or are there only certain cases wherein it is safe?

like image 570
Cristián Romo Avatar asked Feb 15 '09 02:02

Cristián Romo


People also ask

Can I safely delete duplicate files?

1. Duplicates of media files. It is normally safe to delete duplicates of your personal pictures or films, but as before, ensure that you verify the file path and the files' content before you delete anything.

Which duplicate files should I delete?

As such, if you frequently copy-and-paste files on your computer to relocate them, you should always delete the copied files from their original folders. Now that you know how duplicate files show up uninvited on your computer, let's look at some common reasons you should delete them.

Should I delete duplicate files on my phone?

Ran Out of Space on your Android Again? If you're running out of storage space & thinking of uninstalling some of the apps you don't use often, think again. Simply delete the duplicates & you're good to go!

Is it safe to remove duplicate files found by CCleaner?

Is it safe to delete duplicate files in CCleaner? Yes, it is absolutely safe. Firstly, CCleaner is a simple and clean app to help users clean up their computers.


1 Answers

delete this is legal and does what you would expect: it calls your class's destructor and free the underlying memory. After delete this returns, your this pointer value does not change, so it is now a dangling pointer that should not be dereferenced. That includes implicit dereferencing using the class's member variables.

It is usually found in reference-counted classes that, when the ref-count is decremented to 0, the DecrementRefCount()/Release()/whatever member function calls delete this.

delete this is typically considered very bad form for many reasons. It is easy to accidentally access member variables after delete this. Caller code might not realize your object has self-destructed.

Also, delete this is a "code smell" that your code might not have a symmetric strategy for object ownership (who allocates and who deletes). An object could not have allocated itself with new, so calling delete this means that class A is allocating an object, but class B is later freeing it[self].

like image 119
Chris Peterson Avatar answered Sep 22 '22 13:09

Chris Peterson