Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of "delete this"?

Today, I have seen some legacy code. In the destructor there is a statement like "delete this". I think, this call will be recursive. Why it is working?

I made some quick search on Y!, I found that if there is a need to restrict the user to create the stack object, we can make destructor private and provide an interface to delete the instance. In the interface provided, we have to call delete on this pointer.

Are there any other situations for using such statements?

like image 248
Vinay Avatar asked Jan 15 '09 16:01

Vinay


People also ask

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.

Can we call delete this?

Can you delete this pointer inside a class member function in C++? 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.

What is delete used for in C?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

In which case will using a delete this in destructor goes wrong?

No you should not delete this from the destructor. The destructor gets called because of a delete statement (or goes out of scope) and this would most likely lead to some sort of crash.


1 Answers

"delete this" is commonly used for ref counted objects. For a ref counted object the decision of when to delete is usually placed on the object itself. Here is an example of what a Release method would look like [1].

int MyRefCountedObject::Release() {   _refCount--;   if ( 0 == _refCount ) {     delete this;     return 0;   }   return _refCount; } 

ATL COM objects are a prime example of this pattern.

[1] Yes I realize this is not thread safe.

like image 140
JaredPar Avatar answered Sep 22 '22 04:09

JaredPar