c++pointersmacrosdelete-operator

How to write a C++ function that deletes a pointer instead of a macro


I found a macro in legacy code that deletes a pointer. I tried to replace it with a function, and it crashed the application. I can't figure out why. Is there something wrong with my function?

//Legacy Macro
#define DEL_PTR(x) { if (x != nullptr){ delete x; } }

//My function
void delPtr(void * x) { if (x != nullptr){ delete x; } }

Solution

  • You are deleting pointers of the wrong type.

    Consider that you are not actually deleting the pointer, but the pointee. Then it should be clear what the problem is: You attempt to delete objects of type void. Makes no sense.

    You can write a template function that deduces the type of the pointer:

    template <typename P>
    void delPtr(P* ptr) {
         delete ptr;
    }
    

    The check for nullptr is superfluous.

    You should not actually need such a function, because you should use smart pointers rather than manually managing the memory. Moreover there is no advantage of delPtr(x) compared to delete x;. It can be considered obfuscation. Perhaps the original author mistakenly assumed the nullptr check is needed and then mistakenly thought it would be a good idea to use a macro to shorten the code. You better get rid of this.