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?

7
  • Presumably you mean MyClass** a = new MyClass*[100](). Yes, the new initializer is a standard feature. I'm just hunting down a duplicate question. Commented Aug 25, 2011 at 7:02
  • Not quite a duplicate because it asks why not (which is incorrect) rather than why: stackoverflow.com/questions/6717246/… ... but close enough. Voting to close. Commented Aug 25, 2011 at 7: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. Commented Aug 25, 2011 at 7:05
  • Duplicate of Do the parentheses after the type name make a difference with new? Commented Aug 25, 2011 at 7:13
  • It not a duplication because this question asks for references to the C++ standard. Commented Aug 25, 2011 at 7:16

1 Answer 1

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.,

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! Exaclty what I was hoping for. I can now default/value/zero initialize with confidence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.