How are parameters referenced when using QTimer::singleShot?
-
wrote on 11 Dec 2021, 12:54 last edited by mirro 12 Nov 2021, 12:55
void fun(QString& str)
{}
QString param;
QTimer::singleShot(200,this,[&,param](){}
};
//error:qualifiers dropped in binding reference of type "QString &" to initializer of type "const QString" -
Lifetime Qt Championwrote on 11 Dec 2021, 15:02 last edited by Chris Kawa 12 Nov 2021, 15:06
Did you meant to write
QTimer::singleShot(200,this,[&,param](){ fun(param); });
i.e. actually call the fun function from the lambda?If so, lambdas are immutable by default, which means
param
becomes const when copied by the capture group. You can't then use it as a non const parameter to fun. Couple of ways to fix this:-
If you don't want to modify str then make it a const parameter i.e.
void fun(const QString& str)
. -
If you want to modify the original parameter capture it by reference, not by value i.e.
[&](){ fun(param); }
or explicitly[¶m](){ fun(param); }
-
If you want to capture param by copy and modify that copy then you have to make the lambda mutable
[=]() mutable { fun(param); }
or explicitly[param]() mutable { fun(param); }
There's usually no reason to do that, but if you really want to you can.
-
-
void fun(QString& str)
{}
QString param;
QTimer::singleShot(200,this,[&,param](){}
};
//error:qualifiers dropped in binding reference of type "QString &" to initializer of type "const QString"wrote on 11 Dec 2021, 13:12 last edited by@mirro
Assuming something close to this is your actual code (since above won't compile), I can only guess there is an issue/confusion about passing both&
("by-reference") andparam
("not-by-reference"); do you really need this?Otherwise can you show actual code you are compiling.
-
Lifetime Qt Championwrote on 11 Dec 2021, 15:02 last edited by Chris Kawa 12 Nov 2021, 15:06
Did you meant to write
QTimer::singleShot(200,this,[&,param](){ fun(param); });
i.e. actually call the fun function from the lambda?If so, lambdas are immutable by default, which means
param
becomes const when copied by the capture group. You can't then use it as a non const parameter to fun. Couple of ways to fix this:-
If you don't want to modify str then make it a const parameter i.e.
void fun(const QString& str)
. -
If you want to modify the original parameter capture it by reference, not by value i.e.
[&](){ fun(param); }
or explicitly[¶m](){ fun(param); }
-
If you want to capture param by copy and modify that copy then you have to make the lambda mutable
[=]() mutable { fun(param); }
or explicitly[param]() mutable { fun(param); }
There's usually no reason to do that, but if you really want to you can.
-
3/3