Reputation: 553
I have large array of pointer like:
int *m_Data[1000];
During the destruction, should I go element wise always or is there any better way?
for(int i = 0; i<1000; i++)
delete m_Data[i];
Upvotes: 0
Views: 240
Reputation: 14510
Maybe you can do something like:
int* m_Data = new int[1000];
// ...
delete [] m_Data;
Or:
int m_Data[1000]; // Why to allocate each element dynamically ?
In this case, you don't need to delete any element.
But if you need to allocate each element dynamically one-by-one:
int *m_Data[1000];
for( int i = 0; i < 1000; i++ )
m_Data[i] = new int;
// ...
for( int i = 0; i < 1000; i++ )
delete m_Data[i]; // To need to deallocate each element.
Why don't you use a container like std::vector
?
std::vector<int> m_Data(1000);
Upvotes: 0
Reputation: 42083
int *m_Data[1000];
is an array of 1000
pointers to int
s with automatic storage duration.
You need to call delete
for every new
and delete[]
for every new[]
, i.e. this:
for(int i = 0; i<1000; i++)
delete m_Data[i];
is correct only if you were previously doing something like:
for(int i = 0; i<1000; i++)
m_Data[i] = new int;
"is there any better way?" - Yes:
std::vector<int> m_data(1000);
in this case the memory where elements reside will be automatically freed when the object is destructed (if needed, appropriate destructor will be called for each element).
Upvotes: 3
Reputation: 171127
You could use a smart pointer (such as std::unique_ptr
) instead of raw pointers, and not worry about manual deletion:
std::unique_ptr<int> m_Data[1000];
Upvotes: 3