g++ won't allow generalized capture of const object by reference in lambda?

前端 未结 2 1567
清酒与你
清酒与你 2020-12-11 14:48

This is rejected by g++ (4.9.3 and 5.2.0), but is accepted by clang 3.5.0:

int main() { 
    const int ci = 0;
    auto lambda = [ &cap = ci ]() { };
}
<         


        
2条回答
  •  执念已碎
    2020-12-11 15:28

    Your code is valid. §5.1.2/11 goes

    An init-capture behaves as if it declares and explicitly captures a variable of the form
    auto init-capture ;
    whose declarative region is the lambda-expression’s compound-statement […]

    Now, clearly, declaring

    auto &cap = ci;
    

    and capturing cap is fine. That is,

    int main() { 
        const int ci = 0;
        auto &cap = ci;
        auto lambda = [&cap]() { };
    }
    

    compiles with GCC. Apart from the declarative region and lifetime of cap, there is no difference between this snippet and yours, thus GCC is incorrect.
    This bug has already been reported as #66735, with a similar example:

    int x = 0;
    auto l = [&rx = static_cast(x)] {};
    

提交回复
热议问题