Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if you delete this in C++ [duplicate]

Possible Duplicate:
Is it OK to use “delete this” to delete the current object?

I just saw some code where they have done delete this; in a class function, I know that this is not a good design but is it defined what will happen, lets say that the class always is a pointer from somewhere. Will it always be deleted in the correct way?

class A
{
 public:
    void abort() { delete this; }
};

class B
{
    void func() { A* a = new A; a->abort(); }
};
like image 882
hidayat Avatar asked Nov 29 '10 16:11

hidayat


2 Answers

It is perfectly legal in C++ to delete this and is actually very useful for certain patterns like smart pointers. The burden is on the developer though to make sure that no other methods are called or on the stack for this which will access instance data after the delete occurs.

The C++ FAQ Lite has an entry for this which is worth reading

  • https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
like image 107
JaredPar Avatar answered Sep 30 '22 02:09

JaredPar


It is not the case that delete this; is bad design, and it definitely does not result in undefined behaviour. It does what you would expect -- it deletes this object. That means you had better make really sure that you don't do anything else with the object after delete this has been called.

The Microsoft MFC classes use delete this; extensively, for instance in the CWnd (window) class. When a window receives the WM_DESTROY message, the window wrapper class (which is what the C++ object is) is no longer needed, so it calls delete this; (I think in PostNcDestroy(), somewhere like that). It's very neat from the point of view of the user of the framework: you just need to remember that there are ways for the C++ object to get deleted automatically and be a little careful near the end of the window's lifetime.

I am sure there are many other real-world examples where delete this; is a useful paradigm.

like image 22
AAT Avatar answered Sep 30 '22 01:09

AAT