capture by value class members

后端 未结 3 1756
温柔的废话
温柔的废话 2021-02-02 08:49

Is there a way, when writing a lambda function within a member function, to capture fields of the enclosing class by value? The default catch-all = doesn\'t work be

3条回答
  •  伪装坚强ぢ
    2021-02-02 08:56

    No, data members cannot be captured by value. A lambda can capture only two kinds of things:

    1. the this pointer, and
    2. nonstatic local variables (that is, variables with automatic storage duration).

    As has been noted by ildjarn in the comments, you can create a local variable with a copy of the value of the data member, and capture that local variable by value.

    I would argue that if explicit by-value capture of a data member was allowed, it could prove confusing, since the behavior of explicit capture would differ from that of implicit capture. For example, given an accessible data member of type int named m, it would be odd that the following would produce different results:

    [=] () mutable { m = 1; } // we modify this->m
    [=m]() mutable { m = 1; } // we modify the copy of m that was captured
    

提交回复
热议问题