Home >Backend Development >C++ >Detailed explanation of C++ function parameters: rules for parameter passing in lambda expressions
Parameter passing rules in Lambda expressions: By Value: Passed by value, modification of the original value does not affect the external scope. By Reference: Use the [&] or [=] capture list to pass parameters by reference, allowing modification of the outer scope. By Move: For movable types, use the && capture list to pass parameters by move to optimize performance.
C Detailed explanation of function parameters: Rules for passing parameters in lambda expressions
Lambda expression
Lambda expression is a concise and powerful anonymous function pointer syntax. In C, the basic format of lambda expression is:
[capture_list](parameters) -> return_type { body }
Parameter passing rules
When the lambda expression contains parameters, the parameter passing follows the following rules:
[&]
or [=]
capture list to capture the reference of the parameter. You can pass the parameter by reference. &&
capture list to capture the move reference of the parameter, and the parameter can be passed by move. Practical Case
Consider the following C code example:
#include <iostream> #include <vector> int main() { // 创建一个 lambda 表达式,按值传递一个整型参数 auto sum = [](int x) { return x + 1; }; // 实例化一个 lambda 表达式,按引用传递参数 int value = 5; auto increment = [&value]() { value += 1; }; // 实例化一个 lambda 表达式,按移动传递 vector std::vector<int> vec = {1, 2, 3}; auto reverse = [vec = std::move(vec)]() { std::reverse(vec.begin(), vec.end()); }; std::cout << "By Value: " << sum(5) << std::endl; increment(); std::cout << "By Reference: " << value << std::endl; reverse(); std::cout << "By Move: "; for (auto elem : vec) { std::cout << elem << ' '; } std::cout << std::endl; return 0; }
Output:
By Value: 6 By Reference: 6 By Move: 3 2 1
Conclusion
Understanding the parameter passing rules in Lambda expressions is crucial to using them effectively. By passing parameters correctly, you can modify internal variables or optimize performance as needed.
The above is the detailed content of Detailed explanation of C++ function parameters: rules for parameter passing in lambda expressions. For more information, please follow other related articles on the PHP Chinese website!