23

当我使用它是什么意思new auto?考虑表达式:

new auto(5)

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

4

2 回答 2

30

在这种情况下,auto(5)解析为int(5)

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

(所以,它返回一个int *

经许可引用 Andy Prowl 的足智多谋的回答:

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

如果autotype-specifier 出现在new-type-idtype-specifier-seqnew-expression的type-id中,则 new-expression应包含以下形式的new-initializer

( assignment-expression )

分配的类型由 new-initializer 推导如下: 设 为 new-initializereassignment-expression,T 为 new-expression 的new -type-idtype-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*

—<em>结束示例]

于 2013-04-10T19:53:16.970 回答
13

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

如果autotype-specifier 出现在new-type-idtype-specifier-seqnew-expression的type-id中,则 new-expression应包含以下形式的new-initializer

( assignment-expression )

分配的类型由 new-initializer 推导如下: 设 为 new-initializereassignment-expression,T 为 new-expression 的new -type-idtype-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*

—<em>结束示例]

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

auto x(5)

这是int

于 2013-04-10T19:56:19.303 回答