C++中new int()和new int {}的区别
Difference between new int () and new int { } in C++
我知道new int()
和new int(10)
的区别。在第一种情况下,0 被分配,在第二种情况下,10 被分配给新创建的 int。但是new int {}
之间是什么?我们使用 {} 进行数组初始化,如 new a[]{4,5,6}
。但是对于单个变量,在初始化时使用大括号是什么意思?
/* Combined usage and initialized to 0*/
int *ptr2 = new int();
cout<<"*ptr2 = "<<*ptr2<<endl;
/* Allocated memory can be initialized to specific value */
int*ptr3 = new int(5);
cout<<"*ptr3 = "<<*ptr3<<endl;
int* ptr5 = new int{500};
cout<<"*ptr5 = "<<*ptr5<<endl;
在 int
的特定情况下(或任何整数类型,例如 long
),new int(10)
和 new int{10}
之间没有区别。
详细了解 variable initialization。
你的输出是这样的:
*ptr2 = 0
*ptr3 = 5
*ptr5 = 500
你的情况没有区别。
但总的来说:
( expression-list ) (1)
= expression (2)
{ initializer-list } (3)
1) comma-separated list of arbitrary expressions and braced-init-lists
in parentheses
2) the equals sign followed by an expression
3) braced-init-list: possibly empty, comma-separated list of
expressions and other braced-init-lists
我知道new int()
和new int(10)
的区别。在第一种情况下,0 被分配,在第二种情况下,10 被分配给新创建的 int。但是new int {}
之间是什么?我们使用 {} 进行数组初始化,如 new a[]{4,5,6}
。但是对于单个变量,在初始化时使用大括号是什么意思?
/* Combined usage and initialized to 0*/
int *ptr2 = new int();
cout<<"*ptr2 = "<<*ptr2<<endl;
/* Allocated memory can be initialized to specific value */
int*ptr3 = new int(5);
cout<<"*ptr3 = "<<*ptr3<<endl;
int* ptr5 = new int{500};
cout<<"*ptr5 = "<<*ptr5<<endl;
在 int
的特定情况下(或任何整数类型,例如 long
),new int(10)
和 new int{10}
之间没有区别。
详细了解 variable initialization。
你的输出是这样的:
*ptr2 = 0
*ptr3 = 5
*ptr5 = 500
你的情况没有区别。
但总的来说:
( expression-list ) (1)
= expression (2)
{ initializer-list } (3)
1) comma-separated list of arbitrary expressions and braced-init-lists in parentheses
2) the equals sign followed by an expression
3) braced-init-list: possibly empty, comma-separated list of expressions and other braced-init-lists