我正在尝试在 c++ 中探索这个指针。 我已经创建了一个指向类对象的指针并调用了一个函数来删除当前对象,但行为是意外的。
为什么最后一个打印语句的输出是 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;
}
最佳答案
删除this
是合法的,调用类的析构函数
但是,如果对象不是使用 new
分配的,它将是一个未定义的行为
但您必须绝对确定这将是在此对象上调用的最后一个成员函数,并且您的任何成员函数(在 delete this
行之后)都不会通过 this< 调用
对象,因为 this
将成为一个悬空指针,不应取消引用。
如果你这样做,行为将是未定义的,所以你可以在你的输出中看到任何东西。
关于c++ - 在 C++ 中删除此指针的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547693/