NULL pointer is the same as deallocating it?

前端 未结 11 2502
一个人的身影
一个人的身影 2021-02-18 18:29

I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?

For instance:

11条回答
  •  不知归路
    2021-02-18 19:05

    By assigning NULL to the pointer you will not free allocated memory. You should call deallocation function to free allocated memory. According to C++ Standard 5.3.4/8: "If the allocated type is a non-array type, the allocation function’s name is operator new and the deallocation function’s name is operator delete". I could suggest the following function to safely delete pointers (with assigning NULL to them):

    template
    inline void SafeDelete( T*& p )
    {
        // Check whether type is complete.
        // Deleting incomplete type will lead to undefined behavior
        // according to C++ Standard 5.3.5/5.
        typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
        (void) sizeof(type_must_be_complete);
    
        delete p;
        p = NULL;
    }
    

提交回复
热议问题