8 ms·
Lambda expression comparison between C++11, C++14 and C++17
- jaytaylor 11y agoThis is the first time I've looked at C++ lambdas. They appear magnificently powerful and also like another pile of easy ways to get completely screwed up. Ah well, that's just the C++ way I suppose. Makes me glad for Rust, that's for sure!
- frozenport 11y agoWhat do you mean? Only time you can mess up a lambda is if a pointer that you're using gets changed. And this kind of dupicate ownership is a general problem with pointers.
- vvanders 11y agoYeah, I'm not following as well. I've used Lambdas in C++ pretty heavily and they're really well done and thought out. FWIW nothing about them is much different from Rust's approach(anon struct + fn) it's all the ownership guarantees which give Rust it's safety.
- rileymat2 11y agoI think you have issues with reference capture groups and object lifetimes. Or alternatively value capture groups and object slicing.
- jguegant 11y agoHere take your rustwin point! I really like the explicit capture of C++'s lambdas more than the implicit one in most other languages (C#, Java, Python...) where you easily ends-up with a closure not referencing the expected variable. See: https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/ https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/clos...
- deleted 11y ago[deleted]
- netheril96 11y agoI was burned by the same thing in Javascript. "Explicit is better than implicit". Therefore, I agree with you that explicit closure list, with the ability to copy and reference captured variables, is actually what C++ does right, not wrong.
- groovy2shoes 11y agoThe explicit capture list is only necessary in C++ because memory ownership and lifetimes are managed by the programmer in C++. Compare that to a garbage-collected language like Scheme or C#: when the implementation can figure out where memory needs to be freed and ensures you can't use-after-free, it frees the programmer from thinking about ownership (but not necessarily lifetimes: you can still wind up with memory leaks in GC'd languages if you're not careful to let go of references you no longer need). As mentioned elsewhere in this thread, Rust also offers the same level of explicit control without capture lists (though I'm on the fence about which way I prefer). My point is that in languages with automatic memory management, explicit capture lists don't make much sense because the programmer is not tasked with managing memory and can safely capture references all the time. There's no need to ask oneself, "Do I own this pointed-to memory? Do I need to worry about it being freed before this closure? Should I make a copy?", etc. This is because, in a sense, the garbage collector itself owns the memory, but checks to make sure nothing else can use it anymore before it frees it.
- yokohummer7 11y agoThat is almost true, but there's one exception in those GC'ed languages due to the dichotomy of value types and reference types. The confusing behavior on capturing the iteration variable is one example.
- groovy2shoes 11y agoAh, yes! You're correct. I spend most of my GC'd time in languages that don't have such a value vs. reference dichotomy, and I'd completely forgotten about it.
- oolongCat 11y agoA question people who use C++ regularly, is C++ becoming easier to read and code?
- gregstula 11y agoIt does get easier to read and code over time. As an aside, the C++ in this post is pretty much as elegant as it gets.
- hendzen 11y agoYes, I work in a template heavy C++ codebase and the (already quite good) situation is getting better with each language standard. C++11 was really a turning point for the language - features like 'auto', lambdas, and variadic templates have enabled succinct generic code that is both readable and highly performant. Increased competition between the gcc and clang teams has also been a major improvement - both have implemented many C++17 features very quickly, and error messages have greatly improved in both compilers. This is especially welcome when developing templates. Clang's licensing has made it possible to integrate libclang in to vim/emacs (ycmd, irony-mode, rtags, etc) for very accurate completion/syntax checking, etc. Clang-format has also seen quite a bit of adoption, bringing the benefits of standardized formatting to large projects. The sanitizers have also been a huge boon - getting automatic memory leak, buffer/heap overflow, use after free, uninitialized memory, integer overflow, etc is now as easy as compiling with '-fsanitize=[address|undefined|memory|etc]'. Overall, C++(11+) is a very productive language if you have stringent performance and latency requirements and you need powerful abstraction facilities.
- int_19h 11y agoDo you mean, becoming easier with new language features that get added?
- vanderZwan 11y agoContrary to popular belief, new features can make a language more elegant and simple, if they make clunky old features obsolete with a simpler alternative.
- 11y ago
- typon 11y agoTaking a concept such as a lambda function and making it look this ugly...this is why I hate C++. I wish I wasn't forced to program it every day.
- hendzen 11y agoHow is it ugly? The capture list is a necessary complexity in a language with manual memory management.
- steveklabnik 11y agoIt's a trade off more than a necessity. For example, Rust doesn't have explicit capture lists, and if you want explicit control, you make new bindings and capture those. You almost never need to do this in Rust, so it's optimized for that case; I haven't written many closures in C++, so I can't say as much about the frequency there. To make this more concrete: let s = String::from("s"); let closure = || { println!("s is: {}", s); }; closure(); If you wanted to capture s in a different way: let s = String::from("s"); let s1 = &s; let closure = || { println!("s1 is: {}", s1); }; closure(); No capture list needed, same control.
- kibwen 11y agoRust doesn't have explicit capture lists, but it does have the `move` modifier on closures which is like C++'s `[=]`. Strictly speaking, Rust probably could have gotten away with having neither the `move` modifier nor capture clauses at all, but it would have had wide-ranging implications on the ergonomics and capabilty of closures.
- hendzen 11y agoHow would you do the equivalent of this in Rust? auto on_heap = std::make_unique<MyType>(...); function_that_accepts_lambda([obj = std::move(on_heap)]() { obj->bar(...); })
- 11y ago
- aurelian15 11y agoNice overview. Just a small correction: the smallest possible lambda is []{} and not [](){} as stated in the article. The parameter list is optional.
- hellofunk 11y ago>The parameter list is optional. To avoid confusion, only an empty parameter list is optional. You can't omit the parameter list if you take args, unlike lambda shortcuts in languages like clojure which allow you to implicitly refer to arguments inside the body using a universal variable name, and therefore omit the parameter list for all lambdas. That possibility does not exist in c++.
- hendzen 11y agoAnother mildly obscure feature of lambdas is the ability to capture a variadic number of parameters. Example (slightly contrived): #include <future> #include <iostream> template<typename... Args> void log(Args&&... args) { (std::cout << ... << args) << std::endl; } template<typename... Args> std::future<void> log_async(Args&&... args) { return std::async(std::launch::async, [args...] { log(args...); }); } int main() { auto f = log_async(1, 2, 3); f.wait(); }
- netheril96 11y agoWhich standard version?
- hendzen 11y agoThat snippet depends on fold expressions, which are in c++17. AFAIK, capturing a variadic parameter pack should work in C++11.
- groovy2shoes 11y agoFor those of us still stuck on C++98 at work, would you mind explaining what's going on here? In particular, I can't figure out why the ellipsis is so separated from `args` here: (std::cout << ... << args) << std::endl; That looks like some black magic to me. The rest makes sense, I think.
- hendzen 11y agohttp://en.cppreference.com/w/cpp/language/fold http://en.cppreference.com/w/cpp/language/fold
- groovy2shoes 11y agoNeat! Thank you :)
- makecheck 11y agoHeh, great. I used to put an ellipsis into a programming example to mean “fill in whatever you actually do here”, and now C++ went and made it mean something. :)
- forrestthewoods 11y agoNot a bad article. I wish the first example wasn't so complicated. C++ lambda syntax is pretty gross. The initial breakdown is great. But why use a std::vector and std::transform in the first real example? Stick to integer addition. Keep things simple.
- meshko 11y agoNice. I am a bit confused -- before c++17 it is impossible to capture this by copy; is it possible to capture other objects by copy? seems like it is?
- Kristine1975 11y agoYes, it is. Just write: [a](...){ ... } and the variable "a" will be captured by copy.
- Kristine1975 11y agoClang's C++1z support: http://clang.llvm.org/cxx_status.html http://clang.llvm.org/cxx_status.html (scroll down a bit) And gcc's: https://gcc.gnu.org/projects/cxx-status.html#cxx1z https://gcc.gnu.org/projects/cxx-status.html#cxx1z Unfortunately neither supports constexpr lambdas at the moment.
- vmorgulis 11y agoThere is another interesting feature in C++17 for lambdas: Possibility to cast a lambda to a function pointer. It will become possible to store a lambda as a struct/member that could bind to "this" (like in Javascript).
- hellofunk 11y agoI assume this is only for stateless lambdas, that have not captured anything? Because otherwise a function pointer would not be enough, right? Currently, any stateless lambda can decompose into a function pointer and be passed to any function that expects a function pointer, right? Are you saying that ++17 has augmented this, and if so can you provide more details or a reference (or an example) as I'm quite curious to know more.
- vmorgulis 11y agohttps://isocpp.org/files/papers/p0018r3.html https://isocpp.org/files/papers/p0018r3.html It's the best reference I found. The paper only talks of capturing "*this" by value (as in the original post of the topic). I think I read that in a draft about coroutines. The idea was to capture "this" by reference and convert the lambda to a function pointer to make it movable. It would useful for delegates or signals too.
- hellofunk 11y agoI love lambdas, but a lot of commenters are throwing around the word "closure" here, and c++ lambdas are definitely not closures. You can capture outside variables by value or by reference, but that value can expire before the lambda runs if the reference no longer exists; in which case, you are in trouble. Unlike a true closure (as in lisp or other languages), where the closed-over value stays around. If we talk only about c++ capture lists by value (i.e. [=]), then you could make a case for a more appropriate use of the word "closure" but since many lambdas do more than this, I think the distinction is necessary. However, even in by-value captures, if you are capturing a pointer by value, the issue remains. So, really it is not a good idea to think of lambdas as closures in the functional sense typically used in other languages.
- leni536 11y agoI'm not familiar with closures from other languages. What about capturing a shared_ptr by value?
- thrownaway2424 11y agoThe thing to keep in mind is that copying a shared_ptr isn't cheap at all. It's a class with a pointer and atomic reference count inside and the atomic inc/dec takes many cycles.
- leni536 11y agoHow does this compare to the cost of a closure in other languages? Yeah atomic reference counts are not cheap, but basically that's the point of a shared_ptr.
- thrownaway2424 11y agoI'm not sure. I don't program in C++ because I want it to have performance comparable to other languages.
- csl 11y ago
- makecheck 11y agoOne aspect of C++ lambdas that I really don’t like is the visual confusion caused by allowing "return", since at a glance this seems to affect the parent function. I have already found myself adding comments inside lambdas like "return x; // return-from-lambda" to make sure that I see what is really happening. Python by contrast does two things better: Python makes it really hard to write long expressions as lambdas, and no "return" is used in a Python "lambda". Of course, Python also allows "def" inside a "def" as a convenient way to write longer one-time functions. I also found that while I could use C++ lambdas for things like iteration, e.g. "object->forEachThing([](Thing const& t, bool& stop){ ... })", this makes the keyword problem worse. In this type of call, if I want to implement something that is logically like a "break" or "continue" of the loop, it has to use the "return" keyword (from the lambda only) with special conditions attached such as a "bool" variable to request the break. And that is confusing to read, even though conceptually it is similar to the Objective-C NSArray "enumerateObjectsUsingBlock:" that takes a similar approach (in that the block takes a "stop" argument).