C++ - lambda expression, capture clause and class members
Asked Answered
C

1

8

I am using PPL and parallel_for syntax to have a for loop. In the capture clause, I have 3 variables, one of them is a class member. There is a compilation error due to the presence of a class member among variables in the capture clause. However, if I have this class member in lambda body, it does not compile either, and error stated is that variable in enclosing scope should be in capture clause. How to proceed? Should I copy the variable member to a local variable beforehand, and have it passed in the capture clause?

Here is the code, with formulaCommand the class member.

parallel_for (m_rowStart,m_rowEnd+1,[&functionEvaluation,varModel_,formulaCommand](int i)
    {       
            MLEquationVariableModel  model_(varModel_);
            model_.addVariable("i", i);
            model_.addVariable("j", 1);
            MLEquationCommand* command_ = formulaCommand->duplicate(&model_);
            double d = command_->execute().toDouble();
            if(d==NO_VALUE)
            {
                functionEvaluation.local()  = NO_VALUE;
            }
            else
            {
                functionEvaluation.local() += d;
            }
            delete command_;
    });

Thanks!

Corset answered 30/4, 2012 at 7:27 Comment(0)
B
7

You need to capture this to access the member variables (remember that formulaCommand is equivalent to this->formulaCommand).

[&functionEvaluation, varModel_, this](int i) { ... }

(BTW, you should probably use a smart pointer (unique_ptr<MLEquationCommand>) instead of manually delete-ing the raw pointer command_.)

Brythonic answered 30/4, 2012 at 7:30 Comment(5)
Also worth noting that member variables are always captured by-reference since they are really accessed through the captured version of this. If you want to capture a member by value, then copy it to a local and then capture that by value.Bystander
Or like this : [&functionEvaluation, varModel_, =]Alika
@KennyTM Could you expand on use of unique_ptr<>, or point at some relevant ref? thanksCorset
@VJovic: The correct syntax for that would be [=, &functionEvaluation].Brythonic
You know what I meant, and is even shorter :)Alika

© 2022 - 2024 — McMap. All rights reserved.