Search code examples
c++return-valuemember-functionsdelete-operator

Return value after delete this;


Let's say I've got a class A

class A {
public:
    A(){};
    ~A(){};
    bool foo(int);
};

bool A::foo(int i){

    if(i==10){
        delete this;
        return true;
    }
    return false;
}

int main(){

    A *pnt = new A();
    if(pnt->foo(10)){
        cout<<"deleted with foo"<<endl;
    }
    else{
        delete pnt;
    }
    return 1;
}

Is this ok or is it undefined behavior that foo will return true?

I'm asking what happens to the member function after "delete this;".


Solution

  • I searched in draft for current standard and also read the question referenced in comments and the FAQ.

    I could not find any elements saying that this code should lead to Undefined Behaviour.

    The standard says :

    • the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression : fine this is correct in above code
    • If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object : fine, destructor does nothing ...
    • If the value of the operand of the delete-expression is not a null pointer value, then: If the allocation call for the new-expression for the object to be deleted was not omitted and the allocation was not extended (5.3.4), the delete-expression shall call a deallocation function : fine, object will be deallocated

    As the code in not in the allocated part of object and as after delete this, code only uses the constant value true, there is no reason for the code to lead to UB. FAQ (and answers to refed question) clearly indicates that delete this is valid and idiomatic C++.

    So there is no reason why return true should not be executed.

    That being said, as for any other usage of delete this programmer must ensure to use it only on objects allocated with new because if not it is indeed UB.