What does `new auto` do?

2019-02-07 22:26发布

What does it mean when I use new auto? Consider the expression:

new auto(5)

What is the type of the dynamically allocated object? What is the type of the pointer it returns?

2条回答
萌系小妹纸
2楼-- · 2019-02-07 22:35

In this context, auto(5) resolves to int(5).

You are allocating a new int from the heap, initialized to 5.

(So, it's returning an int *)

Quoting Andy Prowl's resourceful answer, with permission:

Per Paragraph 5.3.4/2 of the C++11 Standard:

If the auto type-specifier appears in the type-specifier-seq of a new-type-id or type-id of a new-expression, the new-expression shall contain a new-initializer of the form

( assignment-expression )

The allocated type is deduced from the new-initializer as follows: Let e be the assignment-expression in the new-initializer and T be the new-type-id or type-id of the new-expression, then the allocated type is the type deduced for the variable x in the invented declaration (7.1.6.4):

T x(e);

[ Example:

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

end example ]

查看更多
放荡不羁爱自由
3楼-- · 2019-02-07 22:35

Per Paragraph 5.3.4/2 of the C++11 Standard:

If the auto type-specifier appears in the type-specifier-seq of a new-type-id or type-id of a new-expression, the new-expression shall contain a new-initializer of the form

( assignment-expression )

The allocated type is deduced from the new-initializer as follows: Let e be the assignment-expression in the new-initializer and T be the new-type-id or type-id of the new-expression, then the allocated type is the type deduced for the variable x in the invented declaration (7.1.6.4):

T x(e);

[ Example:

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

end example ]

Therefore, the type of the allocated object is identical to the deduced type of the invented declaration:

auto x(5)

Which is int.

查看更多
登录 后发表回答