On 22.01.2019 15:43, Juha Nieminen wrote:
> Alf P. Steinbach <
alf.p.stein...@gmail.com> wrote:
>> A simple remedy is to just use an ordinary `new[]`-expression, or
>> `make_unique`.
>
> Doesn't the ordinary new[] operator default-initialize the array elements?
It does, yes, but for POD that means doing nothing.
C++17 §8.3.4/1 “If the new-initializer is omitted, the object is
default-initialized”, which goes on to note that if the results in
nothing being done, then the object has an indeterminate value.
> I have found conflicting information on this online (with some claiming
> that it doesn't default-initialize basic integral types, while others
> claim it always does), so I really don't know if that's the case.
Either claim would essentially be correct, because
default-initialization of an object of basic integral type (such as each
item in the array) does nothing.
In C++17 this is covered by the definition of default-initialization in
$11.6/7, where for the case of not a class type and not an array either,
$11.6/7.3 simply says “no initialization is performed”.
So, since
new T[314]
default-initializes, for a POD T it's not guaranteed to zero the memory,
or anything: it just yields indeterminate values. That's the same lack
of guarantee as with calling the allocation function directly.
Since indeterminate value includes a possible value 0 an implementation
might choose to “helpfully” let the allocation function clear the
memory, possibly with some option to specify or avoid that, but I found
no such option for g++ now.
However,
new T[314]()
is guaranteed to value-initialize the array items, which for POD array
items results in a zeroing. In C++17 the value initialization is
specified indirectly by §8.3.4/2, that when there is an initializer “the
new-initializer is interpreted according to the initialization rules of
11.6 for direct-initialization”, where §11.6/17.4 says “If the
initializer is (), the object is value-initialized”.
Cheers!,
- Alf