Hacker News new | ask | show | jobs
by MereInterest 2228 days ago
I'd also say that using auto makes your code easier to read, especially when you are the user of generic code. Looping through a vector where you need to keep track of the iterator, for example.

    for(auto iter = vec.begin(); iter!=vec.end(); iter++)
    for(std::vector<project_namespace::class_name>::iterator iter = vec.begin(); iter!=vec.end(); iter++)
2 comments

These days there is also:

    for (auto i : vec)
Yeah, this is exactly what i dislike - unless the declaration of "vec" is somewhere close by (and assuming it isn't itself "auto" :-P) you have no idea what "i" is.

Especially when that "auto i : vec" should have instead been "auto& i : vec" or "const auto& i : vec" and now you are at best wasting cycles and at worst writing to copies that will soon be discarded, ending up with a bug that can be very hard to spot.

I love the idea of auto range-based iteration but it's full of warts like the one you mention. Recently I found myself wanting an iterator over a combinatorial family.

Generation of a single solution: 3 easy lines (calling on a few hundred lines of goofy math that actually describes the structure, but that's common to all of these approaches)

Writing a for-loop to fill a std::vector of solutions -- about 10 lines of a familiar stack-walking pattern which could confuse a novice.

Making a fake container that defines a begin() and end() along with a nested iterator class: about 20 lines of necessary boilerplate, another 20 lines to replicate the stack-walking, now sprinkled about the boilerplate. The novice is completely bewildered, so we add another 10-20 lines of comments to explain it.

So I have this strong urge to keep the first two implementations in place, just to provide a gentler ramp. But I won't use the code in the end, so it would only add maintenance overhead, so a lone tear rolls down my cheek as I delete the clear, readable code.

In python, this is often as easy as changing square brackets to parentheses to change a list comprehension into a generator.

I usually write auto &i : vec out of reflex, but left the reference part out into visually match what the parent had, with no reference. (But an iterator, so not having that issue.)
If the type is not obvious one can also write

    for(Class entry : container)
This is still an uncontroversial improvement over having to typedef or use auto for the iterator.
Sure, that is what i'd probably write myself too.
I think pretty much every one agree with auto for iterators and duplicated types (casts, initialisation).

The debate is about all the other cases.