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
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
const auto start = std::chrono::steady_clock::now();
do_some_work(size);
const auto end = std::chrono::steady_clock::now();
const std::chrono::duration<double> diff = end - start;
std::cout << "diff = " << diff << "; size = " << size << '\n';
Looking up the (current standard's) return type of std::chrono::steady_clock::now() and spelling it out would serve no purpose here. TP start = TP::clock::now();
do_some_work(size);
TP end = TP::clock::now();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.
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.
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.
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.
auto var = FunctionCall(...);
Then, in the IDE, hover over auto to show what the actual type is, and then replace auto with that type. Useful when the type is complicated, or is in some nested namespace.
Really? I've never experienced this myself.