QJniArray: implement operator-> for the iterator
The QJniArray doesn't store values, so at() always returns a temporary. As we cannot hand out a pointer to a temporary, use a wrapper reference struct that stores the value and implements operator->. It's all inline, so we can move it out in the future to return mutable references, if we ever want to enable write access to QJniArray elements. Change-Id: I3962df6160db8c5b573d47ebb7975864f8ea7a8b Reviewed-by: Mårten Nordheim <marten.nordheim@qt.io> (cherry picked from commit 3d5af4b912e60beb791f874c2dbfef5597b9aad7) Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
parent
71f80cff34
commit
6c3513f514
@ -25,6 +25,15 @@ template <typename T> class QJniArray;
|
||||
template <typename T>
|
||||
struct QJniArrayIterator
|
||||
{
|
||||
private:
|
||||
// Since QJniArray doesn't hold values, we need a wrapper to be able to hand
|
||||
// out a pointer to a value.
|
||||
struct QJniArrayValueRef {
|
||||
T ref;
|
||||
const T *operator->() const { return &ref; }
|
||||
};
|
||||
|
||||
public:
|
||||
QJniArrayIterator() = default;
|
||||
|
||||
constexpr QJniArrayIterator(const QJniArrayIterator &other) noexcept = default;
|
||||
@ -34,7 +43,7 @@ struct QJniArrayIterator
|
||||
|
||||
using difference_type = jsize;
|
||||
using value_type = T;
|
||||
using pointer = T *;
|
||||
using pointer = QJniArrayValueRef;
|
||||
using reference = T; // difference to container requirements
|
||||
using const_reference = reference;
|
||||
using iterator_category = std::random_access_iterator_tag;
|
||||
@ -44,6 +53,11 @@ struct QJniArrayIterator
|
||||
return m_array->at(m_index);
|
||||
}
|
||||
|
||||
QJniArrayValueRef operator->() const
|
||||
{
|
||||
return {m_array->at(m_index)};
|
||||
}
|
||||
|
||||
const_reference operator[](difference_type n) const
|
||||
{
|
||||
return m_array->at(m_index + n);
|
||||
|
@ -22,6 +22,7 @@ private slots:
|
||||
void operators();
|
||||
void ordering();
|
||||
void toContainer();
|
||||
void pointerToValue();
|
||||
};
|
||||
|
||||
using namespace QtJniTypes;
|
||||
@ -308,6 +309,15 @@ void tst_QJniArray::toContainer()
|
||||
QCOMPARE(charArray.toContainer<std::vector<jchar>>(), charVector);
|
||||
}
|
||||
|
||||
void tst_QJniArray::pointerToValue()
|
||||
{
|
||||
const QJniArray stringArray{u"one"_s, u"two"_s, u"three"_s};
|
||||
auto it = std::find(stringArray.begin(), stringArray.end(), u"two"_s);
|
||||
QCOMPARE_NE(it, stringArray.end());
|
||||
QCOMPARE(it->size(), 3);
|
||||
QCOMPARE((++it)->size(), 5);
|
||||
}
|
||||
|
||||
QTEST_MAIN(tst_QJniArray)
|
||||
|
||||
#include "tst_qjniarray.moc"
|
||||
|
Loading…
x
Reference in New Issue
Block a user