Is delete this allowed?

后端 未结 10 1484
-上瘾入骨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 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 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.

提交回复
热议问题