在C++11中,lambda表达式有两种变量捕获方式,分别为值捕获和引用捕获。这两种捕获的形式如下:
#include <iostream>
int main(int argc, char* argv[])
{
int i = 42;
auto l1 = [i]() //值捕获
{
std::cout << "l1::i = " << i << std::endl;
};
auto l2 = [&i]() //引用捕获
{
std::cout << "l2::i = " << i << std::endl;
};
i = 1024;
l1(); //42
l2(); //1024
return 0;
}
//g++ lambda_lifecycle.cpp -o test -std=c++11Copy
使用值传递时,编译器将l1中的i初始化为main函数中的i相同的值(42),之后,l1中的i与main函数中的i不再有任何关系。使用引用传递时则不同,l2中的i为main函数中i的副本,两者在内存中的地址是相同的。
所以,在main函数中更改i的值时,对l1无任何影响,而对l2有影响。l1中的i的声明周期与main函数中的i没有任何关系,l2中的i的声明周期与main函数中的i是相同的。这也导致了一个问题:当lambda表达式的生命周期大于main函数i的生命周期时,程序会产生致命错误。
#include <iostream>
#include <thread>
#include <chrono>
std::thread t;
void func()
{
int i = 42;
std::cout << "address of i:" << &i << " value of i:" << i << std::endl;
t = std::thread([&i](){
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "address of i:" << &i << " value of i:" << i << std::endl;
});
}
int main(int argc, char* argv[])
{
func();
std::this_thread::sleep_for(std::chrono::seconds(1));
t.join();
return 0;
}Copy
执行结果如下:
g++ lambda_lifecycle.cpp -o test -std=c++11 -lpthread
./test
address of i:0x7fff7ab11ebc value of i:42
address of i:0x7fff7ab11ebc value of i:0Copy
当func函数执行完成之后,变量i所在地址被弹出栈,等待2秒之后,线程t对变量i执行读取操作是未定义行为。
在使用lambda表达式捕获变量时,永远不要在捕获局部变量时使用引用捕获。
原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/276532.html