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

Using (or not using) parentheses when initializing an array

本文关键字:括号 数组 初始化      更新时间:2023-10-16

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

int *foo = new int[length];

还有一些像

int *foo = new int[length]();

我的快速实验无法检测出这两者之间的任何区别,但它们是紧挨着使用的。

有区别吗?如果有什么区别?

编辑;因为有一个断言,第一个应该给出不确定的输出,这里是一个显示可疑数字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]$ 

编辑2;显然这个测试是有缺陷的,不要相信它-查看答案以了解详细信息

此行默认-初始化length ints,也就是说,您将获得一堆值不确定的ints:

int *foo = new int[length];

这一行-初始化它们,所以你得到的都是零:

int *foo = new int[length]();

使用括号可以确保数组的所有元素都初始化为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;
}

当我编译并运行它时,看起来foo每次都被分配在同一个内存位置(尽管你可能不能依赖它(。对我来说,上述程序的全部输出是:

0x101300900
0x101300900
0   1   2   3   4   5   6   7   
0x101300900
0   0   0   0   0   0   0   0

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