c++ - What is the difference between QPointer, QSharedPointer and QWeakPointer classes in Qt? -


i have read qt documentations qpointer, qsharedpointer , qweakpointer classes. says:

  1. qpointer template class provides guarded pointers qt objects , behaves normal c++ pointer except automatically set 0 when referenced object destroyed , no "dangling pointers" produced.

  2. qsharedpointer class holds strong reference shared pointer.

  3. qweakpointer class holds weak reference shared pointer.

my questions "what difference between these classes?". i.e difference between pointer object , reference pointer? pointers objects different mechanisms , behaviors?

qpointer:
qpointer can point qobject instances. automatically set nullptr if pointed object destroyed. weak pointer specialized qobject.

consider fragment:

qobject *obj = new qobject; qpointer<qobject> pobj(obj); delete obj; q_assert(pobj.isnull()); // pobj nullptr 

qsharedpointer
reference-counted pointer. actual object deleted, when shared pointers destroyed. equivalent std::shared_ptr.

int *pi = new int; qsharedpointer<int> pi1(pi); qsharedpointer<int> pi2 = pi1; pi1.clear(); // pi2 still pointing pi, not deleted pi2.clear(); // no shared pointers anymore, pi deleted 

note long there shared pointer, object not deleted!

qweakpointer:
can hold weak reference shared pointer. not prevent object being destroyed, , reset. equivalent std::weak_ptr, lock equivalent tostrongref.

int *pi = new int; qsharedpointer<int> pi1(pi); qweakpointer<int> pi2 = pi1; pi1.clear(); // no shared pointers anymore, pi deleted // // use shared pointer, must "lock" use: qsharedpointer<int> pi2_locked = pi2.tostrongref(); q_assert(pi2_locked.isnull()); 

this can used if need access object controlled module.

to use weak pointer, must convert qsharedpointer. should never base decision on weak pointer being valid. can use data() of isnull determine pointer null.

generally, use weak pointer, must convert shared pointer since such operation ensures object survive long using it. equivalent "locking" object access , correct way of using object pointed weak pointer.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -