开发者

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

开发者 https://www.devze.com 2023-01-27 05:53 出处:网络
This question already has answer开发者_开发技巧s here: Closed 12 years ago. Possible Duplicate: Is it OK to use “delete this” to delete the current object?
This question already has answer开发者_开发技巧s here: Closed 12 years ago.

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(); }
};


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


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.


Yes. You only have to take care, that no instance variable (and no virtual method, I think) is used after the delete statement, since the this pointer will no longer be valid after the delete.


yes, it should be deleted normally.

There are a few occasions when this is useful, but extra care is needed to be certain that the object is never accessed after that.


In this particular case it's OK, but think what would happen if a is automatic variable:

void foo() {
    A a;
    a.abort(); // BOOM!
}


As it was pointed out by a commenter there's no undefined behavior if no other members are called after delete You'll be able to continue to the function if you do not access other members of the object.

0

精彩评论

暂无评论...
验证码 换一张
取 消