Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing const this

Tags:

c++

c++11

lambda

right now I have an object function with a lambda, in order to use member functions and variables I would have to(or of course capture all..):

void MyClass::MyFunc() {

    auto myLambda = [this](){...};
}

Is there a way to explicitly state to capture a const this ? I know I could:

void MyClass::MyFunc() {
    MyClass const* const_my_class = this;
    auto myLambda = [const_my_class](){...};
}

Thanks.

like image 312
Alon Avatar asked Feb 17 '15 07:02

Alon


1 Answers

Per §5.1.2 in the standard (N3485), the definition of lambda-capture is:

lambda-capture:
    capture-default
    capture-list
    capture-default , capture-list
capture-default:
    &
    =
capture-list:
    capture ... opt
    capture-list , capture ... opt
capture:
    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`

};

Of course, it's not like capturing this that you can access members as same as local variables.

like image 97
masoud Avatar answered Sep 20 '22 06:09

masoud