CodexBloom - Programming Q&A Platform

How to implement guide with std::function and lambda captures leading to advanced patterns in c++20

👀 Views: 86 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
c++20 stdfunction lambda C++

I need help solving I'm relatively new to this, so bear with me. I've looked through the documentation and I'm still confused about I'm working with an scenario when using `std::function` with a lambda that captures local variables in C++20. The behavior doesn't seem to align with my expectations, and I'm not sure if I'm missing something in how captures work with `std::function`. I have a simple example where I'm trying to store a lambda in a `std::function`, but when I call the function later, it seems to be using stale captures. ```cpp #include <iostream> #include <functional> int main() { int value = 10; std::function<void()> f; f = [&value]() { std::cout << "Value: " << value << std::endl; }; value = 20; // I change the value after assigning the lambda f(); // This should print 20, but it prints 10 instead! return 0; } ``` When I run this code, I expect the output to be `Value: 20`, but instead, it prints `Value: 10`. I thought the lambda would capture the current state of `value`, but it seems like it's capturing it by value rather than by reference. I've tried explicitly using a reference capture in the lambda, but I still get the same result. I'm using GCC 10.2.0 with C++20 standards. Am I misunderstanding how captures work in this context, or is there something else at play here? For context: I'm using C++ on macOS. How would you solve this? Thanks in advance! I'm working with C++ in a Docker container on macOS. Am I missing something obvious? I'm working on a REST API that needs to handle this. Any suggestions would be helpful.