Passing a variable by reference in a lambda the value is not the same, why?

Hi, I created a custom component that is essentially a grid with some buttons and I need to perform some actions while I move those buttons.

In the code below I need absolutely to pass by reference the index of item that I’m dragging, however when I pass by reference my index, it changes his value in another number.

How can I pass by reference my index maintaining his value?

tb2.onClick = [this]() { //tb2 is a button that enable the possibility to drag items

    for (int i = 0; i < vt.getNumOfItems(); i++)
        vt.getItemIstance(i)->onDrag = [this, &i]()
            DBG(i); //Here the value printed is 32766, while if I pass by value it's the item of my component that I'm dragging

Thank You!

I don’t understand why you would want to capture the loop counter as a reference? In any case, it’s not going to work, the loop counter variable is a local variable and if you capture it into a lambda by reference, it is going to result in undefined behavior. You probably need to be capturing something else or have the variable of interest as a member of your “this” class. I think you are getting confused because of the lambda capture. Let’s take a step back and reason about simpler code:

Snippet 1:

int i = 2;
int k = i;
DBG(i); // A
DBG(k); // B

Snippet 2:

int i = 8
int& k = i;
DBG(i); // C
DBG(k); // D

For A, B, C, and D, let us know what you expect.

Passing i by value to the lambda is similar to Snippet 1. Passing i by reference to the lambda is similar to Snippet 2 (though, as @Xenakios pointed out, there is also a lifetime issue in your code).


Thank you, I find a solution! :slight_smile:

Thank you now it is more clear, I find a solution :slight_smile: