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;
".
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 :
this
is correct in above codeAs 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.