Should “delete this” be called from within a member method?

前端 未结 12 2022
醉酒成梦
醉酒成梦 2020-12-03 10:55

I was just reading this article and wanted SO folks advice:

Q: Should delete this; be called from within a member method?

12条回答
  •  执念已碎
    2020-12-03 11:04

    Yes. Like all the answers say, if you're 100% sure that the class's data will not be used after the delete this is called.

    For example, in one project:

    void Test()
    MyClass * Someclass = new MyClass;
    SomeClass->DoYourThing();
    SomeClass->KillYourself();
    return;
    
    void MyClass::DoYourThing() { return; }
    void MyClass::KillYourself() {delete this;}
    

    Very simplistic explanation, the project used delete this; as part of the memory management for objects of that type; their constructor added them to a private list of classes of that type in use, and removed themselves from that list when they were destroyed and then deleted themselves (this was not in a destructor). Any objects of that class that hadn't deleted themselves when the program reached its endpoint then all had their KillYourself() equivalent called from a static member function CleanYourselves()

提交回复
热议问题