sharptooth
sharptooth

Reputation: 170489

To what extent is using "delete this" compliant to C++ standard?

When implementing reference counting in objects the "release and possibly delete object" primitive is usually implemented like this:

void CObject::Release()
{
    --referenceCount;
    if( referenceCount == 0 ) {
       delete this;
    }
}

First of all, delete this looks scary. But since the member function returns immediately and doesn't try to access any member variables the stuff still works allright. At least that's how it is explained usually. The member function might even call some global function to write to a log that it deleted the object.

Does the C++ standard guarantee that a member function can call delete this and then do anything that will not require access to member variables and calling member functions and this will be defined normal behaviour?

Upvotes: 3

Views: 445

Answers (3)

Alok Singhal
Alok Singhal

Reputation: 96151

See C++ FAQ.

I don't have a copy of the standard, but the best "reference" I could find with a google search is this.

To quote the above:

So now I'm wondering if there is anything in the C++ standard that guarantees that a "delete this;" won't crash the program when the function returns.

Nobody can give you such guarantee, because it can crash.

Not according to the standard. The standard is quite clear that the only problem is if the object is used after delete. And the standard also states pretty clearly (in §3.2/2) when an object is "used", and when it is not.

Upvotes: 6

RED SOFT ADAIR
RED SOFT ADAIR

Reputation: 12218

This problem has a number on implications, covered best in Item 27 (10 pages) of Scott Meyers book:

More Effective C++: 35 New Ways to Improve Your Programs and Designs

If you dont have this book, buy it as well as its predecessor

Effective C++: 55 Specific Ways to Improve Your Programs and Designs

They are no "how to" Programming learning books, but rather give clear and straight (and explained) advice what to do and what not to do.

EDIT:

Very briefly the item covers:

  • Item 27 Requiring or prohibiting heap-based objects-

Paragraphs are titled:

  • Requiring Heap-based-Objects
  • Determining wether an Object is on the Heap
  • Prohibiting Heap-based-Objects

One of the Problems is, that you must not delete a object thats created on the stack (local objects created not using new) - this is a illegal case and will lead to a crash. But there are more implications about this items.

I can only repeat myself: Every C++ Programmer should know these books. They won't cost you too much time.

Upvotes: 3

Naveen
Naveen

Reputation: 73443

Yes, that will behave like deleting any other object.

Upvotes: 1

Related Questions