Rule for lambda capture variable

后端 未结 2 1346
忘了有多久
忘了有多久 2021-02-09 01:53

For example:

class Example
{
public:
    explicit Example(int n) : num(n) {}
    void addAndPrint(vector& v) const
    {
        for_each(v.begin(         


        
相关标签:
2条回答
  • 2021-02-09 02:24

    5.1.2/9:

    The reaching scope of a local lambda expression is the set of enclosing scopes up to and including the innermost enclosing function and its parameters.

    and 5.1.2/10:

    The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression.

    As num is neither declared in any function scope nor has automatic storage duration, it cannot be captured. Thus VS is right and g++ is wrong.

    0 讨论(0)
  • 2021-02-09 02:42

    Standard says the following (5.1.2):

    The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression.

    To my understanding GCC compiler is right because 'num' is in the reaching scope at the point of lambda declaration.

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