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 reference variable in the capture