Usually codebases disallow auto because without an IDE it's difficult to see the type. I think this reduces the cognitive load of C++ a bit. The only time it is allowed is getting iterators types from STL containers.
I remember fretting about these rules when reading Scott Meyer's Effective C++11, and then later to realize it's better not to use auto at all. Explicit types are good types
> Usually codebases disallow auto because without an IDE it's difficult to see the type. I think this reduces the cognitive load of C++ a bit. The only time it is allowed is getting iterators types from STL containers.
Strong agree here. It's not just because it reduces cognitive load, it's because explicit types allows and requires the compiler to check your work.
Even if this isn't a problem when the code is first written, it's a nice safety belt for when someone does a refactor 6-12 months (or even 5+ years) down the road that changes a type. With auto, in the best case you might end up with 100+ lines of unintelligible error messages. In the worst case the compiler just trudges on and you have some subtle semantic breakage that takes weeks or months to chase down.
The only exceptions I like are iterators (whose types are a pita in C++), and lambda types, where you sometimes don't have any other good options because you can't afford the dynamic dispatch of std::function.
There are unspeakble types, such as lambdas, that are not exactly easy to handle without "auto". How a variable containing local lambda with captures will look without "auto"?
I know Google’s styleguide discourages auto, but other C++ places I’ve worked weren’t scared of it. The type deduction rules usually do what I expect, unless I have a weird pre-C++11 proxy type that somehow hasn’t been updated in the last 14 years.
I agree that auto should be used as little as possible. There are good uses, though. It is okay to use when the type is trivially inferred from the code. What is auto in "auto ptr = std::make_shared<MyNiceType>();". Everybody who knows any C++ knows. Also, lambdas do not have a type that can be written down, so it is okay to use auto for them.
I also prefer not to use auto when getting iterators from STL containers. Often I use a typedef for most STL containers that I use. The one can write MyNiceContainerType::iterator.
Hard disagree. There are times when nobody, really nobody, cares about a given type. See the example of std::chrono::steady_clock::now over at cppreference.com. There you have
Looking up the (current standard's) return type of std::chrono::steady_clock::now() and spelling it out would serve no purpose here.