1. 程式人生 > >QPointer,QSharedPointer,QWeakPointer的區別與使用例子(QSharedPointer類似Delphi裏的引用計數,是強引用,而QWeakPointer是弱引用,不影響原始對象的引用計數,相當於是在暗中觀察對象,但保持聯系,需要的時候就會出現)

QPointer,QSharedPointer,QWeakPointer的區別與使用例子(QSharedPointer類似Delphi裏的引用計數,是強引用,而QWeakPointer是弱引用,不影響原始對象的引用計數,相當於是在暗中觀察對象,但保持聯系,需要的時候就會出現)

nullptr 聯系 rec strong 使用 ces provide c++ actual

QPointer is a template class that provides guarded pointers to Qt objects and behaves like a normal C++ pointer except that it is automatically set to 0 when the referenced object is destroyed and no "dangling pointers" are produced.
QSharedPointer class holds a strong reference to a shared pointer.
QWeakPointer class holds a weak reference to a shared pointer.

46down voteaccepted:


QPointer:
QPointer can only point to QObject instances. It will be automatically set to nullptr if the pointed to object is destroyed. It is a weak pointer specialized for QObject.

Consider this fragment:

QObject *obj = new QObject;
QPointer<QObject> pObj(obj);
delete obj;

Q_ASSERT(pObj.isNull()); // pObj will be nullptr now
QSharedPointer
A reference-counted pointer. The actual object will only be deleted, when all shared pointers are destroyed. Equivalent to std::shared_ptr.

int *pI = new int;
QSharedPointer<int> pI1(pI);
QSharedPointer<int> pI2 = pI1;
pI1.clear();

// pI2 is still pointing to pI, so it is not deleted
pI2.clear();
// No shared pointers anymore, pI is deleted
Note that as long there is a shared pointer, the object is not deleted!

QWeakPointer:
Can hold a weak reference to a shared pointer. It will not prevent the object from being destroyed, and is simply reset. Equivalent to std::weak_ptr, where lock is equivalent to toStrongRef.

int *pI = new int;
QSharedPointer<int> pI1(pI);
QWeakPointer<int> pI2 = pI1;
pI1.clear();
// No shared pointers anymore, pI is deleted
//
// To use the shared pointer, we must "lock" it for use:
QSharedPointer<int> pI2_locked = pI2.toStrongRef();
Q_ASSERT(pI2_locked.isNull());
This can be used if you need access to an object that is controlled by another module.

當對象被另一個單元所控制的時候,就可以使用QWeakPointer。

To use a weak pointer, you must convert it to a QSharedPointer. You should never base a decision on the weak pointer being valid. You can only use data() of isNull to determine that the pointer is null.

當使用QWeakPointer的時候,必須把它先轉成QSharedPointer,你永遠無法直接決定QWeakPointer是否是有效的。你只能使用data()去判斷這個指針是否為空。

Generally, to use a weak pointer, you must convert it to a shared pointer since such an operation ensures that the object will survive for as long as you are using it. This is equivalent to "locking" the object for access and is the only correct way of using the object pointed to by a weak pointer.

一般來說,必須先轉換成強引用。而強引用相當於鎖定了這個對象。


https://stackoverflow.com/questions/22304118/what-is-the-difference-between-qpointer-qsharedpointer-and-qweakpointer-classes

QPointer,QSharedPointer,QWeakPointer的區別與使用例子(QSharedPointer類似Delphi裏的引用計數,是強引用,而QWeakPointer是弱引用,不影響原始對象的引用計數,相當於是在暗中觀察對象,但保持聯系,需要的時候就會出現)