delete后仍然可以调用问题

来源:互联网 发布:商标域名注册管理局 编辑:程序博客网 时间:2024/04/30 11:48
#include <iostream.h>

class ClassOne
{
public:
int   i;
void SetValue()
{
i = 1000;
}
void PrintValue()
{
cout<<"i = "<<i<<endl;
}
public:
ClassOne()
{
          i = 100;
}
virtual ~ClassOne()
{
}
};

void main()
{
ClassOne*  pBase;
pBase =  new ClassOne;
         pBase->PrintValue();
delete pBase;

pBase->SetValue();//已经用delete销毁pBase所指对象了,为什么还能
                           //调用SetValue函数并成功地将i置为1000???
pBase->PrintValue();

}  



我认为delete pBase只是通知系统,pBase所指的空间可以由系统自由分配了,相当于归还使用权。但pBase指针值没有变。由于你立刻调用pBase->SetValue,所以这块地址中的信息还没有被系统冲掉。因此你这样操作仍旧可以。为了彻底解决delete pBase后pBase可能还能使用的问题,一个好的编程风格是在delete pBase后,马上写上一句pBase = NULL;这样就永远不会有pBase->SetValue成立的可能性了。

0 0