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

标签 c++ new-operator

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

相关文章:

c++ - 为什么使用带有 C++ 'vector' 的新调用?

c++ - 从 C++ 中的函数返回 2D 字符数组并打印它

c++ - 覆盖后调用原始继承函数

javascript - 如何将 Canvas 像素数组传递给 C++ 代码并将其保存为 jpeg?

c++ - 为什么在链表中使用指向结构的指针而不是常规的结构类型变量?

c++ - 找到可能的最大内存分配

javascript - 构造函数可以返回什么值来避免返回 this?

c++ - C 编程 - 堆栈和堆数组声明

C++:优化列表

c++ - 为什么需要仅在全局命名空间中包含 vector (以及其他 header )?