12

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?

3
  • 1
    Isn't this implicitly captured anyway when the capture-default is =?
    – Benj
    Commented Oct 20, 2012 at 15:33
  • @Benj Yes, this is implicitly captured under both = and & capture-default.
    – yohjp
    Commented Oct 20, 2012 at 15:42
  • 1
    It makes me wonder if this is actually always captured by reference irrespective of the default.
    – Benj
    Commented Oct 20, 2012 at 15:48

1 Answer 1

10

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)

6
  • I'm a little confused. Doesn't [&] (not [&,this]) implicitly capture this?
    – yohjp
    Commented Oct 22, 2012 at 4:28
  • 2
    No, [&] doesn't implicitly capture this by default. However, if you odr-use this inside the curly braces {} such as when accessing a member variable, etc., then it is implicitly captured by [&] (but it still is captured by copy and not reference).
    – Jesse Good
    Commented Oct 22, 2012 at 4:46
  • What does odr-used mean?
    – Tim MB
    Commented Oct 18, 2013 at 9:55
  • @TimMB: Have you heard of the One Definition Rule? It is an important concept and related to the term odr-used. 3.2p3 in the C++ standard defines the meaning of odr-used. Basically, when a name is odr-used, it requires a definition and is subject to the one definition rule.
    – Jesse Good
    Commented Oct 18, 2013 at 13:01
  • 1
    @TimMB: A pointer to an object of class type does not require a definition as it does not require the object to be complete. However, any type of member access via the this pointer would require a definition of the class of the member you are accessing. In relation to lambdas, the this pointer is implicitly captured only if you perform some type of member access or evaluation of the this pointer from within the lambda body, which makes the this pointer odr-used.
    – Jesse Good
    Commented Oct 18, 2013 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.