Search code examples
c++destructorconventions

C++ Destructor Conventions


I see a lot of code like the example below in C++, which is usually recommended as a convention:

class Foo
{
public:

    Foo()
    {
        bar = new int[100];
        size = 100;
    }

    // ... copy/assignment stuff ...

    ~Foo()
    {
        if (bar) // <--- needed?
        {
            delete[] bar;
            bar = nullptr; // <--- needed?
        }

        size = 0; // <--- needed?
    }

private:

    int* bar;
    int size;
};

To me, the three statements if (bar) { ... }, bar = nullptr;, and size = 0; are redundant for two reasons:

  1. delete nullptr; is prefectly safe, and it doesn't do anything.
  2. If the object is destroyed and the memory is released, I shouldn't worry about safety to set bar to nullptr and size to 0.

Are these justifications correct? Are these statement truly redundant? If so, why do people keep using and suggesting them? I would like to see some potential problems that could be solved by keeping this convention.


Solution

  • You're right, those aren't needed and some compilers will optimize them away anyway.

    However - the reason people usually do this is to help spot out problems. For example, say you don't set the pointer to null. The object is destroyed, but then you incorrectly attempt to access the (what once was) pointer. Since the runtime will probably not clear it, you'll still see something valid there. This is only valuable from debugging, and it's still undefined behavior, but it sometimes pays off.