如何从捕获中准确预测将在lambda中创建哪种类型的成员?
在C ++中,我认为按值捕获T
类型的对象会创建类型为const T
的数据成员,并引用T&
。但在编译时:
#include <iostream>
struct A{
A(){std::cout<<"A\n";}
A(const A&){std::cout<<"A&\n";}
void cf()const{}
void f(){}
};
int main(){
A a;
A& ra=a;
const A& cra=a;
auto f00 = [ra, cra, &a]()-> void{
//Fixed:
//ra is A, cra is const A, a is A&
//lambda is void operator()()const
a.cf(); a.f();//pass
//ra.cf(); ra.f();//ra.f compilation err.
//cra.cf(); cra.f();//cra.f compilation err
};
//f00(); //A&,A&
auto f01 = [ra, cra, &a]()mutable-> void{
//Fixed:
//ra is A, cra is const A, a is A&
//lambda is void operator()()mutalbe
a.cf(); a.f();//pass
ra.cf(); ra.f();//pass
cra.cf(); cra.f();//cra.cf pass, but cra.f error, why?
};
//f01(); //A&,A&
auto f02 = [&ra, &cra, &a]()mutable-> void{
//Fixed:
//ra is A&, cra is const A&, a is A&
//lambda is void operator()()mutable
a.cf(); a.f();//pass
ra.cf(); ra.f();//pass
//cra.cf(); cra.f();//cra.cf pass, but cra.f error, why?
};
f02(); //
return 0;
}
我遇到了以下编译错误:
test_lambda.cpp:26:25: error: passing 'const A' as 'this' argument discards qualifiers [-fpermissive]
cra.cf(); cra.f();//pass, cra.f error
^
test_lambda.cpp:8:10: note: in call to 'void A::f()'
void f(){}
^
这是否意味着cra
确实是通过引用捕获的,而不是像我预期的那样被引用的对象的副本?