question about destructors

Will a class destructor automatically clear away any dynamically created memory or do I need to define it?
1
2
3
4
5
 //destructor
superArray::~superArray() {
	delete[] p; // Do I need to put this here?
	cout << "ALL CLEAR.";
}
If, at the time of destruction, p is a pointer to an array of memory that was allocated using new and by that point nobody has called delete on it, you need to do it.

Even better, use a modern smart pointer as a member variable and then that smart pointer's destructor will take care of it for you.

Even better, if possible, just have the array be a member variable of the class so you don't need to bother with new and delete.
Last edited on
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
class superArray {
	int size;
	int *p;

public:
	superArray operator + (const superArray &arr) {
		superArray temp(size + arr.size);
		
		return temp;
	}

	void operator = (const superArray &arr) {
		delete[] p;
		size = arr.size;
		p = new int[size];

		for (int i = 0; i < size; i++) {
			p[i] = arr.p[i];
		}
	}

	superArray();
	superArray(int);
	~superArray();
	void printArray();
	void setValues();

};


So this is my class. Since p is a member of the class, I am good? Or do I still need delete in the destructor? p is a pointer...
This class could allocate memory using new that will never ever be deleted. This is bad.

It could also (the first time operator= is used) call delete on p when p is not pointing at memory that was allocated using new. This is also very bad.

This class gets memory wrong, and has a good chance of crashing the first time operator= is called.
Last edited on
I have a default constructor and an overloaded constructor, both use the new keyword to allocate dynamic memory. As a habit when I use new I put delete in there somewhere. I was wondering if it was needed this time or if the destructor clears the memory automatically.
I don't know how many times to keep answering this same question. Yes, you need to use delete.

As a habit when I use new I put delete in there somewhere.

That's not a terrible habit to have, but a better habit is that every time you put new, press backspace a few times to remove it and then either put the variable on the stack, or if it simply must go on the heap, use a smart pointer and make_unique or make_shared.

Basically, as a habit, don't use new.
Last edited on
Ok I better take your advice here. Thank you for your help and patience.

Its back to the drawing board for me...
Topic archived. No new replies allowed.