简体   繁体   中英

Why move capture is not supported in C++ lambda?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM