Initializer list for dynamic arrays?

At the time the OP posted this question, C++11 support may not have been very prevalent yet, which is why the accepted answer says this is not possible. However, initializing a dynamic array with an explicit initializer list should now be supported in all major C++ compilers.

The syntax new int[3] {1, 2, 3} was standardized in C++11. Quoting the new expression page on cppreference.com:

The object created by a new-expression is initialized according to the following rules:

If type is an array type, an array of objects is initialized:

If initializer is a brace-enclosed list of arguments, the array is aggregate-initialized. (since C++11)

So, given the OP’s example, the following is perfectly legal when using C++11 or newer:

foo * foo_array = new foo[2] { nullptr, nullptr };

Note that by providing pointers in the initializer list, we’re actually coaxing the compiler to apply the foo(void * ptr) constructor (rather than the default constructor), which was the desired behavior.

Leave a Comment