Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 auto declaration with and without pointer declarator

What's the difference between the types of bar1 and bar2?

int foo = 10;
auto bar1 = &foo;
auto *bar2 = &foo;

If both bar1 and bar2 are int*, does it makes sense to write the pointer declarator (*) in the bar2 declaration?

like image 522
Henry Barker Avatar asked Jan 01 '16 21:01

Henry Barker


People also ask

Does C++11 have auto?

C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.

What is Auto in C++11?

The auto keyword directs the compiler to use the initialization expression of a declared variable, or lambda expression parameter, to deduce its type.

Is Auto a pointer in C++?

auto_ptr is a class template that was available in previous versions of the C++ standard library (declared in the <memory> header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class.

What does the declaration of a pointer look like C++?

Note that the asterisk ( * ) used when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator seen a bit earlier, but which is also written with an asterisk ( * ).


2 Answers

The declarations are exactly equivalent. auto works (almost) the same as template type deduction. Putting the star explicitly makes the code a bit easier to read, and makes the programmer aware that bar2 is a pointer.

like image 56
vsoftco Avatar answered Oct 19 '22 20:10

vsoftco


Using auto * "documents intention". And auto *p = expr; can be deduced correctly only if expr returns pointer. Example:

int f();

auto q = f(); // OK

auto *p = f(); // error: unable to deduce 'auto*' from 'f()'
like image 58
Victor Dyachenko Avatar answered Oct 19 '22 19:10

Victor Dyachenko