I have always preferred to enter the type of a variable, because it makes the code more readable and less vague, but now there is auto, which seems to offer compile time type inference, and not runtime inference. Given that the compiler will always figure out the type, what risk is there in using auto?
Asked
Active
Viewed 72 times
0
-
2A quick search gave me this: https://stackoverflow.com/questions/34758042/is-there-a-downside-to-declaring-variables-with-auto-in-c – Jessica Sep 02 '21 at 16:49
-
Overuse of `auto` may make your code less readable. – drescherjm Sep 02 '21 at 16:49
-
4When used properly `auto` makes your program more readable and less error prone. But any tool can be used or abused. – Slava Sep 02 '21 at 16:51
-
Except when `auto` is required, where `auto` should be used instead of an explicit type identifier is a matter of opinion. – François Andrieux Sep 02 '21 at 16:52
-
1The only widespread risk that I've run into is relying on implicit conversion. `Bar bar; Foo foo = bar;` converts. `Bar bar; auto foo = bar;` does not convert. `std::unique_ptr
p = std::make_unique ();` converts. `auto p = std::make_unique – Eljay Sep 02 '21 at 16:52();` does not convert. All in all, `auto` has made the code significantly more readable and far less error prone, and the conversions are now explicit. -
2There are two main risks with `auto`. One is that the reader's idea of the type of the object doesn't match what the compiler deduces. The other is that yours doesn't. – Tim Randall Sep 02 '21 at 16:52
-
1The problem, as always, is when you don't want what `auto` does. Some techniques rely on implicit conversions, and not exact type specification (or deduction). Expression templates, in particular, don't play nice with `auto`. – StoryTeller - Unslander Monica Sep 02 '21 at 16:53
-
One rarely spoken of is the weird error messages you get when your compiler doesn't support C++11. – user4581301 Sep 02 '21 at 16:53
-
1One of the main drawbacks, that it's not easy for humans to infer the actual type, can be alleviated with the help of a good editor or IDE, which can run code analysis to figure out the actual type and let you know it when needed (sometimes by using an actual compiler in the background). – Some programmer dude Sep 02 '21 at 16:53
-
Auto is great when it shortens things improving readability but only when it's obvious what the type is. A critical part of readability is knowing the type. If not obvious, declare the type. And don't forget the decorators. Auto is not auto& or auto&&. – doug Sep 02 '21 at 21:09