这是关于删除分配在堆上的对象的指针。程序如下,
class Sample{
private:
int m_value1;
int m_value2;
public:
Sample();
void setValues(int m_value1, int m_value2);
void display();
};
Sample::Sample(){
this->m_value1 = 0;
this->m_value2 = 0;
}
void Sample::setValues(int m_value1, int m_value2){
this->m_value1= m_value1;
this->m_value2 = m_value2;
display();
if(this != NULL)
{
cout <<"Deleting this pointer!"<<endl;
delete this;
cout <<"this->m_value1 is "<<this->m_value1<<endl;
cout <<"this->m_value2 is "<<this->m_value2<<endl;
}
}
void Sample::display(){
cout <<"Values are "<<this->m_value1<<" and "<<this->m_value2<<endl;
}
int main(){
Sample *obj1 = new Sample();;
obj1->setValues(4,6);
obj1->display();
getch();
}
输出:
Values are 4 and 6
Deleting this pointer!
this->m_value1 is 65535
this->m_value2 is 6
Values are 65535 and 6
为什么 m_value1 的值消失了,而另一个变量 m_value2 的值却保留了下来?
最佳答案
在 delete this
之后访问成员变量是未定义的行为 - 任何事情都可能发生,包括读取意外数据、程序崩溃或其他任何事情。该对象已被销毁和释放,您尝试取消引用无效指针。一旦发生delete this
- 不要尝试访问成员变量,不要尝试调用成员函数和don't do anything else (including comparing or casting) to this
pointer .
关于c++ - 删除这个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9259693/