Can the `this` keyword be used in a class scope?

It seems that I can define lambda expressions that capture thisin the class area. As far as I read the N4640 working draft today, I could not find a suggestion that allowed behavior. I think I'm missing something ...

Here is an example:

#include <iostream>
#include <functional>

struct foo {
    std::function<void()> f1 = [this]{ ++i; };
    int i = 0;
};

int main() {
    foo a;
    foo const& cref = a;
    cref.f1();
    std::cout << a.i << std::endl;
}

Launch a demo. (g ++ -std = C ++ 11 pedantic) https://wandbox.org/permlink/HPzaOxbBkOQOmuS6

Update

@Brian @cpplerner, , . " this " - ". , this . .

, this .

, N4640 9.2.2.1 [class.this]. , , . - 9.2.2/3 9.2.2/4.

, .

?

+6
1

()

. , , .

this ?

. [expr.prim.this],

" this , -, ([class.mem]).

. @ T.C.

this ?

.

, ++ n4618, ++, .

this .

expr.prim.lambda,

"-, , - *, - - -".

- -. . block.

, - scple - -.

this . . expr.prim.lambda.capture.

, -, , this.

@cpplearner @ T.C.

g++ clang++.

#include <iostream>
#include <functional>

struct foo {
    std::function<void()> lambda_in_class_scope = [this]{
        std::cout << this << std::endl;
    };
};

int main() {
    foo f;
    std::cout << &f << std::endl;
    f.lambda_in_class_scope();
}

:

0x7fff8f409cb0
0x7fff8f409cb0

. , this .

:

g++ 6.3 https://wandbox.org/permlink/FdhxJhVvripOQ1ng

clang++ 4.0 https://wandbox.org/permlink/kGoNBIoV5WTZV0sy

+1

Source: https://habr.com/ru/post/1016807/


All Articles