I've come into the habit of writing code with direct-list-initialization like below as it's more effective and it's very useful to prevent implicit narrowing:
int i {0};
string s {""};
char c {'a'};
bool b {false};
auto num {100}; // But this??
But when it comes to the auto specifier, I have heard it is considered bad or not preferred to write it like that, why is that?
Here's an example of where using that syntax fails:
You might expect this to be fine:
b
should be aFoo
and be passed toeatFoo
. Unfortunately, this results in the following compiler error:As you can see,
b
is actually of typestd::initializer_list<Foo>
. Certainly not what we want in this case. If we change it toauto b = a
, this works fine. Then if we want to still useauto
, but explicitly state the type, we can change it toauto b = Foo{a}
and let the compiler elide the copy.