delete "this pointer" safe ??
delete this is legal and does what you would expect: it calls your class's destructor and free the underlying memory. After delete this returns, your this pointer value does not change, so it is now a dangling pointer that should not be dereferenced.
# It is considered bad practice to use delete this.
However, if used, the following points must be considered:
1. The delete operator works only for objects allocated using new operator. If the object is created using new, then we can do delete this, otherwise behavior is undefined.
class A {
public:
void fun(){
delete this;
}
};
int main(){
/* Following is valid */
A *ptr = new A;
ptr->fun();
ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr.
/* And following is invalid: Undefined Behavior */
A a;
a.fun();
return 0;
}
2. Once delete this is done, any member of the deleted object should not be accessed after deletion.
class A {
int x;
public:
A() {
x = 0;
}
void fun() {
delete this;
/* Invalid: Undefined Behavior */
cout<<x;
}
};
Comments
Post a Comment