Initializer list for dynamic arrays? Initializer list for dynamic arrays? arrays arrays

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.


No, you cannot do that.

I think C++ doesn't allow this because allowing such thing doesn't add any nice-to-have feature to the language. In other words, what would be the point of dynamic array if you use a static initializer to initialize it?

The point of dynamic array is to create an array of size N which is known at runtime, depending on the actual need. That is, the code

int *p = new int[2]; 

makes less sense to me than the following:

int *p = new int[N]; //N is known at runtime

If that is so, then how can you provide the number of elements in the static initializer because N isn't known until runtime?

Lets assume that you're allowed to write this:

int *p = new int[2] {10,20}; //pretend this!

But what big advantage are you getting by writing this? Nothing. Its almost same as:

int a[] = {10,20};

The real advantage would be when you're allowed to write that for arrays of N elements. But then the problem is this:

 int *p = new int[N] {10,20, ... /*Oops, no idea how far we can go? N is not known!*/ };


No, you will have to create the elements dynamically.

Alternatively, you can use a local array and copy its elements over those of the dynamically allocated array:

int main() {   int _detail[] = { 1, 2 };   int * ptr = new int[2];   std::copy( _detail, _detail+(sizeof detail / sizeof *detail), ptr );   delete [] ptr;}

In the limited version of setting all elements to 0, you can use an extra pair of parenthesis in the new call:

int * ptr = new int[2]();  // will value initialize all elements

But you seem to be looking for a different thing.