Why the below piece of code is not crashing , though i have deleted the object?

后端 未结 10 1170
北海茫月
北海茫月 2021-01-18 02:29
class object
{
  public:
    void check()
    {
      std::cout<<\"I am doing ok...\"<

        
相关标签:
10条回答
  • 2021-01-18 03:04

    I think it depends on the environment (platform/compiler)...
    This at least gives unexpected behaviour. I think you are lucky that it doesn't crash in your case ;-)

    0 讨论(0)
  • 2021-01-18 03:05

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

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

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

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

    0 讨论(0)
  • 2021-01-18 03:07

    Delete only deallocates memory and makes it available back to the heap.

    The value of the pointer is undefined after delete has been called, so it may crash it may not.

    A programming tip I use to reduce programming errors is to after a delete, set the pointer to NULL. In this way, you know you are not accidently using a pointer after it's been deleted.

    0 讨论(0)
  • 2021-01-18 03:11

    You can do the same with nil pointers, just as long as you never access the state of the class instance:

    class object
    {
      public:
        void check()
        {
          std::cout<<"I am doing ok..."<<std::endl;
        }
    };
    
    int main()
    {
      object *p = 0;
      p->check();
    }
    
    0 讨论(0)
提交回复
热议问题