I was just reading this article and wanted SO folks advice:
Q: Should delete this;
be called from within a member method?
Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword. As, delete can only be applied on the object that has been created by using “new” keyword only.
Using delete this; is fine. Doing it in the constructor as well as accessing fields of the objects after it is undefined behavior. Sadly this doesn't typically cause a processor fault, just heap corruption.
"delete this" in C++? Delete is an operator that is used to Deallocate storage space of Variable. This pointer is a kind of pointer that can be accessed but only inside nonstatic member function and it points to the address of the object which has called the member function.
It's safe to delete "this" as long as it's essentially the last operation in the method. In fact several professional level APIs do so (see ATL's CComObject implementation for an example). The only danger is attempting to access any other member data after calling "delete this".
Normally this is a bad idea, but it's occasionally useful.
It's perfectly safe as long as you don't use any member variables after you delete, and as long as clients calling this method understand it may delete the object.
A good example of when this is useful is if your class employs reference counting:
void Ref() {
m_References++;
}
void Deref() {
m_References--;
if (m_References == 0) {
delete this;
}
}
I think there are really 2 questions here
Can delete this be validly called from a member method?
Yes. This is legal as long as you are very careful with the usage.
Should delete this be used within a member method?
In very specific cases this is necessary. Certain types of smart pointers for instance use the delete this
pattern to kill the pointer. Examples: CComPtr<>
style.
Other than smart pointers though, it should be avoided unless you have a very good reason for doing this. Even then, I would carefully reconsider my scenario and see if there was a way around it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With