Reputation: 229
Class name{
private:
int *ptr=new ptr[10];
public:
//do some thing
~name(){
delete ptr; //should I do this?
}
};
After creating this class, if I go out of the scope, should I write a destructor that automatically handles this dynamically allocated integer array?
Upvotes: 0
Views: 1581
Reputation: 598414
Yes, you must free any memory you allocate. But memory allocated with new[]
must be freed using delete[]
, not delete
.
class name {
private:
int *ptr = new ptr[10];
public:
//...
~name() {
delete[] ptr;
}
};
What you should do is use a std::vector
or std::array
instead, and let it handle the memory management for you.
class name {
private:
std::vector<int> ptr{10};
public:
//...
};
class name {
private:
std::array<int, 10> ptr;
public:
//...
};
Upvotes: 2