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?
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.
Like pointers, we can also use auto to declare references to other variables.
Syntactically, C does not have references as C++ does.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With