开发者

delete this ? what does it do?

开发者 https://www.devze.com 2023-03-31 19:59 出处:网络
Given the following : #include <iostream> using namespace std; class A { public: void func() {delete this;}

Given the following :

#include <iostream>
using namespace std;

class A
{
public:
    void func() {delete this;}
    A() : x(5) {cout << "ctor A" << endl;}
    ~A() {cout << "dtor A" << endl;}
    int x;
};

int main() {
    A a;
    cout << "The X value: " << a.x << endl;
    a.func();  // calling 'delete this' ->going to the dtor #1
    cout << "The X value: " << a.x << endl;
    return 0;  
}

the output is :

ctor A
The X value: 5
dtor A
The X valu开发者_Python百科e: 5
dtor A

Does delete this; has any drastic repercussions?


In this case (you did not allocate the A object via new) you are invoking undefined behaviour. Undefined behaviour is usually a very very bad thing. Basically, anything can happen.

It is possible to write code where a "delete this;" would be fine, though. But I can't recall ever doing this. Try to avoid it. Try avoiding to call delete manually altogether (whether you used new or not) by delegating this responsibility to some other object (for example, a smart pointer).


The delete operator call the destructor of the object then release the underlying memory used by the object. The memory must have been allocated by the new operator. In delete this, the object deleted is just the current object. There is nothing special about the construction, it is just plain C++.

In your exemple, the memory is from the stack, and thus your enter the realm of undefined behavior (since you're calling the delete operator on an object that was not allocated via the new operator).

It is generally considered bad design to call delete this because an object should not be responsible of its own lifetime. It is generally considered best practice to have the creator of an object responsible of its destruction.

However, there is one situation where I personally find it really useful. This happens when you have thread communicating by sending messages. In this case, if the message is responsible of its own lifetime it is actually safer and easier to write than having the original thread responsible for it.


I'll look past that you're calling delete on a stack-allocated object, and examine the usage of delete this in general.

There is a school of thought that says "It's not a good idea". However, I have seen it used a number of times with implementations of reference counted objects.

In COM, the framework requires that all objects would be created by a factory method, and then released again by a call to "Release".

  class MyRefCountedObject : public IUnknown
  {
      private:
           // Making the constructor and destructor private
           // so that the object can only be allocated as a pointer

           MyRefCountedObject() {}

           ~MyRefCountedObject() {}

           MyRefCountedObject(const MyRefCountedObject& mrco) {}

            int _refCount;
      public:
           static MyRefCountedObject* CreateInstance()
           {
                MyRefCountedObject* pObject = new MyRefCountedObject();
                pObject->_refCount = 1;
                return pObject;
           }

           void Release()
           {
                if(--_refCount == 0)
                {
                    delete this;
                }
           };
           void AddRef()
           {
               ++_refCount;
           }
  }

Note - that is not a complete implementation, just giving an idea of the logic. But, by making the constructor private, I can ensure that this would only ever be allocated on the heap.


C++ FAQ Lite: "Is it legal (and moral) for a member function to say 'delete this'?"

That said, you should rarely if ever have a use for this in properly organized code.


You should not do this. It is bad programming practice. The object that uses new should be the object that uses delete. Otherwise you get into a mess and end up with memory leaks etc.

0

精彩评论

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

关注公众号