While trying to answer this question I found that the code int* p = new int[10]();
compiles fine with VC9 compiler and initializes the integers to 0. So my questions are:
new int;
or new int();
? Does the latter guarantee to initialize the variable?For dynamically allocated memory like “int *p = new int[10]”, it is the programmer's responsibility to deallocate memory when no longer needed. If the programmer doesn't deallocate memory, it causes a memory leak (memory is not deallocated until the program terminates).
*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".
The first line allocates a single int and initializes it to 100 . Think of the int(100) as a constructor call. Since this is a scalar allocation, trying to access arr[1] or to free the memory using delete[] would lead to undefined behaviour. @SteveJessop Or, as NPE suggested, new (100) int .
int a[10]; refers to 10 cells of integers allocated in memory. int *b = a; is equivalent to int *b = &a[0]; and means that b points to the first cell of a to be precise.
First of all is this valid C++ or is it a microsoft extension?
It is valid in C++, the relevant part of the standard is 5.3.4, with the first paragraph containing the grammar
Is it guaranteed to initialize all the elements of the array?
Yes. Paragraph 5.3.4/15 states that
A new-expression that creates an object of type T initializes that object as follows:
...
- If the new-initializer is of the form (), the item is value-initialized (8.5)
where value initialized for POD means zero-initialize.
Also, is there any difference if I do new int; or new int();? Does the latter guarantee to initialize the variable?
Yes they are different. According with the quote above new int()
will zero-initialize the integer. In a previous block of the same paragraph:
If the new-initializer is omitted:
If T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default-initialized (8.5). If T is a const-qualified type, the underlying class type shall have a user-declared default constructor.
Otherwise, the object created has indeterminate value. If T is a const-qualified type, or a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of const-qualified type, the program is ill-formed;
so new int
will not initialize the memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With