Fix crash when using QProperty<T>::setBinding(Functor ...)

We must move the functor properly into the binding object, otherwise we
end up with stale pointers as pointed out by ASAN.

Change-Id: Icd84f4c113dd48e1e3e2d744abac0902cdf9339e
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
This commit is contained in:
Simon Hausmann 2020-04-29 11:53:18 +02:00
parent 0c4bc39002
commit 709648993c
2 changed files with 16 additions and 3 deletions

View File

@ -316,10 +316,11 @@ public:
#ifndef Q_CLANG_QDOC
template <typename Functor>
QPropertyBinding<T> setBinding(Functor f,
const QPropertyBindingSourceLocation &location = QT_PROPERTY_DEFAULT_BINDING_LOCATION)
QPropertyBinding<T> setBinding(Functor &&f,
const QPropertyBindingSourceLocation &location = QT_PROPERTY_DEFAULT_BINDING_LOCATION,
std::enable_if_t<std::is_invocable_v<Functor>> * = nullptr)
{
return setBinding(Qt::makePropertyBinding(f, location));
return setBinding(Qt::makePropertyBinding(std::forward<Functor>(f), location));
}
#else
template <typename Functor>

View File

@ -68,6 +68,7 @@ private slots:
void genericPropertyBinding();
void genericPropertyBindingBool();
void staticChangeHandler();
void setBindingFunctor();
};
void tst_QProperty::functorBinding()
@ -674,6 +675,17 @@ void tst_QProperty::staticChangeHandler()
QCOMPARE(t.observedValues, values);
}
void tst_QProperty::setBindingFunctor()
{
QProperty<int> property;
QProperty<int> injectedValue(100);
// Make sure that this picks the setBinding overload that takes a functor and
// moves it correctly.
property.setBinding([&injectedValue]() { return injectedValue.value(); });
injectedValue = 200;
QCOMPARE(property.value(), 200);
}
QTEST_MAIN(tst_QProperty);
#include "tst_qproperty.moc"