Question

I'm suppose to clear and set all elements of a dynamic array to 0. I suppose I could either just do

  • a for loop and set them all to 0 or NULLs, depending on the type
  • or I could just delete it, and reallocate a new array with the same size

In terms of good practice in the long run, should I avoid overusing the delete[] somePointer, and new (if I properly clean it up), or does it not really make any difference?

Was it helpful?

Solution

I think in this case, I'd avoid freeing and reallocating the array's storage. About the best you can hope for is that it'll end up nearly as efficient as just writing to all the elements in the array. In reality, it'll almost always be at least a little slower.

I probably wouldn't just write a loop either though. I'd probably use std::fill or std::fill_n to fill the array with 0, or nullptr (etc.) depending on the type.

OTHER TIPS

You may also want to call memset() to clear the memory. Deleting and reallocating would be more expensive and may lead to fragmentation..

If you want to set all elements of an array with build-in types to 0, delete it, and reallocate a new array won't do it. I'd do something like that:

std::fill(arr,arr+size,0);

To begin with, use std::vector. Furthermore, as long as you don't store pointers (or use RAII with something like std::shared_ptr or std::unique_ptr), you won't have to do anything special.

If you need this array in future delete + new operations will cause performance overhead. Use std::fill or memset function instead.

The proper way is to use a std::vector<>. If you use the clear() method, it will destroy all the elements of the vector while retaining the original capacity so that you can add new elements without a realloction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top