Is delete this allowed?

后端 未结 10 1388
-上瘾入骨i
-上瘾入骨i 2020-11-22 03:40

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 ob

相关标签:
10条回答
  • 2020-11-22 04:17

    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.

    0 讨论(0)
  • 2020-11-22 04:18

    You can do so. However, you can't assign to this. Thus the reason you state for doing this, "I want to change the view," seems very questionable. The better method, in my opinion, would be for the object that holds the view to replace that view.

    Of course, you're using RAII objects and so you don't actually need to call delete at all...right?

    0 讨论(0)
  • 2020-11-22 04:20

    Well, in Component Object Model (COM) delete this construction can be a part of Release method that is called whenever you want to release aquisited object:

    void IMyInterface::Release()
    {
        --instanceCount;
        if(instanceCount == 0)
            delete this;
    }
    
    0 讨论(0)
  • 2020-11-22 04:20

    Delete this is legal as long as object is in heap. You would need to require object to be heap only. The only way to do that is to make the destructor protected - this way delete may be called ONLY from class , so you would need a method that would ensure deletion

    0 讨论(0)
提交回复
热议问题