Lambdas and Move Semantics
Lambdas and Move Semantics
Use local callable objects and efficient value transfer in modern C++.
Lambdas and Move Semantics
Use local callable objects and efficient value transfer in modern C++.
auto square = [](int x) {
return x * x;
};
int factor = 2;
auto scale = [factor](int x) { return x * factor; };
std::string name = "Ada";
std::vector<std::string> names;
names.push_back(std::move(name));
After moving, the source object is valid but its exact value is unspecified.
int total = 0;
auto add = [&total](int value) { total += value; };
[&] and [=] for nontrivial lambdas unless the scope is very small and obvious.auto fn = [name = std::string{"Ada"}] {
std::cout << name << '\n';
};
Init captures are useful when a lambda should own moved data.
A moved-from object is valid but only safe to destroy, assign, or otherwise use according to its documented post-move guarantees.