Delete NULL but no compile error

后端 未结 5 1710
悲哀的现实
悲哀的现实 2021-01-18 06:12

I\'m confused why the following C++ code can compile. Why does a call to delete the method of 0 not produce any error?!

int *arr = NULL;     // or if I use 0         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-18 06:43

    Although your example is trivial, there is no way for a compiler to know (at compile time) the value of a pointer.

    You can also dereference null at compile time:

    // this code compiles
    Object* pObject = 0;
    pObject->SomeMethod();
    

    Compilers aren't built to handle these kinds of error conditions at compile time.

    And most (all?) implementations have 'delete 0' as a non-operation. This code should run fine:

    Object* pObject = new Object();
    delete pObject;
    pObject = 0;
    delete pObject;
    

    Although I'm not 100% sure on that :)

提交回复
热议问题