Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restriction about default capture mode and 'this' in C++ lambda-expression

Tags:

c++

c++11

lambda

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?

like image 395
yohjp Avatar asked Oct 20 '12 15:10

yohjp


1 Answers

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)

like image 101
Jesse Good Avatar answered Nov 15 '22 20:11

Jesse Good