Current C++11 standard does not support move capture of variable in lambda expression like
unique_ptr<int[]> msg(new int[1000000]);
async_op([&&msg] { // compile error : move capture is not supported
/* do something */
});
Since message passing and unique ownership has some critical role in some asynchronous system design, I think move semantic should be treated as first class language semantic. But lambda doesn't support move capture.
Of course I know that there is some workaround using move capture proxy - but I wonder the reason of decision that this functionality not to be included in the C++11 standard, despite of its importance.
Capture clauseA lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.
A capture clause of lambda definition is used to specify which variables are captured and whether they are captured by reference or by value. An empty capture closure [ ], indicates that no variables are used by lambda which means it can only access variables that are local to it.
The C++ spec tries to be pretty conservative. It's really bad for the next language spec to break programs that were compliant under the previous spec.
Move semantics took a while to mature. There were changes as late as 2009, if I recall. Meanwhile lambdas weren't implemented in many compilers until a similar timeframe. There was no time to fill in the gaps and still release a standard in 2011, which was already very late. (Prototype the spec with the compilers, test the compilers, go back and debate the spec, draft, prototype, test, repeat. Takes a while.)
Lambdas will be extended greatly in the next standard, gaining type deduction (auto
polymorphism). Xeo mentions one potential solution to move initialization.
Note that lambdas are only syntactic sugar. They are specified in terms of an automatically-defined class, but contain nothing you can't do yourself. As for the present language standard, you are expected to manually flesh out that implementation when the sugar runs out.
By the way, you can possibly work around the missing feature by capturing an old fashioned auto_ptr
, which is C++03's now-deprecated attempt at a smart pointer. It is invalidated by its own copy constructor, essentially implementing move-on-copy. But it is deprecated by C++11 and may cause warnings. You could try implementing something similar, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With