C++中的动态分配数组差异

Dynamic allocation array difference in C++

今天我在 cpp 中遇到了一种新的分配类型,我从未听说过我尝试搜索 google 但没有找到任何相关答案。

long int *a=new long int[N+1]();

我知道long int *a = new long int[N+1];

但是以上两者有什么区别呢?

long int *a=new long int[N+1]();int 的值初始化,因此 a 的每个元素都自动初始化为 0,而在第二个实例中,它只是创建一个大小为 N+1 的数组,这可能包含任何东西。在这种情况下,您必须在使用该变量或调用未定义的行为之前为其赋值。

long int *a = new long int[N+1]();
                               ^^

分配内存,initialize them to the default state 类型(对于内置类型,为零)。这是初始化由 new 分配的对象的标准方法,因此它们不包含不确定的值(虽然没有 UB)。在C++11中,还可以使用大括号:

long int *a = new long int[N+1]{};
                               ^^