Declaring array size for dynamically allocated array with initializer list
Asked Answered
V

1

6

I'm trying to initialize a dynamically declared array with an initializer list but I noticed that I have to provide the array size with GCC or I get an error. Trying the same using MSVC does not cause any errors if the array size is left out. Is providing array size when using an initializer list with dynamic arrays mandatory or not? Is this something implementation-defined which is why it's different for both the compilers?

int *array { new int [3] {0, 1, 2} }; // Works with both MSVC and GCC.
int *array { new int [] {0, 1, 2} }; // Works only with MSVC, not GCC.
Vegetation answered 24/3, 2021 at 12:4 Comment(4)
Clang also accpet both version Demo.Arevalo
(the initializer-list tag refers to std::initializer_list)Turtle
Not 100% and I can't lay out the all the details, but I think g++ is wrong here and the second version should be accepted. This reference also gives double* p = new double[]{1,2,3}; as working example.Socrates
github.com/cplusplus/draft/commit/…Transfix
S
3

This is P1009R2: Array size deduction in new-expressions, which was implemented for C++20.

Bjarne Stroustrup pointed out the following inconsistency in the C++ language:

double a[]{1,2,3}; // this declaration is OK, ...
double* p = new double[]{1,2,3}; // ...but this one is ill-formed!

Jens Maurer provided the explanation why it doesn’t work: For a new-expression, the expression inside the square brackets is currently mandatory according to the C++ grammar. When uniform initialization was introduced for C++11, the rule about deducing the size of the array from the number of initializers was never extended to the new-expression case. Presumably this was simply overlooked. There is no fundamental reason why we cannot make this work [...]

Proposed wording

The reported issue is intended as a defect report with the proposed resolution as follows. The effect of the wording changes should be applied in implementations of all previous versions of C++ where they apply. [...]

From GCC's C++ Standards Support pages we may note that GCC lists P1009R2 as implemented as of GCC 11, and we may verify that GCC 11 have back-ported the implemented to accept the OP's example as well-formed as far back as C++11.

DEMO (GCC 11 / -std=c++11).

Saeger answered 24/3, 2021 at 12:58 Comment(3)
Thanks for your response. I guess my question then is how come it's not working for me if this has already been implemented by GCC. imgur.com/a/LtgDwThVegetation
@MohammadAli See the last part of my answer: this has been implemented for GCC 11; any version prior to this (say, GCC 10), does not contain this feature. As GCC 11 is cutting-edge, your are likely using an older version in your own toolchain.Saeger
Thanks, I mistook that to mean that I need to be using the C++11 standard or later.Vegetation

© 2022 - 2025 — McMap. All rights reserved.