9

I had trouble with initializing arrays of pointers. What I found out compiling with gcc c++ (4.6.0) is:

MyClass** a = new MyClass*[100];

Does not always initalize the array of pointers. (most of the time it did give me an array of null pointers which confused me)

MyClass** a = new MyClass*[100]();

DOES initialize all the pointers in the array to 0 (null pointer).

The code I'm writing is meant to be be portable across Windows/Linux/Mac/BSD platforms. Is this a special feature of the gcc c++ compiler? or is it standard C++? Where in the standard does it says so?

john
  • 85,011
  • 4
  • 57
  • 81
Roderick Taylor
  • 202
  • 1
  • 8
  • Presumably you mean `MyClass** a = new MyClass*[100]()`. Yes, the `new` initializer is a standard feature. I'm just hunting down a duplicate question. – CB Bailey Aug 25 '11 at 07:02
  • Not quite a duplicate because it asks why not (which is incorrect) rather than why: http://stackoverflow.com/questions/6717246/no-array-allocated-using-new-can-have-an-initializer ... but close enough. Voting to close. – CB Bailey Aug 25 '11 at 07:04
  • The first version returns uninitialized memory, which of course *can* be NULL (zero) if it is previously unused. Most OSs clear out memory allocated to a process, for security reasons. – Bo Persson Aug 25 '11 at 07:05
  • Duplicate of [Do the parentheses after the type name make a difference with new?](http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new) – James McNellis Aug 25 '11 at 07:13
  • It not a duplication because this question asks for references to the C++ standard. – Cheers and hth. - Alf Aug 25 '11 at 07:16
  • Thanks John for fixit it and Charles for pointing out the duplicate. – Roderick Taylor Aug 25 '11 at 07:20
  • This is not a duplicate, nor a precise opposite. If anything, it's more an extension to those questions (they both ask why or how, this is "what does the spec say given the why and how?"). – ssube Aug 25 '11 at 09:05

1 Answers1

5

This value-initialization is standard C++.

The relevant standardeese is in C++98 and C++03 §5.3.4/15. In C++98 it was default-initialization, in C++03 and later it's value initialization. For your pointers they both reduce to zero-initialization.

C++03 §5.3.4/15:

– If the new-initializer is of the form (), the item is value-initialized (8.5);

In C++0x that paragraph instead refers to “the initialization rules of 8.5 for direct-initialization”, where in N3290 (the FDIS) you find about the same wording in §8.5/16.

Cheers & hth.,

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331