@JonB said in operator[]:"index out of range":
@jeremy_k
As @Christian-Ehrlicher writes. Passing a local/auto variable to a lambda as a reference is not in itself any problem. Loads of lambdas may be written which use this, e.g. (I haven't looked) perhaps some of the std:: container algorithms may use reference parameters.
The potential problem arises when it is a slot for a signal, because that continues to use the lambda after the function which does the connect() exits. Then a reference parameter to a variable local to the function would indeed be a problem, as @Christian-Ehrlicher's code shows. However, in this particular case the OP is doing it from main(), so that will not be a problem here.
Yes, I did understand. It appears to be my point that was misunderstood. The code, abbreviated, was:
int main() {
qreal val=0;
QTimer timer1;
QObject::connect(&timer1,&QTimer::timeout,[&] ()
{
val = val + 10;
});
timer1.start(100);
}
Given:
Connections are broken when the object that emits the signal is destroyed.
timer1 has the same automatic block scope as val. val is declared before timer1, and will therefore be destructed after it.
There is no evidence of a move operation to alter the lifetime of timer1.
We can determine that the reference to val does not dangle prior to timer1 being destroyed, breaking the connection.
The situation would be the same in any function, or for any code block. main() does not alter the situation.