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?
In my initial basic tests it is perfectly safe to do so. However, it
Share
delete thisis legal and does what you would expect: it calls your class’s destructor and free the underlying memory. Afterdelete thisreturns, yourthispointer 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 callsdelete this.delete thisis typically considered very bad form for many reasons. It is easy to accidentally access member variables afterdelete this. Caller code might not realize your object has self-destructed.Also,
delete thisis 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 withnew, so callingdelete thismeans that class A is allocating an object, but class B is later freeing it[self].