Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading