1

Do destructors automatically call delete[] in C++?

For example:

class A
{
    int *num;

    A()
    {
        num=new int[5];
    }

    ~A() {}
}

Do I have to add delete[] into ~A()?

SomeRandomDev
  • 129
  • 11
Tki Lio
  • 263
  • 1
  • 8
  • Any `new/new[]` must have corresponding `delete/delete[]`. Recently, I learnt nothing comes for free in this world :) – Mahesh Aug 28 '18 at 15:06
  • 3
    This is an example of the problem [`std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr) was invented to solve. – François Andrieux Aug 28 '18 at 15:07
  • 1
    Not only do you need a corresponding `delete[]`, you also have to worry about the [rule of 3-5-0](https://en.cppreference.com/w/cpp/language/rule_of_three). – François Andrieux Aug 28 '18 at 15:09
  • If that is the case, why do we need destructors? Do they only delete the reference to the object? – Tki Lio Aug 28 '18 at 15:12
  • @TkiLio We need destructors because we need a place to write out how to cleanup the class. In this case, a place to tell the class it needs to `delete[]` it's `num`. – François Andrieux Aug 28 '18 at 15:15

2 Answers2

6

They do not. If you want your dynamically allocated int array to be automatically destroyed when A is destroyed, using std::vector<int> (or std::array<int, 5> if your size is fixed) instead of an int pointer would probably be a good choice.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • If that is the case, why do we need destructors? Do they only delete the reference to the object? – Tki Lio Aug 28 '18 at 15:12
  • @TkiLio Modern C++ rarely has a need for destructors, indeed. This is called the "rule of zero". See [here](https://en.cppreference.com/w/cpp/language/rule_of_three) for some more information, although there is plenty of other material for this. – Max Langhof Aug 28 '18 at 15:13
  • @TkiLio dynamically allocated memory is specially used when programmer needs to control lifetime of the object so compiler cannot read your mind and decide when object needs to be destroyed. – Slava Aug 28 '18 at 15:14
  • @TkiLio destructors are normally needed to _implement_ the things like `std::vector` and the like. But since in your case such facility already exists, it's usually wiser to use it rather than to re-invent the wheel. – Ruslan Aug 28 '18 at 15:15
2

No. You need to call delete[] num in your destructor to avoid memory leaks upon destructing instances of your class A.

If you want to avoid this manual bookkeeping, you can consider using the following standard containers or wrappers that encapsulate and perform the bookkeeping for you in their destructors:

Matthias
  • 4,481
  • 12
  • 45
  • 84