🎯 1. Lambdas & Capture-Klauseln
Ein C++ Lambda ist ein anonymer Funktionstyp mit der Signatur [capture](parameter) -> return_type { body }:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int threshold = 50;
int call_count = 0;
// [&] = Capture by Reference, [=] = Capture by Value
// [threshold, &call_count] = Selektiver Capture
auto is_above = [threshold, &call_count](int val) {
++call_count;
return val > threshold;
};
std::vector<int> nums = {10, 60, 30, 80};
int count = std::count_if(nums.begin(), nums.end(), is_above);
std::cout << "Größer als 50: " << count << " (Prüfungen: " << call_count << ")\n";
}
Die Capture-Klausel [...] ist wie ein Rucksack für die Funktion: Sie packt Umgebungsvariablen ein, damit die Funktion sie am Bestimmungsort nutzen kann – entweder als Fotokopie ([=] Value) oder als direktes Funkgerät zum Original ([&] Reference).
🧩 2. Structured Binding (auto [a, b]) & std::optional
Seit C++17/C++20 können Tupel, Paare und Structs direkt in benannte Variablen zerlegt werden. Mit std::optional werden fehlende Werte ohne Null-Pointer sicher abgebildet:
#include <optional>
#include <string>
#include <tuple>
#include <iostream>
struct User {
int id;
std::string name;
std::string role;
};
// Rückgabe von std::optional (Kein nullptr nötig!)
std::optional<User> find_user(int id) {
if (id == 42) return User{42, "Alice", "Admin"};
return std::nullopt; // Wert nicht gefunden
}
int main() {
auto user_opt = find_user(42);
if (user_opt.has_value()) {
// Structured Binding zum Entpacken der Struct-Felder
auto [uid, uname, urole] = user_opt.value();
std::cout << "User: " << uname << " (" << urole << ")\n";
}
// Default-Wert mit .value_or()
auto missing = find_user(99);
std::string name = missing ? missing->name : "Gast";
}
📑 3. Cheat-Sheet: Lambdas & Modern Features
| Feature | Syntax | Bedeutung |
|---|---|---|
| Value Capture | [x, y]() { ... } |
Kopiert Variablen schreibgeschützt in die Closure |
| Reference Capture | [&x, &y]() { x++; } |
Ermöglicht Modifikation der äußeren Variablen |
| Generic Lambda | [](auto a, auto b) { return a + b; } |
Automatische Typableitung für Argumente |
| Init Capture (Move) | [p = std::move(ptr)]() { ... } |
Verschiebt Move-only Typen (wie unique_ptr) in das Lambda |
std::optional<T> |
std::optional<int> opt; |
Verhindert Null-Pointer Bugs für optionale Werte |
🧠 Diagnostischer Selbst-Check
Überprüfe dein Verständnis zu Speichersicherheit, Syntax und Systems-Design mit gezieltem Feedback:
🎯 Aufgaben & Checkliste in aufgabe.cpp
std::optional statt Magic ValuesVerwende niemals Magic Values wie -1 oder nullptr, um das Fehlen eines Ergebnisses zu signalisieren. std::optional<T> macht das Vorhandensein im Typensystem explizit und zwingt zur sauberen Fehlerprüfung!