Is it safe to delete a NULL pointer?

qiuxiafei picture qiuxiafei · Nov 16, 2010 · Viewed 171k times · Source

Is it safe to delete a NULL pointer?

And is it a good coding style?

Answer

ruslik picture ruslik · Nov 16, 2010

delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems).

I'd also love if delete by default was setting the parameter to NULL like in

#define my_delete(x) {delete x; x = NULL;}

(I know about R and L values, but wouldn't it be nice?)