开发者

Deleting self object inside class [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C++: Delete this?

In C++, is it 开发者_C百科ok to delete the self object in function definition. What are side effects of this?

class MyClass {

public:
    void ~myClass() {}
    void myFunction() { 
        // logic here
        delete this;
    }
}

Thanks!


From parashift FAQ:

Is it legal (and moral) for a member function to say delete this?

As long as you're careful, it's OK for an object to commit suicide (delete this).

Here's how I define "careful":

  • You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).

  • You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.

  • You must be absolutely 100% positively sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).

Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.


You may delete an object from within itself, but it is necessary that you do not, afterward, access any member variables or functions of that class instance after doing so.


It's pretty dangerous. Consider this:

void foo() {
   MyClass bar;
   bar.myFunction(); // calls delete
}  // bar goes out of scope, calls delete again

Check out this C++FAQ 16.15 entry for when doing delete this is possible - it's legal, just needs to be used bery carefully.


The side effects of that are that the object is no longer valid, nor are pointers or references to that object.

I've seen this pattern a lot of places. Typically it's used in a reference counting sort of situation, when the last reference to the object goes away the object deletes itself. It's also typically paired with a factory function of some sort, e.g. a static class member function named Create, taking no parameters, and returning a pointer to the class. The body of this function does the corresponding new, and your constructor can even be private (that way people don't create the object in a way that will mess up your cleanup code).


Depends on your definition of ok!

You can do this, if you are careful, but you shouldn't do it without very good reason, because no-one will be expecting it, and because there is no guarantee that the object has been allocated with new.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜