【问题标题】:Why can I still call a function from a pointer class after I delete it? [duplicate]为什么删除后仍然可以从指针类调用函数? [复制]
【发布时间】:2012-10-23 18:22:03
【问题描述】:

可能重复:
What will happen when I call a member function on a NULL object pointer?

#include <iostream>
#include <string>

using namespace std;

class myClass{
private:
        int *x, *y, *z;

public:
        myClass();
    ~myClass();
    void display();
    void math(int,int,int);
};


void myClass::math(int x,int y,int z){
    this->x = new int;
    this->y = new int;
    this->z = new int;

    *this->x = x;
    *this->y = y;
    *this->z = z;

    cout << "result: " << (x*y)+z << endl;
}

myClass::~myClass(){
    delete x;
    delete y;
    delete z;
}

void myClass::display(){
    cout << x << y << z << endl;
}

myClass::myClass(){
    x=0;
    y=0;
    z=0;
}


int main()
{
    myClass myclass;
    myClass *myptr;
    myptr = new myClass();

        myclass.math(1,1,1);

myptr->math(1,1,1);

delete myptr;

myptr->math(1,1,1);  **//why does this still print?**



int t;
cin >> t;

 }

:::输出:::

结果:2

结果:2

结果:2

我只是在 C++ 中胡闹,试图了解更多。我想看看删除操作符到底做了什么。为什么我删除对象后仍然得到第三个输出“result: 2”?

【问题讨论】:

  • 因为 (a) 你没有删除 code;只有使用它的对象的内存,并且 (b) 它是完全未定义的行为。
  • 这就是为什么建议在删除指针后立即使其无效的原因。
  • @Nick:不,这就是为什么建议不要对具有所有权语义的代码使用原始指针。
  • 解除分配并不会完全删除指向的内存,它只是将其标记为未使用,这意味着之后直接使用它仍然可以工作,前提是另一个程序没有保留该内存块。跨度>

标签: c++ pointers function-pointers


【解决方案1】:

对象内存可能还没有被其他东西覆盖。不要做这样的事情,这是未定义的行为

【讨论】:

    【解决方案2】:

    那是未定义的行为。愿恶魔从你的鼻子里飞出来。

    还有另一个方面。当一个对象是deleted 时,它不会从内存中删除,直到它被之后可能创建的其他对象覆盖。因此,即使它被标记为可回收,数据(由指针指向)也可能与释放时一样。但不能保证它不会被使用。这就是为什么它的未定义行为。

    【讨论】:

      猜你喜欢
      • 2014-05-14
      • 2013-04-12
      • 1970-01-01
      • 2013-08-08
      • 2020-05-13
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多