1. 空捕获列表的示例:
[](){
    std::cout << "Hello, world!" << std::endl;
}();
  1. 值捕获列表的示例:
int x = 10;
auto lambda = [x]() {
    std::cout << "x = " << x << std::endl;
};
lambda();
  1. 引用捕获列表的示例:
int x = 10;
auto lambda = [&x]() {
    x++;
    std::cout << "x = " << x << std::endl;
};
lambda();
  1. 混合捕获列表的示例:
int x = 10, y = 20;
auto lambda = [x, &y]() {
    x++;
    y++;
    std::cout << "x = " << x << ", y = " << y << std::endl;
};
lambda();
  1. this指针捕获列表的示例:
class MyClass {
public:
    void printX() {
        auto lambda = [this]() {
            std::cout << "x = " << x << std::endl;
        };
        lambda();
    }

private:
    int x = 10;
};

MyClass obj;
obj.printX();
``
cpp中的lambda表达式前的中括号的作用在C++中lambda表达式前的中括号用于指定lambda表达式的捕获列表。捕获列表用于指定lambda表达式所需的外部变量并使其在lambda表达式内可用。捕获列表可以包含以下选项:1 空捕获列表:表示lambda表达式不会使用任何外部变量。2 值捕获列表:var1 var2 表示lambda表达式会使用指定的外部变量并将其值复制到lambda表达式内

原文地址: https://www.cveoy.top/t/topic/ccMg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录