C++11 features the new auto
type declaration, allowing you to work with an object without ever knowing its actual type.
I use only strongly typed languages - C++, Delphi (Object Pascal), Go, etc and I feel uncomfortable (guilty?) using auto
, (or for example the short variable declaration - x:=1
- in Go.) It feels like a hack to me - I use strongly typed languages because they ensure that you know what type you're using. (With the exception of the abuse of untyped pointers.) Although certainly I appreciate the benefits: Proper type names involving iterators, templates, smart pointers etc can get very lengthy and a bit difficult to determine and declare explicitly, or to parse when reading. Granted, once you know the proper type name, you can "typedef it", but sometimes getting it right the first time is time consuming and not always so easy.
Or, imagine you that inherit a large, complex project that you need to modify, and every variable possible in that project is declared using auto
- you're going to have to do a lot more work to understand that code-base than if everything was declared using explicit types.
So, what are some guidelines on when to use auto
and when to sweat it out with full and proper type names? I am currently reading Stroustrup's A Tour of C++ and he himself there in Chapter 1 advocates using auto
in situations when you know auto
will "get it right":
We use auto where we don’t have a specific reason to mention the type explicitly. “Specific reasons” include:
• The definition is in a large scope where we want to make the type clearly visible to readers of our code.
• We want to be explicit about a variable’s range or precision (e.g., double rather than float).
In the Advice section of Chapter 1 there he also warns:
-Prefer the {}-initializer syntax for declarations with a named type;
-Prefer the = syntax for the initialization in declarations using auto;
This, because default initialization {}
could result in an incorrect type initialization.
Still, I feel a bit uncomfortable using auto
.
Can anyone perhaps give me some additional guidelines about the use of auto
, and/or debunk my impression that auto
is a hack of sorts and really should be avoided in favor of determining the proper type and then using atypedef
?
auto
. So it's impossible for us to determine whether your reasons are justified or not.auto
/var
or not./strongly/statically/g
, the former means absolutely nothing.