1

I am trying to understand the rules that regulate memory initialization in new int and new int(). Some people suggest that the former leaves memory uninitialized, whereas the latter will initialize it to zero (e.g. this question). However, I cannot find these rules in the documentation. C++ reference says the following:

For non-array type, the single object is constructed in the acquired memory area.

  • If initializer is absent, the object is default-initialized.
  • If initializer is a parenthesized list of arguments, the object is direct-initialized.
  • If initializer is a brace-enclosed list of arguments, the object is list-initialized.

First, it's not quite clear from these statements whether new int() corresponds to the absent initializer or the initializer with a parenthesized list of arguments. Is an empty pair of parentheses still a parenthesized list?

Second, neither default-initialization nor direct-initialization seem to initialize the value to zero in this case. Default initialization leaves the value uninitialized unless it's a class type. Direct initialization does not seem to be applicable as it requires a nonempty parenthesized list of expressions or braced-init-lists.

Interestingly enough, for array types C++ reference clearly and explicitly states that

If initializer is an empty pair of parentheses, each element is value-initialized.

But where are the rules for non-array types with an empty parenthesized list?

mentalmushroom
  • 2,261
  • 1
  • 26
  • 34
  • `new int()` is counts as "parenthesized list of arguments". It does the same initialization to the memory that `auto i = int();` does... A brace enclosed list would be `new int{}`, which has the same effect for type `int`... – fabian Apr 02 '23 at 08:25
  • @paddy I see, value initialization indeed specifies that. Still, somewhat strange that the documentation for new doesn't even mention value initialization among possible options for non-array types. – mentalmushroom Apr 02 '23 at 09:50
  • It says right there in the "Construction" section: _"If initializer is an empty pair of parentheses, each element is value-initialized."_ – paddy Apr 02 '23 at 09:58
  • @paddy That's about array types. I was talking about non-array types. – mentalmushroom Apr 02 '23 at 10:00

1 Answers1

2

But where are the rules for non-array types with an empty parenthesized list?

The rule for new T() can be seen at value initialization documentation:

new T ()  (2)     

Value initialization is performed in these situations:

2,6) when an object with dynamic storage duration is created by a new-expression with the initializer consisting of an empty pair of parentheses or braces (since C++11);

(emphasis mine)

This means that new int() uses value initialization.

Jason
  • 36,170
  • 5
  • 26
  • 60