21

Consider the contrived class below with a method A() that contains two lambda functions, a1() and a2(). I'd like to be able to invoke a2 from inside a1. However, when I do so, (the second line inside a1), I get the error

Error: variable “cannot be implicitly captured because no default capture mode has been specified”

I don't understand this error message. What am I supposed to be capturing here? I understand that using [this] in the lambda definition gives me access to methods in class foo but I'm unclear as to how to do what I want.

Thanks in advance for setting me straight on this.

class foo
{
   void A()
   {
      auto a2 = [this]() -> int
      {
         return 1;
      };

      auto  a1 = [this]() -> int
         {
            int result;
            result = a2();
            return result;
         };

      int i = a1();
      int j = a2();
   }
};

1 Answer 1

22

You need to capture a2 in order to odr-use a2 within the body of a1. Simply capturing this does not capture a2; capturing this only allows you to use the non-static members of the enclosing class. If you expect a2 to be captured by default, you need to specify either = or & as the capture-default.

[this, &a2]  // capture a2 by reference
[this, &]    // capture all odr-used automatic local variables by reference, including a2
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks so much for the quick response but I'm still unclear. While [this, &a2] does work, [this, &] does not.
@David - It may be useful to specify a compiler and version. In VS 2017, for instance, it has to be [&, this] although the error message is quite clear.
@zzxyz . I'm using XCode 9.x and you're absolutely right, you have to put the & before 'this'. Now everything works --- thanks so much to both you and Brian
More specifically, The reason why capturing this does not also capture a2 is because a2 is a local variable. Capturing this to get access to a2 doesn't make any more sense than writing this->a2 in the main body of the foo::A() function would make.
@Brian, quick question, does a2 have to be captured by reference? Would [this, a2] work in this case?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.