If I have a class that looks something like this:
class SomeClass {
public:
SomeClass(int size) {
arr = new int[size];
someInt = size / 10;
};
~SomeClass() {
delete [] arr;
//do I need to somehow delete the int value 'someInt'?
};
private:
int *arr; //pointer to dynamically allocated array
int someInt;
}
What, exactly, should be contained in the destructor to avoid memory leaks?
I am aware that I need to delete the array, since it is dynamically allocated, but do I need to do anything with int values, or other basic data types?
Thanks, Jonathan
No.
But not just for basic types. For anything that you didn't allocate with new
you don't have to call delete
on. Even for pointers.
delete
has (somehow) nothing to do with the member variable type. What matters is if you have allocated it (with new
) in your constructor (or somewhere else in your class methods).
The rule of thumb is
Have as many delete as new
Have as many delete[] as new[].
Of course sometimes you will have to delete
something you haven't allocated but are pointing to if it is not needed anymore (allocated by someone else but you are the only one using it).
Of course sometimes you will have to NOT delete
something you HAVE allocated but someone else is pointing to (allocated by you but someone else is using it).
No, you don't have to manually delete automatic variables. Only delete
what you new
.
Additionally, you can avoid the need to delete the array by using RAII via a smart pointer. Then you won't have to manually define a destructor; the automatically defined destructor will do what you need.
class SomeClass {
public:
SomeClass(int size)
: arr {new int[size]}
, someInt = size/10;
{};
private:
std::unique_ptr<int[]> arr; //pointer to dynamically allocated array
int someInt;
}
It's even better to use a more specialized type such as std::vector
instead of a generic smart pointer:
class SomeClass {
public:
SomeClass(int size)
: arr (size)
, someInt = size/10;
{};
private:
std::vector<int> arr;
int someInt;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With