2012-02-13 92 views
0

这是关于这个指针上heap.Program如下分配对象的缺失,删除这个指针

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(); 
} 

OUTPUT:

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?

+0

[相关](http://stackoverflow.com/a/7039749/220636) – nabulke 2012-02-13 11:31:38

+0

也许你有学习'this'意义。所有的 – vulkanino 2012-02-13 11:32:36

+1

首先,'this'永远不要向外界'NULL'非静态成员函数内部时。其次,你应该**永远不要删除'this'!你在做什么就像在拆下桥的时候拆掉它。 – 2012-02-13 11:33:11

回答

6

访问成员变量delete this后是不确定的行为 - 任何事情都有可能发生,包括读取意外数据,程序崩溃或其他任何东西。该对象已被销毁并解除分配,并尝试解除引用无效指针。一旦delete this已经发生了 - 不要试图访问成员变量,不要试图牛逼调用成员函数和don't do anything else (including comparing or casting) to this pointer

2

为什么m_value1的值消失,而它保持另一个变量m_value2?

您删除后,您正在访问的内存。这意味着你正在调用未定义的行为。因此,任何事情都可能发生,你的观察与其他事情一样是对还是错。

可能发生的情况是存储m_value1的那部分内容被重用于其他内容,而m_value2的存储尚未用于其他任何内容(尚)。

1

这是一个偶然的机会,可能是operator<<或删除后的任何操作this分配足够的内存来覆盖一个而不是其他。

但是当你做一些不应该做的,你不应该依赖于任何特定的后果。

0

危险和不可预测的产出预计包括系统崩溃! 请勿直接删除由此指向的位置。它不是一个好的编程习惯。删除后不要使用内存。即使u必须把它放在一个断言()内

this != NULL // this will never be NULL if used properly.