“新车”做什么?

时间:2013-04-10 19:48:42

标签: c++ c++11 dynamic-allocation type-deduction

使用new auto时的含义是什么?考虑表达式:

new auto(5)

动态分配对象的类型是什么?它返回的指针的类型是什么?

2 个答案:

答案 0 :(得分:29)

在此上下文中,auto(5)解析为int(5)

您正在从堆中分配新的int,初始化为5

(所以,它正在返回int *

在得到许可的情况下引用Andy Prowl的足智多谋的答案:

根据C ++ 11标准的第5.3.4 / 2段:

  

如果auto类型说明符出现在 new-type-id type-id <的 type-specifier-seq new-expression 的/ em>    new-expression 应包含形式的 new-initializer

( assignment-expression )
     

分配的类型是从new-initializer中推导出来的,如下所示:让e成为赋值表达式    new-initializer 和T是 new-expression new-type-id type-id ,然后分配的类型是类型   在本发明的声明(7.1.6.4)中推导出变量x

T x(e);
     

[示例

new auto(1); // allocated type is int
auto x = new auto(’a’); // allocated type is char, x is of type char*
     

- 结束示例]

答案 1 :(得分:13)

根据C ++ 11标准的第5.3.4 / 2段:

  

如果auto类型说明符出现在 new-type-id type-id <的 type-specifier-seq new-expression 的/ em>    new-expression 应包含形式的 new-initializer

( assignment-expression )
     

分配的类型是从new-initializer中推导出来的,如下所示:让e成为赋值表达式    new-initializer 和T是 new-expression new-type-id type-id ,然后分配的类型是类型   在本发明的声明(7.1.6.4)中推导出变量x

T x(e);
     

[示例

new auto(1); // allocated type is int
auto x = new auto(’a’); // allocated type is char, x is of type char*
     

- 结束示例]

因此,分配对象的类型与本发明声明的推断类型相同:

auto x(5)

哪个是int