Do destructors automatically call delete[]
in C++?
For example:
class A
{
int *num;
A()
{
num=new int[5];
}
~A() {}
}
Do I have to add delete[]
into ~A()
?
Do destructors automatically call delete[]
in C++?
For example:
class A
{
int *num;
A()
{
num=new int[5];
}
~A() {}
}
Do I have to add delete[]
into ~A()
?
They do not. If you want your dynamically allocated int
array to be automatically destroyed when A
is destroyed, using std::vector<int>
(or std::array<int, 5>
if your size is fixed) instead of an int
pointer would probably be a good choice.
No. You need to call delete[] num
in your destructor to avoid memory leaks upon destructing instances of your class A
.
If you want to avoid this manual bookkeeping, you can consider using the following standard containers or wrappers that encapsulate and perform the bookkeeping for you in their destructors:
std::vector< int >
if the size is not fixed and not known at compile time;std::unique_ptr< int[] >
if the size is fixed but not known at compile time;std::array< int, N >
if the size is fixed and known at compile time.