Delete NULL but no compile error

后端 未结 5 1711
悲哀的现实
悲哀的现实 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:37

    NULL and 0 aren't the same thing. In C++ you should use 0.

    There is nothing syntactically wrong or ambiguous about deleting the null pointer. In fact, this is by definition a no-op; that is, the operation of deleting the 0th address is equivalent to doing nothing at all.

    0 讨论(0)
  • 2021-01-18 06:38

    You can delete a NULL pointer without problem, and the error you may/can have won't be at compilation time but at runtime.

    int *ptr_A = &a;
    ptr_A = NULL;
    delete ptr_A;
    

    Usually it's convenient to do :

    ...
    delete ptr;
    ptr = NULL;
    
    0 讨论(0)
  • 2021-01-18 06:42

    It is a de-facto standard in C and C++ languages (and not only in them) that resource deallocation routines must accept null-pointer arguments and simply do nothing. Actually, it is a rather convenent convention. So, the real question here: why does it surprize you? What makes you think that it should produce an error? Moreover, what makes you think that it should fail to compile???

    BTW, your question, the way it is stated, doesn't seem to make much sense, since your code actually cannot compile. The supposed pointer declaration lacks a type, which will make any compiler to issue a diagnostic message.

    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2021-01-18 06:48

    The C++ language guarantees that delete p will do nothing if p is equal to NULL.

    For more info, check out Section 16.8,9 here:

    0 讨论(0)
提交回复
热议问题