c++ - 删除这个指针

标签 c++

这是关于删除分配在堆上的对象的指针。程序如下,

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/

相关文章:

c++ - 为 iOS 开发人员启动 Qt/C++ 开发 (obj C)

c++ - Delphi 相当于 C++ 的 memset 是什么?

c++ - 将 OpenGL 渲染保存到图像文件

c++ - 如何使用 boost::json::value 调用无参数函数

c++ - 如何过早停止长时间运行的功能?

c++ - 如何在主机 C++ 函数之间传递 cl::Buffer 对象?

c++ - 语言环境构面构造函数被忽略

c++ 这个指针不执行构造函数

c++ - 使用G++编译C++程序时出错

c++ - 在 map 中使用已删除的元素