Do classes destroy all its objects when the destructor runs?

Here I have been told to mimic a dynamically allocated int array. Note that uncommenting the destructor causes a crash (double free)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  /*Write your own integer array class named IntArray from scratch (do not use
 * std::array or std::vector). Users should pass in the size of the array when
 * it is created, and the array should be dynamically allocated.*/

#include <iostream>
using namespace std;

class IntArray {
 private:
  int* arr0{0};
  size_t length;

 public:
  IntArray(const size_t n) : length{n} { arr0 = new int[n]; }
  // overload subscript op
  int& operator[](const size_t element) const { return this->arr0[element]; }

  // IntArray1 = IntArray2
  // deep copy
  IntArray& operator=(IntArray& given_arr) {
    this->length = given_arr.length;
    this->arr0 = given_arr.arr0;
    for (size_t i = 0; i < length; ++i) {
      this->arr0[i] = given_arr[i];
    }
    return *this;
  }

  friend ostream& operator<<(ostream& os, const IntArray& arr) {
    for (size_t i = 0; i < arr.length; ++i) {
      os << arr[i] << " ";
    }
    return os;
  }

  // deleting arr0 will make the program crash!
  //~IntArray() { delete[] arr0; }
};

// a function that just returns an IntArray
IntArray fillArray() {
  IntArray a(5);
  a[0] = 5;
  a[1] = 8;
  a[2] = 2;
  a[3] = 3;
  a[4] = 6;

  return a;
}

int main() {
  IntArray a = fillArray();
  std::cout << a << '\n';

  IntArray b(1);
  a = a;
  b = a;  // copy

  std::cout << b << '\n';

  return 0;
}
Last edited on
Yes and No.
All class member variables are destroyed when the object is destroyed, but any dynamic memory allocated for them is NOT.

so

class leak
{
int * ip;
leak::leak(){ip = new int[1000];} //leaks. ip is destroyed when an object dies, but the memory allocated is still owned by the program. you need a delete[] ip; in the dtor.
}

thankfully vectors destroy their own memory, so using that instead of a pointer in your class solves the problem (not here, but in unlimited code, here you were told not to use a vector).
Last edited on
@Jonnin

Understood. However uncommenting line 37 causes a double-free. I wonder what the problem is.
I wonder what the problem is.
The reason is that you have an copy operator which makes a deep copy but not copy constructor. The copy construct is called on line 53. See:

https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)

also, your operator= may access out of range
Topic archived. No new replies allowed.