Why is a const variable sometimes not required to be captured in a lambda?

后端 未结 3 1768
灰色年华
灰色年华 2020-12-08 03:44

Consider the following example:

#include 

int main() {
    const int m = 42;
    [] { m; }(); // OK

    const int n = std::rand();
    [] {          


        
3条回答
  •  情话喂你
    2020-12-08 04:14

    EDIT: The previous version of my answer was wrong. Beginner's is correct, here is relevant standard quote:

    [basic.def.odr]

    1. A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion to x yields a constant expression that does not invoke any non-trivial functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion is applied to e, or e is a discarded-value expression. ...

    Since m is a constant expression, it is not odr-used and therefore does not need to be captured.

    It appears that clangs behaviour is not compliant with the standard.

提交回复
热议问题