Is the copy (move) construction in a by-value capture ([x]
) (or C++14 move capture [x = std::move(x)]
) in a lambda expression (as a return value) possible (or guaranteed) to be elided?
auto param_by_value(Widget w) {
// manipulating w ...
return [w] { w.doSomeThing(); };
}
auto param_by_move(Widget w) {
// manipulating w ...
return [w = std::move(w)] { w.doSomeThing() };
}
auto local_by_value() {
Widget w;
// manipulating w ...
return [w] { w.doSomeThing(); };
}
auto local_by_move() {
Widget w;
// manipulating w ...
return [w = std::move(w)] { w.doSomeThing() };
}
My questions are:
- Is the copy (move) for
w
in the above functions possible (or even guaranteed) to be elided? (I recall the explicitstd::move
would sometimes prevent copy elision, and the copy/move for parameters are impossible to be elided.) - If copy elision is not going to happen in case 1 and 3, will the by-value capture for
w
call the move constructor ofWidget
? - Which, by value or using
std::move
, should be preferred as the best practice?