5 ms·
Under the hood of C++ lambdas and std::function
- doomrobo 11y agoIf anyone is curious, as of C++14 you can `move` variables into a lambda scope (like Rust's move ||) as follows Foo foo; // Foo implements a move constructor auto l = [cap = std::move(foo)](){ do_stuff(cap);} // Make the lambda do_stuff(foo); // ILLEGAL. Cannot use moved value l(); // Run the lambda
- rjeli 11y agoAt this time, what can Rust accomplish with the borrow checker that C++ can't accomplish with move semantics?
- bjz_ 11y agoRust's moves are implicit, making it easier to write code that doesn't copy heap allocated memory, and you can't get 'use after moves' like in C++ - the type system will pick that up.
- rjeli 11y agoOh, having only read about and not used recent C++ practices, I assumed use-after-move would be caught at compile time. Looking around a bit, it seems there's not even a warning for this; is there a reason? It seems like it would be very useful.
- Animats 11y agoMove is a template level concept, not a language concept. The compiler has no idea that something was moved, rather than assigned. Some implementations null out the "moved from" reference, so that a use after move will dereference null and crash the program. I've referred to the attempts to fix C++ ownership semantics with templates as "wallpapering over the mold".
- girvo 11y ago> is there a reason Yeah, basically that it's quite difficult to implement especially with C++'s baggage and undefined behaviour, from what I remember
- catnaroek 11y agoIn C++, "moving" and "copying" are a matter of class design. While you are expected to use move (resp. copy) constructors and assignments to, well, move (resp. copy); the language doesn't rule out using them for other purposes. In Rust, assignment and argument passing always move, "moving" always does the right thing (make a shallow copy and invalidate the original object), and you can't override this behavior. Furthermore, Rust splits what C++ calls "copying" into two concepts: shallow copying (which is the same as moving, except the original object isn't invalidated, and the type checker guarantees you can only do it when it makes sense) and deep cloning (which may be expensive and needs to be explicitly requested by the programmer). This is why Rust can track which objects are no longer usable.
- Too 11y agoIn c++ if you pass something as reference there is nothing preventing the receiving function from keeping a pointer to that reference even after returning. Right now the only way to enforce this is by convention: 1. move/unique/shared_ptr=receiver allowed to keep pointer, 2. raw ptr=totally banned, 3. reference=caller must outlive callee and called function is not allowed to keep pointer after returning. The last scenario here is not enforcable by the compiler.
- sebastic 11y agoCompiler will not warn this: MovableObject a, b, c; b = std::move(a); c = std::move(a); `c` may contain garbage. BTW the "move trait" (as its called in rust) is a related but orthogonal concept to its borrow checker.
- catnaroek 11y agoIn Rust, moving isn't a trait. It's the default, non-overridable behavior of assignment and argument passing. And everything is movable.
- loqi 11y agoRust disallows mutation of multiply-referenced data, which prevents things like iterator invalidation and data races.
- svalorzen 11y agoNote that `do_stuff` may not necessarily be illegal, since a moved value is required to be valid but in an unknown state. So maybe the result of `do_stuff` will be unspecified and unknowable (unless it requires some specific assumptions about the data), but any operations on `foo` should not give rise to obvious errors.
- Kristine1975 11y ago>// ILLEGAL. Cannot use moved value Actually that depends on the implementation of "Foo". After all "foo" has not been destroyed yet. Edit: An instance of std::unique_ptr for example points to nullptr after having been moved to another instance (C++14 Standard §20.8.1p4.2).
- Animats 11y agoFrom the article: "My favorite expression in C++ is [](){}();, which declares an empty lambda and immediately executes it." Sigh.
- Too 11y agoIn JavaScript it's quite common to see self executing lambdas like this (not empty though), because there variables have function scope rather than block scope so it's a way to limit the scope and capture closures. Does it have any practical use in c++?
- tunah2 11y agoLazy initialization is one example: void foo() { // initialized once when foo is first called static auto lazy_data = ...; // use lazy_data... } As of c++11, the compiler is required to make this threadsafe (initializer only runs once, even if foo() is called concurrently), typically by inserting locks. Since this only applies to the initializer, for complex initialization a self-executing lambda can be used: void foo() { static auto lazy_data = []{ auto data = new Whatever(); // initialize data... return data; }(); // use lazy_data... }
- catnaroek 11y agoNo, you don't need this in C++. You can use a normal (brace-delimited) block for this purpose.
- evincarofautumn 11y agoThe key difference being that a lambda is an expression, while a block is not, unless you use GCC’s statement-expression syntax of “({…})”.
- catnaroek 11y agoOh, I forgot that, you're absolutely right. I'm getting too used to languages where everything is an expression. :-)
- thelema314 11y agoI kind of wish this article had gotten into some details of how various compilers implement std::function; while it was nice to see some details of clang++'s 32-byte size of all std::function to remove the need for dynamic memory for many function objects, I'm still wishing I had more details on efficiency/cost of using std::function vs. plain lambdas or function pointers or other solutions.
- hellofunk 11y ago>Lambdas are also awesome when it comes to performance. Because they are objects rather than pointers they can be inlined very easily by the compiler, much like functors. This means that calling a lambda many times (such as with std::sort or std::copy_if) is much better than using a global function. This is one example of where C++ is actually faster than C. That's insight I've never seen anywhere before.
- stinos 11y agoI think there's truth in it but I'd still take it with a grain of salt, more like can be faster under the right circumstances. Inlining can not only be faster because there's no need for the function call prologue/epilogue etc but, probably more important, because the compiler sees all of the code and this opens doors for more optimizations. That's really important to realize; I recommend looking at the assembly generated by the compiler for loops etc from time to time. It's simply amazing what can be done. So if in similar code C++ can take advantage of it while C can't because it has to do an actual function call then the C++ version has advantages and might very well be faster (whereas otherwise both would produce roughly the same result and speed I guess, unless C++-only features like virtual functions etc used).
- exDM69 11y ago> So if in similar code C++ can take advantage of it while C can't because it has to do an actual function call then the C++ version has advantages and might very well be faster This is a matter of compilation units, not C vs. C++. If you put qsort() in a header file, and call it with a function pointer in the same compilation unit, it will get inlined and work exactly the same way as std::sort (which is in a header file since it's a template). You can pretty easily verify this yourself by doing a C++ template and a C function with function pointers (in a header file!), compile and inspect the resulting assembly code. Link-time optimization may relax the compilation unit requirement, but it's not very widely used yet.
- Kristine1975 11y agoIt's also wrong. If the compiler inlines e.g. std::sort, it doesn't matter whether the comparator is a lambda or a pointer to a function: The compiler knows what it is and can inline it as well. The only exception is when the function is defined in a different compilation unit. Then the compiler has no access to its definition and thus cannot inline it into std::sort. The "C++ with lambda is faster than C with function" comes from C's qsort function that takes a function pointer to a comparator and is not inlined by the compiler. This can result in it being slower than std::sort. BTW since lambdas without capture decay to function pointers, you can pass such a lambda to qsort.