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?
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.
The auto keyword directs the compiler to use the initialization expression of a declared variable, or lambda expression parameter, to deduce its type.
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.
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 ( * ).
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.
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()'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With