Search code examples
c++delete-operator

Calling delete upon a conditional call to new


Suppose I have the following class:

foo{
    ~foo();

    private:
        char *bar;
};

Under certain conditions bar will create a new char array so what would be the correct way to handle the deletion of it? Would a simple bool do or would that be considered bad practice?


Solution

  • deleteing a null pointer is safe. That's why you should always set your pointer to NULL or nullptr when not in use:

    struct foo{
        foo() : bar(NULL) {}
            //  ^ Initialize bar to NULL
    
        ~foo() {
           delete bar;
        }
    
        void some_method() {
            bar = new char;
            ...
            delete bar;
            bar = NULL;  // Immediately set bar back to NULL
        }
    
        private:
            char *bar;
    };
    

    Please note that when you set a pointer to the one returned by new, you must match it with delete, while if you set it using the pointer returned by new[], be sure to use delete[] on it.

    Anyway, if you have access to C++11 smart pointers std::shared_ptr or std::unique_ptr, then they are your best bet.