I was reading a really great Bjarne Stroustrup\'s article where he exposes some
ID: 659042 • Letter: I
Question
I was reading a really great Bjarne Stroustrup's article where he exposes some C++ myths. I look at code that focus my attention, because I wouldn't know that C++ supports this kind of expressions. I'm talking about lambda expressions, or closures.
void do_my_sort(vector<double>& v)
{
sort(v,[](double x, double y) { return x>y; }); // sort v in decreasing order
}
I was working with C# and JavaScript for several years, more recently with Java and Objective C and I find this language feature very powerful and useful. I currently doing some works in Smalltalk and, no surprise... the closures are there too...
So I was wondering, why this language feature came so late to C++ (2011)?
Explanation / Answer
Weak compilers, large scope, existing library weaknesses, and potentially negative library interactions.
First, it was very hard for implementations to support all of C++98, and only occurred many years after the Standard shipped. Adding even more features in would only have made this worse. C# doesn't have this problem because C# 1.0/2.0 are very easy to implement in comparison. The fact is that even now C++ tooling is far behind tooling for these other languages because C++ is such a bitch to handle.
Secondly, C++ lambdas have to deal with a lot of additional details. For example, the lifetime of captured objects is something that C#/JS do not have to consider.
Thirdly, I will say that there were few examples of APIs where lambdas would have been genuinely useful. For example, the original STL did a lot with function objects. However, because you couldn't compose or lazy the algorithms, and iterators seriously suck, adding lambdas would not exactly have made them into LINQ. Really addressing these issues and making the C++ algorithms on par would have required a lot more work than just lambdas, a lot of which still hasn't been done. Compared to writing custom iterators and allocators of the time, and chaining together algorithms in-place on containers by hand, using a non-local struct functor was really not that bad.
Finally, it was unclear as to whether library techniques like expression templates could completely obviate the need for a language feature at all. It turns out that they can't, but there are other language features (non-placement new, delete and their array versions, native arrays) that are now not only completely redundant in C++11, but actively seriously harmful. Repeating these mistakes is undesirable. It's better to only resort to language features where you know for sure that a library can't handle it.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.