Reputation: 1739
If I want to delete a dynamically allocated array of primitive type values:
int *it = new int[10]
do I just put delete [] it
in the destructor to take care of releasing memory properly?
OR
Realizing that, as a pointer is a primitive type, does deleting a dynamically allocated array involve doing something like this in the destructor:
for (size_t idx = 0; idx != 5; ++idx)
delete sp[idx];
delete[] sp;
I'm rather confused about this as I am having a lot of memory related errors in my program.
Upvotes: 1
Views: 2045
Reputation: 168626
If you are going to use new
and delete
, the general rule to follow is this: Use exactly as many delete
s as you did new
s.
In your case, you invoked new[]
only once. You should inovke delete[]
only once.
As an aside, if you ever store a pointer in a member variable, please consider the Rule of Three.
I say "If you are going to use new
and delete
", because you often shouldn't. Using RAII techniques, and standard containers, it is entirely possible to write perfectly useful programs that never directly invoke new
or delete
.
If you are trying to maintain an array of int
s, use std::vector
:
class MyClass {
std::vector<int> it;
void SomeFun() { it.resize(10); }
};
Then, in your destructor, do nothing. Vectors disappear with no help from you at all.
Upvotes: 2
Reputation: 121971
If you have:
int* it = new int[10];
the correct way to delete
it is:
delete[] it;
If you have a member variable of this type you need to implement a copy constructor and assignment operator as the default versions of these are not sufficient or make the class uncopyable.
As this is C++ I would suggest using std::vector<int>
instead as this will handle the memory management for you.
Upvotes: 5