Is "delete this" allowed in C++?

121,374

Solution 1

The C++ FAQ Lite has a entry specifically for this

I think this quote sums it up nicely

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

Solution 2

Yes, delete this; has defined results, as long as (as you've noted) you assure the object was allocated dynamically, and (of course) never attempt to use the object after it's destroyed. Over the years, many questions have been asked about what the standard says specifically about delete this;, as opposed to deleting some other pointer. The answer to that is fairly short and simple: it doesn't say much of anything. It just says that delete's operand must be an expression that designates a pointer to an object, or an array of objects. It goes into quite a bit of detail about things like how it figures out what (if any) deallocation function to call to release the memory, but the entire section on delete (§[expr.delete]) doesn't mention delete this; specifically at all. The section on destrucors does mention delete this in one place (§[class.dtor]/13):

At the point of definition of a virtual destructor (including an implicit definition (15.8)), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor’s class (see 8.3.5).

That tends to support the idea that the standard considers delete this; to be valid--if it was invalid, its type wouldn't be meaningful. That's the only place the standard mentions delete this; at all, as far as I know.

Anyway, some consider delete this a nasty hack, and tell anybody who will listen that it should be avoided. One commonly cited problem is the difficulty of ensuring that objects of the class are only ever allocated dynamically. Others consider it a perfectly reasonable idiom, and use it all the time. Personally, I'm somewhere in the middle: I rarely use it, but don't hesitate to do so when it seems to be the right tool for the job.

The primary time you use this technique is with an object that has a life that's almost entirely its own. One example James Kanze has cited was a billing/tracking system he worked on for a phone company. When start to you make a phone call, something takes note of that and creates a phone_call object. From that point onward, the phone_call object handles the details of the phone call (making a connection when you dial, adding an entry to the database to say when the call started, possibly connect more people if you do a conference call, etc.) When the last people on the call hang up, the phone_call object does its final book-keeping (e.g., adds an entry to the database to say when you hung up, so they can compute how long your call was) and then destroys itself. The lifetime of the phone_call object is based on when the first person starts the call and when the last people leave the call--from the viewpoint of the rest of the system, it's basically entirely arbitrary, so you can't tie it to any lexical scope in the code, or anything on that order.

For anybody who might care about how dependable this kind of coding can be: if you make a phone call to, from, or through almost any part of Europe, there's a pretty good chance that it's being handled (at least in part) by code that does exactly this.

Solution 3

If it scares you, there's a perfectly legal hack:

void myclass::delete_me()
{
    std::unique_ptr<myclass> bye_bye(this);
}

I think delete this is idiomatic C++ though, and I only present this as a curiosity.

There is a case where this construct is actually useful - you can delete the object after throwing an exception that needs member data from the object. The object remains valid until after the throw takes place.

void myclass::throw_error()
{
    std::unique_ptr<myclass> bye_bye(this);
    throw std::runtime_exception(this->error_msg);
}

Note: if you're using a compiler older than C++11 you can use std::auto_ptr instead of std::unique_ptr, it will do the same thing.

Solution 4

One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.

Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.

Solution 5

It is allowed (just do not use the object after that), but I wouldn't write such code on practice. I think that delete this should appear only in functions that called release or Release and looks like: void release() { ref--; if (ref<1) delete this; }.

Share:
121,374

Related videos on Youtube

Martijn Courteaux
Author by

Martijn Courteaux

I'm writing Java, C/C++ and some Objective-C. I started programming in 2007 (when I was 11). Right now, I'm working on my magnum opus: an iOS, Android, OS X, Linux, Windows game to be released soon on all relevant stores. The game is written in C++ using SDL and OpenGL. A couple of seeds for my name (for java.util.Random, radix 26): 4611686047252874006 -9223372008029289706 -4611685989601901802 28825486102

Updated on February 06, 2021

Comments

  • Martijn Courteaux
    Martijn Courteaux over 3 years

    Is it allowed to delete this; if the delete-statement is the last statement that will be executed on that instance of the class? Of course I'm sure that the object represented by the this-pointer is newly-created.

    I'm thinking about something like this:

    void SomeModule::doStuff()
    {
        // in the controller, "this" object of SomeModule is the "current module"
        // now, if I want to switch over to a new Module, eg:
    
        controller->setWorkingModule(new OtherModule());
    
        // since the new "OtherModule" object will take the lead, 
        // I want to get rid of this "SomeModule" object:
    
        delete this;
    }
    

    Can I do this?

    • Lundin
      Lundin over 8 years
      Main problem would be that if you delete this you have created a tight coupling between the class and the allocation method used for creating objects of that class. That is very poor OO design, since the most fundamental thing in OOP is to make autonomous classes which don't know or care about what their caller is doing. Thus a properly designed class shouldn't know or care about how it was allocated. If you for some reason need such a peculiar mechanism, I think a better design would be to use a wrapper class around the actual class, and let the wrapper deal with the allocation.
    • Jimmy T.
      Jimmy T. about 4 years
      Can't you delete in setWorkingModule?
    • Ayxan Haqverdili
      Ayxan Haqverdili over 3 years
      @Lundin CFrameWnd class from MFC does delete this; in PostNcDestroy because that's when the WinAPI class it's wrapping is getting destroyed presumably. So, it does have its own valid use cases, I'd say.
    • Dragan
      Dragan almost 3 years
      @Lundin The problem is not deallocation, but destruction. In C++ the only proper way to separate these two, and still achieve encapsulation and polymorphism, is to use shared_ptr. Unique_ptr does not separate them. The class in question doesn't care about allocation/deallocation, but it wants to control its lifetime. I would bet the class in question can be properly designed with shared_ptr/enable_shared_from_this, but I don't like that it has to be done that way, especially since shared_ptr/enable_shared_from_this eat a lot of code size and are therefore unusable for my embedded development.
  • Alexandre C.
    Alexandre C. almost 14 years
    The corresponding FQA also has some useful comment : yosefk.com/c++fqa/heap.html#fqa-16.15
  • Alexandre C.
    Alexandre C. almost 14 years
    Thanks, I'll put it somewhere in my memory. I suppose you define the constructors and destructors as private and use some static factory method to create such objects.
  • Jerry Coffin
    Jerry Coffin almost 14 years
    @Alexandre: You'd probably do that in most cases anyway -- I don't know anywhere close to all the details of the system he was working on, so I can't say for sure about it though.
  • Joh
    Joh almost 12 years
    +1. I can't understand why you were downvoted. "C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack" is very good advice.
  • Felix Dombek
    Felix Dombek over 10 years
    You could just wrap the object you want to delete itself in a special class which deletes the object and then itself, and use this technique for preventing stack allocation: stackoverflow.com/questions/124880/… There are times when there is really not a viable alternative. I just used this technique to self-delete a thread that is started by a DLL function, but the DLL function must return before the thread ends.
  • cmaster - reinstate monica
    cmaster - reinstate monica about 9 years
    Which is exactly once in every project of mine... :-)
  • Cem Kalyoncu
    Cem Kalyoncu over 8 years
    For safety you may use private destructor on the original object to make sure its not constructed on the stack or as a part of an array or vector.
  • Lundin
    Lundin over 8 years
    Why can't you just have a (singleton) class "allocator/garbage collector", an interface through which all allocation is done and let that class handle all reference counting of the allocated objects? Rather than forcing the objects themselves to bother with garbage collection tasks, something that is completely unrelated to their designated purpose.
  • MBraedley
    MBraedley almost 8 years
    The way I often get around the problem of how the memory was allocated is to include a bool selfDelete parameter in the constructor that gets assigned to a member variable. Granted, this means handing the programmer enough rope to tie a noose in it, but I find that preferable to memory leaks.
  • Jerry Coffin
    Jerry Coffin almost 8 years
    @MBraedley: I've done the same, but prefer to avoid what seems to me like a kludge.
  • Game_Overture
    Game_Overture over 7 years
    You can also just make the destructor protected to prohibit static and stack allocations of your object.
  • Owl
    Owl over 7 years
    I can't get this to compile using c++11, is there some special compiler options for it? Also does it not require a move of the this pointer?
  • Mark Ransom
    Mark Ransom over 7 years
    @Owl not sure what you mean, it works for me: ideone.com/aavQUK. Creating a unique_ptr from another unique_ptr requires a move, but not from a raw pointer. Unless things changed in C++17?
  • Owl
    Owl about 7 years
    Ahh C++14, that'll be why. I need to update my c++ on my dev box. I'll try again tonight on my recently emerged gentoo system!
  • CinCout
    CinCout almost 7 years
    Define 'careful'
  • CharonX
    CharonX about 6 years
    'Careful' is defined in the linked FAQ article. (While the FQA link mostly rants - like almost everything in it - how bad C++ is)
  • Galaxy
    Galaxy over 5 years
    For anybody who might care ... there's a pretty good chance that it's being handled (at least in part) by code that does exactly this. Yes, the code is being handled by the exactly this. ;)
  • Jimmy T.
    Jimmy T. about 4 years
    You can't program in such a way that someone doing just copy and paste with your code ends up misusing it anyway
  • Ayxan Haqverdili
    Ayxan Haqverdili over 3 years
    Do note that making the dtor protected won't make sure the object is only ever created with new operator. It could be malloc+operator new() or some means, in which case delete this; would cause undefined behavior.
  • Dragan
    Dragan almost 3 years
    It's a hack, unless you make your destructor private, which will prevent unique_ptr from working.