Capturing a static variable by reference in a C++11 lambda

前端 未结 2 496
广开言路
广开言路 2020-12-09 00:58

Main question

I\'m trying to compile the following code with GCC 4.7.2:

#include 

int foo() {
    static int bar;
    return [&b         


        
相关标签:
2条回答
  • 2020-12-09 01:27

    Why are you even trying to capture bar? It's static. You don't need to capture it at all. Only automatic variables need capturing. Clang throws a hard error on your code, not just a warning. And if you simply remove the &bar from your lambda capture, then the code works perfectly.

    #include <iostream>
    
    int foo() {
        static int bar;
        return [] () { return bar++; } (); // lambda capturing by reference
    }
    
    int main (int argc, char* argv[]) {
        std::cout << foo() << std::endl;
        std::cout << foo() << std::endl;
        std::cout << foo() << std::endl;
        return 0;
    }
    

    prints

    0
    1
    2
    
    0 讨论(0)
  • 2020-12-09 01:42

    Per the standard, you can only capture variables with automatic storage duration (or this, which is mentioned as explicitly capturable).

    So, no, you can't do that as per the standard (or, to answer your first question, that is not valid C++ 11 and is not a compiler bug)

    5.1.1/2 A name in the lambda-capture shall be in scope in the context of the lambda expression, and shall be this or refer to a local variable or reference with automatic storage duration.

    EDIT: And, as Kevin mentioned, you don't even need to capture a local static anyways.

    0 讨论(0)
提交回复
热议问题