Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of C++ and exploring a powerful feature called Mutable Lambdas. Let's get started! š
Lambdas, also known as anonymous functions, are a fundamental part of C++11. They allow you to write small function snippets directly in line with other code, providing a clean and efficient way to handle function calls without the need for a separate function definition.
So, what makes a lambda mutable? By default, all lambdas are constexpr (constant expressions) and const (constant data), meaning they can't modify data outside of their scope. However, mutable lambdas can change this behavior, allowing them to modify captured variables.
When a lambda captures a variable from its surrounding scope, it creates a copy of that variable. But with mutable lambdas, you can capture variables by reference ([&]) or by value ([=]), allowing the lambda to modify the original variable.
Let's see a simple example of a mutable lambda that increments a counter:
#include <iostream>
void incrementCounter(int& counter) {
auto increment = [&counter]() mutable { ++counter; };
increment();
}
int main() {
int counter = 0;
incrementCounter(counter);
std::cout << "Counter: " << counter << std::endl;
return 0;
}In this example, incrementCounter is a function that takes a reference to an int variable counter. Inside incrementCounter, we define a mutable lambda increment that captures counter by reference and increments it every time it's called.
When a lambda captures variables, it creates a closure around those variables. This means the variables persist throughout the lifetime of the lambda, even after the surrounding function has returned.
Now, let's create a mutable lambda that keeps track of the number of times a function is called:
#include <iostream>
#include <functional>
auto callCounter = [counter = 0]() mutable { ++counter; std::cout << "Function called: " << counter << std::endl; };
std::function<void()> wrapper = callCounter;
void myFunction() {
wrapper();
}
int main() {
for (int i = 0; i < 5; ++i)
myFunction();
return 0;
}In this example, we define a mutable lambda callCounter that increments a counter and prints the function call count every time it's called. We then create a std::function<void()> object wrapper that holds callCounter. Inside myFunction, we simply call wrapper to execute the lambda.
What is the purpose of making a lambda mutable?
That's all for today! We hope you've enjoyed learning about mutable lambdas in C++. Stay tuned for more exciting lessons! š