DEV Community

Discussion on: Let's learn some modern C++!

 
pgradot profile image
Pierre Gradot

There is one famous article by Herb Sutter about auto and I highly recommend reading it: herbsutter.com/2013/08/12/gotw-94-...

Scott Meyer dedicates a chapter of _Effective Modern C++ to auto.

Thread Thread
 
dynamicsquid profile image
DynamicSquid

Sutter's article is really good, but I have a few points about it.

1. Ensures variables will always be initialized

If you can remember to use auto, then you can remember to initialize variables as well :)

2. Auto helps to write code against interfaces, not implementations / We already ignore actual types all the time

Well, it's not the type that I care about, but rather how to use that type. For the append_unqiue function, I don't care about the specific type, but I still care about the type. I need a container that works with those methods and helper functions.

Another example:

for (const auto& row : grid) // what's row? how should I use it in the for loop?

for (const std::vector<int>& row : grid) // it's longer, but better
Enter fullscreen mode Exit fullscreen mode

But for things like iterators or lambdas, then I would agree, auto is better:

3. It guarantees that you will continue to use the correct exact type under maintenance as the code changes, and the variable’s type automatically tracks other functions’ and expressions’ types unless you explicitly said otherwise.

That's actually a good point I haven't considered before.

So really the only point is #3, but other than that, I don't see a practical reason to use auto.

Thread Thread
 
pgradot profile image
Pierre Gradot • Edited

Point 1 : you can remember to initialize values without auto, but you can't forget to initialize them with it. That's quite not the same.

OK, I have to admit: I almost never use auto v = short{3} 😆

Furthermore, tools like clang-tidy warn me when a variable isn't initialized.

Point 2 : if your code is so long that you can't even remember what is grid and why you are trying to iterate over it, then not using auto seems quite a poor way to improve the overall function ;)

I used to think the same as you are doing now, I (sort of) forced myself to use auto at the beginning, and now I find code more readable in a case like this one. Also, I made a parallel between auto in C++ and Python, where (somehow) everything is auto. It's just a different way of thinking from traditional C++ or C.