gpt4 book ai didi

c++ - 捕获 const this

转载 作者:可可西里 更新时间:2023-11-01 15:24:51 24 4
gpt4 key购买 nike

现在我有一个带有 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.2lambda-capture 的定义是:

lambda-capture:    capture-default    capture-list    capture-default , capture-listcapture-default:    &    =capture-list:    capture ... opt    capture-list , capture ... optcapture:    identifier    & identifier    this

So, you only can have =, &, this, identifier, & identifier in the capture list. You can not have expressions, for example casting this to a const.

Some simple expressions in the capture list in higher versions (-std=c++1y) is avaiable, for example:

auto myLambda = [self = static_cast<MyClass const*>(this)](){

// Use `self` instead of `this` which is `const`

};

当然,不像捕获this那样可以像访问局部变量一样访问成员。

关于c++ - 捕获 const this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com