int foo = 11;
int *p = &foo;
auto pp = p;
auto *ppp = p;
cout << pp << endl;
cout << ppp << endl;
This program will produce the same output for pp
and ppp
, but why? auto
deduces the variable should be int
, so I think the declaration of ppp
is right. But pp
and ppp
have the same value...
Output:
0x61fefc
0x61fefc
In the particular example you show, there is no difference. But imagine you would later on add two const
qualifier like the following:
const auto pp = p;
const auto *ppp = p;
Is it still the same? Turns out that this is identical to
int * const pp = p; // pointer is readonly
const int *ppp = p; // pointer is readonly
because in auto pp = p
, auto
matches int*
as a whole, and const
modifies what's on its left (or what's on its right, if there is nothing on its left). Contrary, in auto *ppp = p
, auto
matches int
, and this is what const
applies to.
Because of this notable difference and because we should use const
variables whenever possible, I'd advise you to always use auto*
when using type deduction for pointer variables. There is no way to const
-qualify the pointer itself instead of the pointee, and if you want to const
-qualify both, this is possible by
const auto * const pppp = p;
which doesn't work without the *
.
There is no difference in auto
and auto *
in this particular case. In case of auto pp = p;
type will be deduced to int *
while in case of auto *ppp = p;
type will be deduced to int
.
For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. [...]
Note that unlike auto
the auto *
will deduce only pointer types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.