C++11 auto declaration with and without pointer declarator

Henry Barker picture Henry Barker · Jan 1, 2016 · Viewed 9.8k times · Source

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?

Answer

Victor Dyachenko picture Victor Dyachenko · Jan 2, 2016

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()'