Return value after deletion;

Let's say I have 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 normal or is this undefined behavior, what will foo return true?

I ask what happens to the member function after " delete this;".

+4
source share
2 answers

I searched in the project for the current standard, and also read the question link in the comments and FAQ.

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

The standard says:

  • value, , : fine this
  • - , -delete ( ) : fine, destructor ...
  • - , : , , , (5.3.4), delete : fine,

, delete this, true, , UB. FAQ ( ed) , delete this ++.

, return true .

, delete this , , , UB.

+1

, "delete this" , , .

, IS undefined -; () ( vtable). , , ( ) .

+1

Source: https://habr.com/ru/post/1569762/


All Articles