JNI: clean up move and swap semantics in QJniObject

QJniObject is a value type with move semantics, but didn't provide swap,
so add it.
Make it safe to check a moved-from QJniObject for validity, and to
compare it with another QJniObject. As before, two invalid objects
compare as equal.

Change-Id: Ie08bb7c50da831f3e7e98e731e8ddbc0ebb3af78
Reviewed-by: Assam Boudjelthia <assam.boudjelthia@qt.io>
(cherry picked from commit 3e0c21691dd2be6911c417f4cbfaf54d10b4d634)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Volker Hilsheimer 2024-07-10 16:26:24 +02:00 committed by Qt Cherry-pick Bot
parent 6d55e0b053
commit 92b1923e31
3 changed files with 20 additions and 1 deletions

View File

@ -736,6 +736,14 @@ QJniObject::QJniObject(jobject object)
QJniObject::~QJniObject() QJniObject::~QJniObject()
{} {}
/*!
\fn void QJniObject::swap(QJniObject &other)
\since 6.8
Swaps this object with \a other. This function is very fast and never fails.
*/
namespace { namespace {
QByteArray getClassNameHelper(JNIEnv *env, const QJniObjectPrivate *d) QByteArray getClassNameHelper(JNIEnv *env, const QJniObjectPrivate *d)
{ {
@ -1385,7 +1393,7 @@ bool QJniObject::isClassAvailable(const char *className)
*/ */
bool QJniObject::isValid() const bool QJniObject::isValid() const
{ {
return d->m_jobject; return d && d->m_jobject;
} }
/*! /*!
@ -1411,6 +1419,8 @@ QJniObject QJniObject::fromLocalRef(jobject lref)
bool QJniObject::isSameObject(jobject obj) const bool QJniObject::isSameObject(jobject obj) const
{ {
if (!d)
return obj == nullptr;
if (d->m_jobject == obj) if (d->m_jobject == obj)
return true; return true;
if (!d->m_jobject || !obj) if (!d->m_jobject || !obj)
@ -1420,6 +1430,8 @@ bool QJniObject::isSameObject(jobject obj) const
bool QJniObject::isSameObject(const QJniObject &other) const bool QJniObject::isSameObject(const QJniObject &other) const
{ {
if (!other.isValid())
return !isValid();
return isSameObject(other.d->m_jobject); return isSameObject(other.d->m_jobject);
} }

View File

@ -102,6 +102,8 @@ public:
~QJniObject(); ~QJniObject();
void swap(QJniObject &other) noexcept { d.swap(other.d); }
template<typename Class, typename ...Args> template<typename Class, typename ...Args>
static inline QJniObject construct(Args &&...args) static inline QJniObject construct(Args &&...args)
{ {

View File

@ -328,6 +328,11 @@ void tst_QJniObject::compareOperatorTests()
QVERIFY(jstrobj != stringObject); QVERIFY(jstrobj != stringObject);
QVERIFY(stringObject != jstrobj); QVERIFY(stringObject != jstrobj);
QVERIFY(!invalidStringObject.isValid()); QVERIFY(!invalidStringObject.isValid());
QJniObject movedTo(std::move(stringObject3));
QVERIFY(!stringObject3.isValid());
QCOMPARE_NE(movedTo, stringObject3);
QCOMPARE(invalidStringObject, stringObject3);
} }
void tst_QJniObject::className() void tst_QJniObject::className()