Search code examples
c++c++11initializationnew-operatordynamic-memory-allocation

What is the purpose of "{}" in "new int[5]{};"?


If we write something like:

int *arr = new int[5];

In this case, the system dynamically allocates space for 5 elements of type int and returns a pointer to the first element of the sequence.

But, once I saw the following code:

int *arr = new int[5]{};

So, What does mean {} after new operator? What is the purpose of {} in this code?

I have initialized array with my own value, like this:

#include <iostream>

int main()
{
    int* a = new int[5]{1};
    for(int i = 0; i < 5; i++)
        std::cout<< a[i]<<' ';

    delete[] a;
}

Output:

1 0 0 0 0

Only first element print 1. Why?


Solution

  • int *arr = new int[5];
    

    performs a default initialization (which in this case means the elements of arr are uninitialized), while

    int *arr = new int[5]{};
    

    is a value initialization (which in this case means the elements of arr are zero-initialized). See the corresponding rules in the links. Specifically for the latter case, the array will be zero-initialized.

    Anyway, if there is no other good reason, the use of std::vector should be preferred.

    Edit: Concerning your second question: This is due to the initialization rules. You would have to write

    int* a = new int[5]{1, 1, 1, 1, 1 };
    

    The already recommended std::vector supports the syntax you desire:

    #include <iostream>
    #include <vector>
    
    int main()
    {
        std::vector<int> a(5, 1);
        for(int i = 0; i < 5; i++)
            std::cout<< a[i]<<' ';
    }
    

    https://ideone.com/yhgyJg Note however the use of ()-braces here. As vector has an constructor for std::initializer_list, calling vector{ 5, 1} would impose a certain ambiguity, which is resolved by always preferring the initializer_list constructor for {}-initializations if provided. So using { } would cause to create a vector with 2 elements of values 5 and 1, rather than 5 elements of value 1.