What does `new auto` do?

六眼飞鱼酱① 提交于 2019-12-30 03:44:24

问题


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?


回答1:


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 ]




回答2:


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.



来源:https://stackoverflow.com/questions/15935080/what-does-new-auto-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!