Advanced Scope Control
Lambda Scope Capturing
Lambda functions provide powerful scope control mechanisms:
#include <iostream>
#include <functional>
std::function<int(int)> createMultiplier(int factor) {
// Capturing variables by value and reference
return [factor](int x) {
return x * factor; // Captures factor by value
};
}
void demonstrateLambdaScopes() {
auto doubler = createMultiplier(2);
auto tripler = createMultiplier(3);
std::cout << "Double 5: " << doubler(5) << std::endl;
std::cout << "Triple 5: " << tripler(5) << std::endl;
}
Scope Capture Modes
Capture Mode |
Description |
Syntax |
[=] |
Capture all variables by value |
Default copy |
[&] |
Capture all variables by reference |
Default reference |
[x, &y] |
Capture x by value, y by reference |
Selective capture |
[this] |
Capture current object pointer |
Member access |
Scope Lifetime Management
graph TD
A[Scope Creation] --> B[Variable Capture]
B --> C[Closure Generation]
C --> D[Controlled Execution]
D --> E[Scope Destruction]
Advanced Scope Control Techniques
#include <memory>
#include <functional>
class ScopeController {
private:
std::unique_ptr<int> dynamicResource;
public:
// Move semantics for efficient resource transfer
std::function<void()> createScopedOperation() {
auto localResource = std::make_unique<int>(42);
return [resource = std::move(localResource)]() {
// Captured resource with controlled lifetime
std::cout << "Resource value: " << *resource << std::endl;
};
}
};
Scope Extension Strategies
- Use
std::move
for efficient resource transfer
- Implement custom deleters for smart pointers
- Leverage RAII principles
- Control resource lifetime explicitly
Complex Scope Scenarios
- Nested lambda captures
- Recursive lambda definitions
- Lifetime-extended closures
- Minimize capture size
- Prefer value captures for small types
- Use reference captures carefully
- Avoid capturing large objects by value
At LabEx, we recommend mastering these advanced scope control techniques to write more flexible and efficient C++ code.