4 ms·
It's funny, none of his examples point out the simplest problem with "auto": it is not a reference and in fact it strips references out. Therefore, if somethin
by makecheck 11y ago
It's funny, none of his examples point out the simplest problem with "auto": it is not a reference and in fact it strips references out. Therefore, if something non-trivial is being used, most programmers might say "auto var = value" (as his examples do) and incur costs or unexpected behavior that would not be seen with the expression "const auto &var = value".
And that is the real problem with C++: its defaults are downright stupid in many situations and the only real way to produce code without pitfalls is to know all the tricks.
I don't think "auto" is meant to be overused. It makes no sense to use it in place of an "int". It is fantastic for eliminating redundancy in expressions where the type already exists in multiple places and the "auto" serves to eliminate one of the pointless type expressions. It is also good when using objects that you really shouldn't depend on the types of, such as lambdas and possibly magical object types in certain template libraries that exist primarily as a means to an end.
Current compilers appear to generate very confusing error messages for "auto" variables, too. For instance, if you've forgotten to include "Xyz.h" which defines the class "Xyz", and the type of your "auto x = f()" happens to be Xyz, and class Xyz hasn't been used anywhere else in your code, it may take quite awhile to figure out that this is the problem. Therefore, resist the urge to blindly remove all type information from your code; keep as many hints around as you can.
- qMopey 11y agoGood point! OP here, and this was one of the worst things (imo) when dealing with auto. Why the hell would it strip off reference qualifiers??? No clue man, no clue.
- stinos 11y agoProbably because otherwise you cannot choose between stripping out references, or not doing that (by using auto& for instance)?