为什么下面的代码不崩溃,虽然我已经删除对象? [英] Why the below piece of code is not crashing , though i have deleted the object?

查看:109
本文介绍了为什么下面的代码不崩溃,虽然我已经删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class object
{
  public:
    void check()
    {
      std::cout<<"I am doing ok..."<<std::endl;
    }
};

int main()
{
  object *p = new object;
  p->check();
  delete p;
  p->check();
  delete p;
  p->check();
}

EDIT
Gurus很多语句混淆了它可能崩溃或可能不会..为什么没有标准说,这是我们如何处理使用删除操作符删除的内存块?任何输入?

EDIT: Gurus, i am confused by many of the statements "it may crash or may not".. why isnt there a standard to say, this how we deal with a block of memory that is deleted using 'delete operator'..? Any inputs ?

推荐答案

因为编译器已经有了它,它实际上看起来像这样:

Because what it actually looks like after the compiler has had its way, is something like this:

object::check( object* this )
{
     // do stuff without using this
}

int main()
{        
     object *p = new object;
     object::check( p );
     delete p;
     object::check( p );
     delete p;
     object::check( p );
 }

由于您没有触摸this

Since you're not touching "this", you don't actually access any bad memory.

虽然删除p两次应该会导致崩溃:

Although, deleting p twice should be able to cause a crash:

http://www.parashift.com/c++-faq-lite/freestore -mgmt.html#faq-16.2

这篇关于为什么下面的代码不崩溃,虽然我已经删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆