Search code examples
c++iteratorlanguage-design

C++ iterators considered harmful?


At the Boost library conference today, Andrei Alexandrescu, author of the book Modern C++ Design and the Loki C++ library, gave a talk titled "Iterators Must Go" (video, slides) about why iterators are bad, and he had a better solution.

I tried to read the presentation slides, but I could not get much out of them.

  1. Are iterators bad?
  2. Is his replacement really better?
  3. Will C++ implementators pick up his ideas?

Solution

  • First, to answer your questions:

    1. No. In fact, I argued elsewhere that iterators are the most important/fundamental concept of computer science ever. I (unlike Andrei) also think that iterators are intuitive.
    2. Yes, definitely but that shouldn't come as a surprise.
    3. Hmm. Looking at Boost.Range and C++0x – haven't they already?

    Andrei's big contribution here is just to say: drop the concept of iterators altogether, see ranges not just as a convenience wrapper but rather as a core construct. Other languages have already done this (much of Andrei's concepts just echo .NET's LINQ or Python's iterators) but they all only offer output ranges. Andrei argues for different types of ranges, much like the conventional iterator categories.

    In that light, it's odd that he starts by mocking the arbitrariness of these iterator categories.

    I also think that his examples are off, especially his file copying: yes, the iterator variant is a huge improvement over the 1975 code. It reduces a loop with complicated break condition down to one statement. What he's really taking issue with here is just the syntax. Well, excuse me: we're talking about C++ here – of course the syntax is ugly. And yes, using ranges here is an improvement – but only syntactically.

    I also think that Andrei's find implementation is off. What he really defines there is the DropUntil operation (naming is hard!) from LINQ. The find operation should really return either one or zero elements (or an iterator!). Shunning iterators here isn't helpful in my opinion since we might want to modify the value directly instead of copying it. Returning a one-element range here only adds overhead without a benefit. Doing it Andrei's way is bad because then the name of the method is just wrong and misleading.

    That said, I essentially agree with Andrei in almost all points. Iterators, while being my pet concept from computer science, are certainly a big syntactical burden and many ranges (especially infinite generators) can (and should) be implemented conveniently without them.