Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `new auto` do?

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?

like image 457
Joseph Mansfield Avatar asked Apr 10 '13 19:04

Joseph Mansfield


2 Answers

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 ]

like image 171
Drew Dormann Avatar answered Oct 23 '22 11:10

Drew Dormann


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.

like image 23
Andy Prowl Avatar answered Oct 23 '22 11:10

Andy Prowl