如果我正确理解(我的来源是C++ Primer,第5版)的第395页,mutable使从lambda中修改捕获的变量成为可能。有两件事我不明白:
mutable的目的是什么?只是一种语法糖?mutable是否可以在每个变量的基础上应用,难道不是更有帮助吗?发布于 2015-07-09 12:51:39
mutable允许您修改在lambda作用域之外定义的变量,但是对这些变量所做的任何更改都不会扩展到初始变量:
auto f1 = [=] () mutable { n += 4; return n ; } ;
auto f2 = [&] () { n += 4; return n ; } ;
std::cout << f1 () << ' ' ; // Call to f1, modify n inside f1
std::cout << n << ' ' ; // But not in main
// 2nd call to f1, the value of n inside f1 is the value stored during the first call,
// so 8 (the output will be 8 + 4)
std::cout << f1 () << ' ' ;
std::cout << f2 () << ' ' ; // Call to f2, modify n inside f2
std::cout << n << std::endl ; // And in main输出
8 4 12 8 8 另一个不同之处是,当您按值使用capture时,值是在计算lambda时捕获的,而不是当它被调用时:
int n = 4 ;
auto f1 = [=] () mutable { return n ; } ; // lambda evaluated, value is 4
auto f2 = [&] () { return n ; } ; // lambda evaluated, reference to n
std::cout << f1 () << ' ' ; // Call to f1, captured value is 4
std::cout << f2 () << ' ' ;
n = 8 ;
std::cout << f1 () << ' ' ; // Call to f1, captured value is still 4
std::cout << f2 () << std::endl ; // Reference to n, so updated value printed输出:
4 4 4 8 最后一个(巨大的)区别是,一旦引用的目标超出范围,引用捕获的变量就不可用:
std::function <int ()> f (bool withref) {
int n = 4 ;
if (withref) {
return [&] () { return n ; } ;
}
return [=] () { return n ; } ;
}
auto f1 = f (false) ;
auto f2 = f (true) ;
std::cout << f1 () << ' ' ;
std::cout << f2 () << std::endl ; // Something will go wrong here...输出:
4 1639254944 第二种行为是不明确的。
概括地说:
mutable,您可以修改值在中捕获的变量--函数的作用域,但是由于在计算lambda时,该变量已被复制到另一个内存位置,所以您只需要修改该变量的本地复制(即使原始变量已经消失,您也可以访问该副本)。&并不会创建原始变量的副本,允许您修改它(原始变量),而是允许您在该变量销毁后访问该变量。https://stackoverflow.com/questions/31317478
复制相似问题