Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should "delete this" be called from within a member method?

Tags:

I was just reading this article and wanted SO folks advice:

Q: Should delete this; be called from within a member method?

like image 721
jldupont Avatar asked Dec 07 '09 18:12

jldupont


People also ask

Can you call delete this inside a member function?

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.

What will happen if I say delete this?

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.

When to use delete this?

"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.

Is delete this safe?

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".


2 Answers

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;
  }
}
like image 154
dmazzoni Avatar answered Sep 18 '22 15:09

dmazzoni


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.

like image 39
JaredPar Avatar answered Sep 18 '22 15:09

JaredPar