C++ Capture by Reference šŸŽÆ

beginner
10 min

C++ Capture by Reference šŸŽÆ

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.

What is Capture by Reference? šŸ“

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.

Why Capture by Reference? šŸ’”

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.

How to Capture by Reference šŸ’”

There are two ways to capture variables by reference:

  1. [&] : Captures all variables by reference.
  2. [variable_name] : Captures a specific variable by reference.

Let's see these in action!

Example 1: Simple Capture by Reference šŸ“

cpp
#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.

Example 2: Capturing Specific Variables šŸ“

cpp
#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.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

Which capture syntax allows a lambda function to capture all variables by reference?

Quick Quiz
Question 1 of 1

If a lambda function captures a variable by value, what happens to the original variable?