【发布时间】: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