Welcome to another exciting lesson at CodeYourCraft! Today, we're diving deep into the world of C++ and exploring a powerful concept called Capture by Reference. This lesson is designed to be friendly and accessible, even if you're just starting out with C++ or looking to solidify your understanding.
When working with C++ lambdas (anonymous functions), sometimes we want to access variables outside the function scope. That's where capture by reference comes into play. It allows a lambda function to access and modify variables from its enclosing scope.
Capture by reference is useful when we want to maintain the state of variables outside the lambda function. It's a great way to create reusable and flexible functions that can adapt to changing data.
There are two ways to capture variables by reference:
[&] : Captures all variables by reference.[variable_name] : Captures a specific variable by reference.Let's see these in action!
#include <iostream>
int main() {
int counter = 0;
auto myLambda = [&]() {
std::cout << "Counter: " << counter << std::endl;
counter++;
};
myLambda();
myLambda();
myLambda();
std::cout << "Counter outside lambda: " << counter << std::endl;
return 0;
}In this example, our lambda function myLambda captures the variable counter by reference, allowing it to modify the counter's value.
#include <iostream>
int main() {
int counter = 0;
std::string message = "Hello, World!";
auto myLambda = [message]() {
std::cout << message << std::endl;
};
myLambda();
message = "Hello, CodeYourCraft!";
myLambda();
return 0;
}In this example, our lambda function myLambda captures the message variable by reference, allowing it to modify the message inside the lambda function without affecting the original variable outside it.
Which capture syntax allows a lambda function to capture all variables by reference?
If a lambda function captures a variable by value, what happens to the original variable?