0

I searched for an answer to this question, but did not come across a case like mine.

Having the following code:

A
{
 private:
     SomeObject** _array; 
 public:
     A(int n) { 
         _array = new SomeObject*[n];
     }
     virtual ~A(){
         delete[] _array;
     }
}

As you can see _array is a pointer to an array of pointers, pointing at objects(SomeObject). Is the destructor in the code correct? As far as i understand, "delete []" calls the destructor of each element in the array. And as this is an array of pointers, simply calling "delete []" is not correct. In my opinion, the correct solution is to 1)iterate over the array and delete each element, then 2)call "delete [] _array".

Thank you very much in advance!

  • 4
    Any reason you cannot use `std::vector` and/or smart pointers? – UnholySheep Feb 23 '18 at 21:07
  • 1
    Your "correct solution" would only be correct if you did something similar during construction. As of right now the pointers in the second dimension of the array are not dynamically allocated with `new`; therefore it would be incorrect to `delete` them. – 0x5453 Feb 23 '18 at 21:08
  • Your array elements are pointers. Pointers are POD types and don't have destructors. – Thomas Matthews Feb 23 '18 at 21:09
  • I agree with UnholySheep. But just to expand on it. Go to cppreference.com and look through Container's Library (e.g. std::vector and friends) for something that fits. If nothing fits your needs, consider std::unique_ptr next. Then, consider std::shared_ptr. All of these take care of cleaning up their children for you when they are deleted. – Dave Feb 23 '18 at 21:15
  • as part of my studies i need to understand these examples, and not resort to other methods... – Shahaf Nahmias Feb 23 '18 at 21:18

0 Answers0