Memory management with HEAP arrays
If i create a heap array inside a loop, do i have to delete it at the end of each loop before i reinitialize it at the beginning of the loop again or will reinitializing the exact same thing again simply overwrite the 开发者_如何学JAVAold array and i can just skip the delete command?
Do you mean something like this?
for (int i = 0; i < 5; i++) {
char *array = new char[10];
// ...
delete[] array;
}
In that case: yes, you do need to delete the array.
If you had written something like this instead,
char *array = 0;
for (int i = 0; i < 5; i++) {
if (!array) array = new char[10];
// ...
}
delete[] array;
then no, you can reuse the array across multiple iterations of the loop.
Adding to ephemient's answer: Why are you thinking about re-initializing the array inside of the loop?
Your question would be appropriate if every iteration of your loop needs to do both of these steps:
1) Insert data into the array.
2) Do something with the data that's been filled into the array
If this doesn't sound like what your code needs to do, then the answer to your question should probably be: Don't create or delete the array inside the loop. Create the array before the loop, and delete it afterwards.
(In my experience, it's rare to find a case where steps 1) and 2) are done within the same loop.)
精彩评论