这是关于删除堆上分配的对象的指针.程序如下,
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();
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
Values are 4 and 6
Deleting this pointer!
this->m_value1 is 65535
this->m_value2 is 6
Values are 65535 and 6
Run Code Online (Sandbox Code Playgroud)
为什么m_value1的值会消失,而另一个变量m_value2会保留?
在delete this未定义的行为之后访问成员变量- 任何事情都可能发生,包括读取意外数据,程序崩溃或其他任何事情.该对象已被销毁并取消分配,您尝试取消引用无效指针.一旦delete this发生 - 不要尝试访问成员变量,不要尝试调用成员函数,也不要做任何其他事情(包括比较或转换)到this指针.