I try to capture a certain class member’s class member from within a function of class for a lambda.
To clarify: ClassA has a class member of type ClassB, which has a member C (e.g. a Pointer). ClassA has a function that attaches a lambda to some Object O. The lambda needs to refer to C (at the moment of lambda attachment to Object O).
The more specific code I am using is this. Where decide is another class function which takes an Answer Object. i is my control variable of a for loop:
choices.back()->onClick([this, i] {decide(this->content->currentStep->answers[i]); });
The issue here is, that to my understanding, I capture this, which is a pointer, by value (which is fine). Once the lambda function body is executed though, to my understanding, it at that point in time dereferences content, currentStep and answers[]. So if the “content” pointer changes between setting and executing the lambda, the Answer object will be different from when I set the lambda.
What would the syntax look like for capturing the actual reference to answer itself instead of starting off from this->content->… ?
The syntax would look like this.
choices.back()->onClick(
[&answer=this->content->currentStep->answers[i]] {decide(answer);}
); // ^^^^^^ creating a named variable in the capture
1