Functions, Pass-by-Const-Reference, Lambdas & Capture Clauses
1Concept
In C++, pass large objects by const reference (const T&) to prevent copy overhead. Lambdas ([capture](params) -> ret { body }) define inline anonymous functions. Capture modes: [&] (by reference), [=] (by value copy), [this] (enclosing class).
2Architecture Diagram
Lambda Structure:
[ captures ] ( parameters ) mutable noexcept -> return_type { body }
│
├─ [&] : Capture all outer variables by reference
├─ [=] : Capture all outer variables by value copy
└─ [a, &b]: Capture 'a' by value, 'b' by reference3Code Example
Stage 0 Language Foundations
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> scores = {45, 88, 92, 67, 95, 78};
int threshold = 80;
// Lambda capturing 'threshold' by value
int honors_count = std::count_if(scores.begin(), scores.end(), [threshold](int score) {
return score >= threshold;
});
std::cout << "Number of students scoring >= " << threshold << ": " << honors_count << "\n";
// Modifying captures via mutable lambda
auto multiplier = [factor = 2](int val) mutable {
return val * factor;
};
std::cout << "Multiplier result (25 * 2): " << multiplier(25) << "\n";
return 0;
}4Expected Output
Number of students scoring >= 80: 3 Multiplier result (25 * 2): 50
5Key Takeaways
- ✓Pass read-only objects by const T& to avoid expensive heap/copy operations.
- ✓Never capture local stack variables by reference [&] in asynchronous or escaping lambdas.
- ✓Generic lambdas ([](auto x) { ... }) deduce parameter types automatically.