3 ms·
> 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
by moregrist 10mo ago
> 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.
- nly 10mo agoImplicit type conversions blow your reasoning out of the water imho The number of times someone has assigned a return type to int, triggering an implicit conversion. I'll take "unintelligible compile errors" any day over subtle runtime bugs.
- moregrist 10mo agoI guess it depends on your code base and whether you find more bugs from return values implicitly changed with the usual arithmetic conversions or from other aspects of C++. I have not encountered that many issues with the usual arithmetic conversions on return types, at least not in a way that auto would prevent. Clearly your experience is different. Perhaps we can both agree that it would be nice to force explicit numerical conversions? You can _almost_ get this by wrapping the arithmetic types in a union with only one member, but that may incur a performance hit, which is often not a viable trade off. > I'll take "unintelligible compile errors" any day over subtle runtime bugs. As would the rest of us, but that’s not the choice that auto gives you. auto can cause subtle bugs with class types. It doesn’t necessarily protect you from integer narrowing, either, as you eventually have to give the compiler a concrete non-auto type.