13

Is there a functional difference between the following? Is there any reason to prefer one over the other?

auto p = new C();

and

auto* p = new C();
2
  • 2
    No differences whatsoever, use whichever you prefer. However, if the expression being deduced is not of pointer type when auto* is used, then you'll get a compiler error while in the former case you won't.
    – David G
    Mar 24, 2016 at 23:35
  • auto will add the pointer for you. It's the same
    – DimChtz
    Mar 24, 2016 at 23:36

1 Answer 1

15

In the snippet you have given there is no difference. The compiler will deduce that p will be a pointer to C, either way.

In a more general case, there is a difference. For example;

auto *p = func();

auto p = func();

The first form will cause an error message if func() returns something that is not a pointer, but the second will not. This is sometimes useful (e.g. in templated code) where there is a need to enforce a requirement that func() return a pointer rather than (say) an int. [Although, admittedly, there are more clear and powerful ways to enforce such a requirement, such as traits].

As noted by John Ilacqua in comments, there are further benefits of using auto *, including const qualification of the pointer. For example, const auto * p = func() specifies that p points at something that is const or const auto * const p = func() specifies that p points at something that is const AND p cannot be reassigned. Such qualification will also result in diagnostics if const qualifiers on the return type of func() are incompatible.

1
  • 6
    I would suggest that there is an additional benefit to using auto* - it allows you to declare that the pointer is const if you so desire: const auto* const p = func(); Mar 5, 2018 at 0:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.