ggrr
ggrr

Reputation: 7867

Is it safe to do something after "delete this" if the "somethings" does not require to access "this"?

for example, I have a class which has a retain count and a release method that can delete self if the retain count is 0:

class MyClass{
public:
    void retain(){
        this->retainCount++;
    }

    void release(){
        this->retainCount--;
        if(this->retainCount==0){
            delete this;
        }

        printf("release called");
        MyClass::deleteCount++;
        FileOutputStream* fio=new FileOutputStream();
        fio->generateLog();
        delete fio;
        EmailUtils::sendEmailAboutMemoryUsage();
    }
protected:
    int retainCount;
    static int deleteCount;
}

Which I may have some code to do after the object is deleted:

printf("release called");
MyClass::deleteCount++;
FileOutputStream* fio=new FileOutputStream();
fio->generateLog();
delete fio;
EmailUtils::sendEmailAboutMemoryUsage();

My question is, if the code block after delete does not require any access of this, is it safe to continue the execution of code after the object is deleted?

Upvotes: 3

Views: 110

Answers (3)

AhmadWabbi
AhmadWabbi

Reputation: 2197

Yes it is safe. The code is not removed when you delete this. But this is a strange thing to do. My rule of thump is: "whoever creates something, should destroy it". I don't like creating things (objects, arrays, ...) in a place (in the code) and destroying them elsewhere. This may lead to bugs and memory leaks, and makes your program less readable and maintainable.

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 148975

This is perfectly defined behaviour provided you can be sure that your object had been allocated with new.

In that case, it calls the destructor and releases memory associated with the object making this a dangling pointer. As you do not access it after the delete, there is no immediate problem in your code.

BUT you should at least add a strong notice in that method because even if safe, you should warn future maintainers of the two now unbreakable rules:

  • do not access this nor any member variable of non static method after the delete this
  • never create a non dynamically allocated object of that class

Upvotes: 6

Rosh Donniet
Rosh Donniet

Reputation: 418

Here's an entry of the isocpp FAQ about this issue.

As long as you’re careful, it’s okay (not evil) for an object to commit suicide (delete this).

Basically, if you're not calling any member function or accessing any member variable after delete this, it may be okay.

See the link for details.

Upvotes: 7

Related Questions