1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David S
  • 195
  • 5
  • 19

3 Answers3

7

If bar is nullptr, then you can safely call delete on it:

bar = nullptr;
delete bar;

so you don't need to test, just delete.

3.7.4.2/3:

The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.

Community
  • 1
  • 1
perreal
  • 94,503
  • 21
  • 155
  • 181
4

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.

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
  • Suppose I want to do this to a 2D-array how would you set the second element to NULL? – David S Jun 05 '13 at 08:59
  • @DavidS, if you need an array, why don't you use `std::vector`? – Denis Novikov Jun 05 '13 at 09:03
  • @DavidS [I don't know why I did this... but NP.](http://coliru.stacked-crooked.com/view?id=928e9a3b0c9929aa0fb43b50dc1e9c7b-50d9cfc8a1d350e7409e81e87c2653ba) – Mark Garcia Jun 05 '13 at 09:09
  • @DenisNovikov Using a 2d array to map a value to each pixel on the screen when the program starts up, also from my understanding vectors are slightly slower so that's why I opted for array. – David S Jun 05 '13 at 09:36
  • @DavidS, as I can see from the example below, `std::vector` has slower construction/destruction, but not data access. If you do not need to often create/destroy array, `std::vector` would not be slower, but it can be safer to use it. Example: http://ideone.com/cUOlpp – Denis Novikov Jun 05 '13 at 11:47
1

Initialize bar to nullptr/NULL (/), You can delete it without any checks in the destructor.

Your class definition will contain char *bar=nullptr;.

Marc Claesen
  • 16,778
  • 6
  • 27
  • 62