Delete this in C + +

Source: Internet
Author: User

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

As long as you ' re careful, it's okay (not evil) for a object to commit suicide ( delete this ).

Here's how I define "careful":

  1. You must is absolutely 100% positively sure this that object is allocated via new (not new[] by, nor by placement , nor a local object on the stack, nor a namespace-scope/global, nor a member of another object; But by plain ordinary new ).
  2. You must is absolutely 100% positively sure that your member function would be the last member function invoked on this OB Ject.
  3. You must is absolutely 100% positively sure that the rest of your member function (after the line delete this ) doesn ' t tou Ch any piece of the this object (including calling any and member functions or touching any data members). This includes code that would run in destructors for any objects allocated on the stack that is still alive.
  4. You must is absolutely 100% positively sure that is no one even touches the pointer itself after the line this delete this . In other words, your must not examine it, compare it with another pointer, compare it with nullptr , print it, cast it, does any thing with it.

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

If you call delete this in a destructor, you are stuck in a dead loop:

classtdel{ Public: TDel () {x=1; }    Virtual~TDel () {printf ("This is dstr\n"); printf ("Delete this now\n"); Delete  This; }Private:    intx;};intMain () {TDel*TD =NewTDel; DeleteTD;}

The results are as follows:

This isDstrDelete  ThisNowThis isDstrDelete  ThisNowThis isDstrDelete  ThisNowThis isDstrDelete  ThisNowThis isDstrDelete  This Now ...

Https://isocpp.org/wiki/faq/freestore-mgmt#delete-this

Delete this in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.