vendredi 27 août 2021

Is it safe to delete a nullptr twice in C++?

I have watched a talk in CPPCon which is back to basic: class layout and the link is this. At 54:20, he said it's undefined bahavior to delete the nullptr twice. As far as I know, C++ standard guarantee deleting a nullptr does nothing but why deleting a nullptr twice is undefined bahavior?

And I was told before that there is no need to check if ptr is null in destructor because deleting a null pointer is valid. But if delete a null pointer twice is undefined, does that mean I still need to check if it's nullptr to prevent double-deleting happen?

This is a transcription of the author from his video:

[...] ignore the standard and then got later problems. A common example I see is it's ok to delete a null pointer, that's fine, but you can't delete it twice without resetting the value to some valid pointer value. If I delete the same pointer twice if it's not null you'll get probably a segfault, if it is null it typically just happens to work, but it's not guaranteed to work and there was actually one compiler in the 1980s where it wouldn't work because when you deleted a pointer a new value was overwritten in the deleted pointer. So again, do follow the standard.

Aucun commentaire:

Enregistrer un commentaire