c++pointersdelete-operator

Is there a designated way to delete a pointer and set it to nullptr in C++?


In my c++ code, I often have blocks like this:

if (m_pointer) {
   delete m_pointer;
   m_pointer = nullptr;
}

I just wonder, whether there is a better, designated, way to do it than repeating this block all over my code. Smart pointers are not an option here, since it's all about QObjects, which don't really support them afaik.


Solution

  • Since deleting a nullptr is safe, you don't need to check, and to set it to nullptr you can just "exchange" it.

    #include<utility>
    ...
        delete std::exchange(m_pointer, nullptr);
    

    https://godbolt.org/z/eKqh7oWPW

    But if you are looking for this kind of automaticity, consider using std::unique_ptr instead.

    Here is GCC producing identical machine code for the two types of constructs: https://godbolt.org/z/aP5hsT7fv


    NB: This is not as interesting or useful as it looks, why? because any non-trivial use of null state for a pointer generally also controls other parts of the logic of the program or the class for which this pointer is a member. In these cases you need to do the if(m_pointer) conditional anyway to control that. And in the cases where this is trivial, you can already use std::unique_ptr, which precisely tracks its internal state through a null pointer. Finally, putting this kind of code in destructors is controversial at best, because there is no need to set a member variable that is about to expire.