捕获 const this
Capturing const this
现在我有一个带有 lambda 的对象函数,为了使用成员函数和变量我必须(或者当然捕获所有..):
void MyClass::MyFunc() {
auto myLambda = [this](){...};
}
有没有办法明确声明捕获 const this ?我知道我可以:
void MyClass::MyFunc() {
MyClass const* const_my_class = this;
auto myLambda = [const_my_class](){...};
}
谢谢。
根据标准 (N3485) 中的 §5.1.2,lambda-capture 的定义是:
lambda-capture:
capture-default
capture-list
capture-default , capture-list
capture-default:
&
=
capture-list:
capture ... opt
capture-list , capture ... opt
capture:
identifier
& identifier
this
因此,您只能有 =
、&
、this
、标识符、&
identifier 在捕获列表中。您不能有表达式,例如将 this
转换为 const
.
捕获列表在高版本(-std=c++1y
)中的一些简单表达式是可用的,例如:
auto myLambda = [self = static_cast<MyClass const*>(this)](){
// Use `self` instead of `this` which is `const`
};
当然不像捕获this
那样可以像访问局部变量一样访问成员
现在我有一个带有 lambda 的对象函数,为了使用成员函数和变量我必须(或者当然捕获所有..):
void MyClass::MyFunc() {
auto myLambda = [this](){...};
}
有没有办法明确声明捕获 const this ?我知道我可以:
void MyClass::MyFunc() {
MyClass const* const_my_class = this;
auto myLambda = [const_my_class](){...};
}
谢谢。
根据标准 (N3485) 中的 §5.1.2,lambda-capture 的定义是:
lambda-capture:
capture-default
capture-list
capture-default , capture-list
capture-default:
&
=
capture-list:
capture ... opt
capture-list , capture ... opt
capture:
identifier
& identifier
this
因此,您只能有 =
、&
、this
、标识符、&
identifier 在捕获列表中。您不能有表达式,例如将 this
转换为 const
.
捕获列表在高版本(-std=c++1y
)中的一些简单表达式是可用的,例如:
auto myLambda = [self = static_cast<MyClass const*>(this)](){
// Use `self` instead of `this` which is `const`
};
当然不像捕获this
那样可以像访问局部变量一样访问成员