restriction about default capture mode and 'th

2019-03-16 00:41发布

问题:

I'm wondering why = capture-default mode prohibits this in capture-list of C++ lambda expression.

That is,

[=, this]{ };  // error
[&, this]{ };  // OK

This is specified by C++11 5.1.2/8.

  • If a lambda-capture includes a capture-default that is &, the identifiers in the lambda-capture shall not be preceded by &.
  • If a lambda-capture includes a capture-default that is =, the lambda-capture shall not contain this and each identifier it contains shall be preceded by &.

Q: Is there any reason or background story for this rule?

回答1:

this can only be captured by copy and never by reference. Even if you specify only [&], this can be implicitly captured by copy if odr-used. Therefore, [=, this] is an error because = would already implicitly capture this by copy while the & in [&, this] signifies capture by reference and does not implicitly capture this (unless it is odr-used)



标签: c++ lambda c++11