C ++指针数组初始化帮助 [英] C++ pointer array initialization help
问题描述
我在初始化指针数组时遇到麻烦。我发现用gcc c ++(4.6.0)编译是:
MyClass ** a = new MyClass * ;
不总是初始化指针数组。 (大部分时间它给我一个空指针数组,这让我困惑)
MyClass ** a = new MyClass * (100)。
DOES将数组中的所有指针初始化为0(空指针)。
我写的代码意味着可以在Windows / Linux / Mac / BSD平台上移植。这是gcc c ++编译器的一个特殊功能吗?还是标准的C ++?
这个值初始化是标准C ++。
相关的标准是C ++ 98和C ++ 03§5.3.4/ 15。在C ++ 98它是默认初始化,在C + + 03和以后它的值初始化。对你的指针,他们都减少到零初始化。
C ++ 03§5.3.4/ 15:
< blockquote>
–如果 new-initializer 是
()
形式,则该项目是值初始化的(8.5);
在C ++ 0x中,该段落改为引用初始化规则8.5用于直接初始化,其中N3290 FDIS),你发现在§8.5/ 16中有相同的措辞。
hth。,
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?
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.,
这篇关于C ++指针数组初始化帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!