Search code examples
c++memory-managementdestructormove-semanticsnullptr

Check pointer is not null in destructor


I have class with move constructor. After moving, pointer became null. Do I have to check for not_null in destructor before calling delete?

class A {
    int *data;
public:
    A(size_t size) : data(new int[size]) {}

    A(A &&rhs) : data(rhs.data) {
        rhs.data = nullptr;
    }

    ~A() {
        if (data) {
            delete [] data;
        }
        //or
        delete [] data;
    }
}

Solution

  • No, both delete and delete[] are well-defined for nullptr - they will do nothing.