Behavior of delete this pointer in C++ -
i trying explore pointer in c++ . have created pointer class object , caling function delete current object behavior unexpected.
why output of last print statement x= 0 , y= 6.
#include<iostream> using namespace std; class test { private: int x; int y; public: test(int x = 6, int y = 6) { this->x = x; this->y = y; } void setx(int a) { x = a; } void sety(int b) { y = b; } void destroy() { delete this; } void print() { cout << "x = " << x << " y = " << y << endl; } }; int main() { test *obj = new test(); test objs; obj->print(); obj->destroy(); obj->print(); return 0; }
deleting this legal , calls destructor of class
however, if object not allocated using new, undefined behavior
but have absolutely sure last member function invoked on object , none of of member function (after delete this line) gets called through this object, since this become dangling pointer, should not dereferenced.
if these, behavior undefined, can see in output.
Comments
Post a Comment