初始化数组时使用(或不使用)括号

Jek*_*owl 4 c++ arrays initialization

在我正在阅读的c ++代码中,有一些数组初始化为

int *foo = new int[length];
Run Code Online (Sandbox Code Playgroud)

还有一些像

int *foo = new int[length]();
Run Code Online (Sandbox Code Playgroud)

我的快速实验无法检测到这两者之间的任何差异,但它们彼此紧挨着使用.

有没有区别,如果有的话呢?

编辑; 因为有一个断言,第一个应该给出不确定的输出,这是一个显示可疑数量为0的测试;

[s1208067@hobgoblin testCode]$ cat arrayTest.cc
//Test how array initilization works
#include <iostream>
using namespace std;
int main(){
int length = 30;
//Without parenthsis
int * bar = new int[length];
for(int i=0; i<length; i++) cout << bar[0] << " ";

cout << endl;
//With parenthsis 
int * foo = new int[length]();
for(int i=0; i<length; i++) cout << foo[0] << " ";


cout << endl;
return 0;
}
[s1208067@hobgoblin testCode]$ g++ arrayTest.cc
[s1208067@hobgoblin testCode]$ ./a.out
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
[s1208067@hobgoblin testCode]$ 
Run Code Online (Sandbox Code Playgroud)

编辑2; 显然这个测试是有缺陷的,不要相信它 - 看看答案的细节

Bar*_*rry 11

这行默认为 -initializes length int s,也就是说你会获得一堆int具有不确定值的s:

int *foo = new int[length];
Run Code Online (Sandbox Code Playgroud)

这个行 -而不是初始化它们,所以你得到全零:

int *foo = new int[length]();
Run Code Online (Sandbox Code Playgroud)

  • 不确定并不意味着"不是0".这意味着"可以是任何东西".让他们碰巧是0是可以接受的,但不是你应该依赖的东西. (4认同)

cel*_*rel 5

使用括号可以保证数组的所有元素都初始化为0.我只是尝试使用以下代码:

#include <iostream>
using namespace std;

int main(int,char*[]){
    int* foo = new int[8];
    cout << foo << endl;
    for(int i = 0; i < 8; i++)
        foo[i] = i;
    delete[] foo;
    foo = new int[8];
    cout << foo << endl;
    for(int i = 0; i < 8; i++)
        cout << foo[i] << '\t';
    cout << endl;
    delete[] foo;
    foo = new int[8]();
    cout << foo << endl;
    for(int i = 0; i < 8; i++)
        cout << foo[i] << '\t';
    cout << endl;
    delete[] foo;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我编译并运行它时,看起来foo每次都分配在相同的内存位置(尽管你可能不能依赖于此).以上程序的完整输出对我来说是:

0x101300900
0x101300900
0   1   2   3   4   5   6   7   
0x101300900
0   0   0   0   0   0   0   0
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到第二次分配foo没有触及分配的内存,使其处于与第一次分配相同的状态.