gpt4 book ai didi

c++ - C++中new int()和new int {}的区别

转载 作者:行者123 更新时间:2023-11-30 02:22:59 25 4
gpt4 key购买 nike

我知道 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;

最佳答案

你的输出是这样的:

*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

引用:http://en.cppreference.com/w/cpp/language/initialization

关于c++ - C++中new int()和new int {}的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46639140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com