QWeakPointer: add lock() for std::weak_ptr compatibility

[ChangeLog][QtCore][QWeakPointer] Added lock() method for std::weak_ptr compatibility.

Change-Id: I0851d91c51f5a4f04a855a1d8082234ce38396b4
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Marc Mutz 2014-03-09 11:46:26 +01:00 committed by The Qt Project
parent ef2a2a9c03
commit e3a8e242ad
4 changed files with 30 additions and 0 deletions

View File

@ -893,6 +893,15 @@
\sa QSharedPointer::QSharedPointer()
*/
/*!
\fn QSharedPointer<T> QWeakPointer::lock() const
\since 5.4
Same as toStrongRef().
This function is provided for API compatibility with std::weak_ptr.
*/
/*!
\fn void QWeakPointer::clear()

View File

@ -126,6 +126,7 @@ public:
void clear();
QSharedPointer<T> toStrongRef() const;
QSharedPointer<T> lock() const;
};
template<class T, class X> bool operator==(const QSharedPointer<T> &ptr1, const QSharedPointer<X> &ptr2);

View File

@ -639,6 +639,8 @@ public:
inline void clear() { *this = QWeakPointer(); }
inline QSharedPointer<T> toStrongRef() const { return QSharedPointer<T>(*this); }
// std::weak_ptr compatibility:
inline QSharedPointer<T> lock() const { return toStrongRef(); }
#if defined(QWEAKPOINTER_ENABLE_ARROW)
inline T *operator->() const { return data(); }

View File

@ -74,6 +74,7 @@ private slots:
void useOfForwardDeclared();
void memoryManagement();
void dropLastReferenceOfForwardDeclared();
void lock();
void downCast();
void functionCallDownCast();
void upCast();
@ -494,6 +495,22 @@ void tst_QSharedPointer::dropLastReferenceOfForwardDeclared()
QCOMPARE(forwardDeclaredDestructorRunCount, 1);
}
void tst_QSharedPointer::lock()
{
QSharedPointer<int> sp = QSharedPointer<int>::create();
QVERIFY(sp);
QWeakPointer<int> wp = sp;
QVERIFY(sp == wp);
QVERIFY(sp == wp.lock());
QVERIFY(sp == wp.toStrongRef());
sp.reset();
QVERIFY(!wp);
QVERIFY(sp != wp); // this is why op(shared_ptr, weak_ptr) is a bad idea (apart from MT races)...
QVERIFY(sp == wp.lock());
QVERIFY(sp == wp.toStrongRef());
}
class DerivedData: public Data
{
public:
@ -866,6 +883,7 @@ void tst_QSharedPointer::objectCast()
ptr.clear();
QVERIFY(ptr.isNull());
QVERIFY(weakptr.toStrongRef().isNull());
QVERIFY(weakptr.lock().isNull());
// verify that the object casts fail without crash
QSharedPointer<OtherObject> otherptr = qSharedPointerObjectCast<OtherObject>(weakptr);