Search code examples
c++c++11auto

Difference between auto and auto* when storing a pointer


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

Solution

  • 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.