Lambdas and Move Semantics

Lambdas and Move Semantics

Use local callable objects and efficient value transfer in modern C++.

Lambdas and Move Semantics

Lambda basics

auto square = [](int x) {
    return x * x;
};

Capture lists

int factor = 2;
auto scale = [factor](int x) { return x * factor; };

Moving values

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.

Main lessons

Capture carefully

int total = 0;
auto add = [&total](int value) { total += value; };

Init captures

auto fn = [name = std::string{"Ada"}] {
    std::cout << name << '\n';
};

Init captures are useful when a lambda should own moved data.

Moved-from objects

A moved-from object is valid but only safe to destroy, assign, or otherwise use according to its documented post-move guarantees.