简体   繁体   中英

If function f() returns a pointer, which is correct: auto* v = f() OR auto v = f()?

I use the c++11 auto keyword just about everywhere. I'm not sure if I'm using it correctly in this case though. Consider the following trivial example: ( http://ideone.com/TxLJlx )

#include <iostream>

const char* f()
{
    return "Hello";
}

int main()
{
    auto  s1 = f();
    auto* s2 = f();

    std::cout << s1 << std::endl;
    std::cout << s2 << std::endl;

    return 0;
}

Both auto and auto* seem to work and appear to do the same thing. Is this assumption wrong?

Why do both give the same results?

Which is the correct use of auto in this case?

They both mean the same - the type will be const char* in both cases. However, using auto * stresses (and self-documents) the fact that f() returns a pointer. And it would signal an error if the function is later changed to return something else (eg std::string in this case).

Which to use is primarily a matter of style. If the code relies heavily on f() returning a pointer, or you feel the need to make this obvious, use auto* . Otherwise, just use auto and be done with it.

Note that the case is different when returning references. Those are dropped by the auto deduction, so if you need to take a returned reference as a reference, you have to use auto & (or use auto && to get a universal reference).

auto  s1 = f();

You use auto so that compiler can deduce the appropriate type whenever it can without being bothered about doing so yourself. whether it is a pointer or not is take care of because it is a part of the type so you don't have to be worried about that.

auto completes any type for you, if you specified the pointer( * ) all its left is to complete is the char (or will cause an error if no completion available, for example if f() return a plain char ).

You should bother with the pointer, just use auto .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM