Can a lambda capturing nothing access global variables?

后端 未结 3 2003
走了就别回头了
走了就别回头了 2021-02-05 04:07
int n;    
int main()
{
    [](){ n = 0; }(); // clang says \"ok\"

    int m;
    [](){ m = 0; }(); // clang says \"not ok\"
}

I just wonder:

3条回答
  •  孤城傲影
    2021-02-05 04:49

    Actually the [](){ n = 10; }(); doesn't capture anything, it uses the global variable instead.

    int n;    
    int main()
    {
        [](){ n = 10; }(); // clang says "ok"
        std::cout << n; // output 10
    }
    

    See capture-list in Explaination

    capture-list - a comma-separated list of zero or more captures, optionally beginning with a capture-default.

    Capture list can be passed as follows (see below for the detailed description):

    • [a,&b] where a is captured by copy and b is captured by reference.
    • [this] captures the current object (*this) by reference
    • [&] captures all automatic variables used in the body of the lambda by reference and current object by reference if exists
    • [=] captures all automatic variables used in the body of the lambda by copy and current object by reference if exists
    • [ ] captures nothing

提交回复
热议问题