Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

auto

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?

like image 848
x-x Avatar asked Jan 01 '14 07:01

x-x


People also ask

Is Auto a pointer in C++?

The C++ standard provides class template auto_ptr in header file <memory> to deal with this situation. Our auto_ptr is a pointer that serves as owner of the object to which it refers.

Can auto be a reference?

Like pointers, we can also use auto to declare references to other variables.

Does C have reference?

Syntactically, C does not have references as C++ does.

Why do you need references in C++?

The main use of references is acting as function formal parameters to support pass-by-reference. In an reference variable is passed into a function, the function works on the original copy (instead of a clone copy in pass-by-value). Changes inside the function are reflected outside the function.


2 Answers

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 (e.g. 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).

like image 74
Angew is no longer proud of SO Avatar answered Sep 18 '22 19:09

Angew is no longer proud of SO


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.

like image 21
Alok Save Avatar answered Sep 17 '22 19:09

Alok Save