C++ proper new usage?

181 views Asked by At
int* array = new int[ 10 ]( );

Is this the proper usage of the new operator? To my knowledge the previous code will initialize each element in the array to 0.

int* array = new int[ 10 ];

Does the second line of code just initialize the array, but not set the values to zero?

1

There are 1 answers

0
PolyMesh On

The proper way to use the new operator depends on whatever you are going to do next after allocating the memory.

int* array = new int[10](); will zero out the memory that you are allocating because it is running the int initializer for each int in the array.

int* array = new int[10]; will not initialize the memory, so the value of each int in the array will be whatever the value was at the memory address you get from new. It might be zeros if you're lucky, but more than likely it's probably garbage left there from some other memory request/release.

Generally speaking, you need to treat uninitialized variables as garbage values and not use them before assigning them a value. That is unless you are using it as entropy in a random number generator, but even then it might not be random enough if the memory happens to be too clean. Another rare use case might be snooping on what another program left in memory after closing. Both of these examples are exceptions to the rule.

Usually the best reason NOT to initialize is speed. Setting each item in the array to 0 has a speed cost to it, and although it might be small, it might be noticeable if your array is huge or you execute this code frequently. This is for when you KNOW you will be setting those values before you use them, you can save yourself the cost of initializing them needlessly.

Now having said all that, I also agree with the comments that std::vector<int> is usually the better way to go, if nothing more than for the advantage that you don't have to worry about memory leaks (which can cost a lot of debug/development time and should not be underestimated) and you also get a lot of benefits. Not to mention you can do all the same things with vectors that you could a regular array - this is because vectors allocate contiguous memory.

std::vector<int> safeArray(10);
int* array = &safeArray[0]; // array now points to the 0th element in safeArray

One thing you lose with std::vector is that you no longer have a choice on whether or not you initialize.