初始化数组时使用(或不使用)括号
Using (or not using) parentheses when initializing an array
在我正在阅读的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
int
s,也就是说,您将获得一堆值不确定的int
s:
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
的第二次分配没有接触到分配的内存,使其处于与第一次分配时相同的状态。
相关文章:
- C++20 从括号中的值列表初始化聚合,不支持内部数组
- 如何在使用模板的函数调用的大括号表达式中推导多维数组的大小
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 数组 c++ 中的大括号初始化
- 如何将大括号初始值设定项用于动态大小数组和新数组?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 用另一个 constexpr 数组对成员数组进行大括号初始化
- 双指针 (int**) 和双括号,用于从 2D 数组中获取值
- 为什么在使用堆叠 std::array 声明多维数组时需要"双括号"?
- 为什么C CHAR数据类型3D数组通过参数第一个括号为空白
- 从大括号括起来的列表进行数组初始化C++很奇怪
- 错误C7034:无法使用括号初始化器初始化数组
- C++ - 与号+括号数组语法
- 大括号之间的自定义类型初始化数组
- 警告:数组"字母表"由括号字符串文本初始化
- 如何访问带有多个括号的一维数组以提高可读性
- std::数组聚合初始化需要大量的大括号
- 如果需要零数组,用一对花括号初始化std::数组是否正确
- 括号中的 C 数组索引
- 是否可以将文本的大括号数组作为构造函数中的参数发送