C ++ proper new use?

int* array = new int[ 10 ]( );

Is this the correct use of the new operator? As far as I know, the previous code initializes each element of the array to 0.

int* array = new int[ 10 ];

The second line of code just initializes the array, but doesn't set the value to zero?

+4
source share
1 answer

The correct way to use the new operator depends on what you are going to do after allocating memory.

int* array = new int[10](); will disable the allocated memory as it starts the int initializer for each int in the array.

int* array = new int[10]; , int , , new. , , , , , , , / .

, . , , , . , . .

- . 0 , , , . , , , , .

, , , std::vector<int>, , , , ( / ), . , , - , .

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

, std::vector, , , .

+2

Source: https://habr.com/ru/post/1524033/


All Articles