As far as I can understand, QSharedPointer is a smart pointer, that is, a pointer that offers automatic garbage collection.
If possible I would like a code that would best explain this, including when to use it.
As far as I can understand, QSharedPointer is a smart pointer, that is, a pointer that offers automatic garbage collection.
If possible I would like a code that would best explain this, including when to use it.
After much reading I was able to understand. But you need to know what a QPointer is.
According to the QT documentation:
The QPointer class is a template class that provides reserved pointers to QObject. A saved pointer, QPointer, behaves like a normal, C ++ pointer T *, except that it is automatically set to 0 when the referenced object is destroyed (unlike normal C ++ pointers, which become "hanging hands" in such cases). T has to be a QObject subclass .
Example:
QPointer<QLabel> label = new QLabel;
label->setText("&Status:");
...
if (label)
label->show();
If QLabel is deleted, however, the label variable will be 0 rather than an invalid address, and the last line will never run. The functions and operators available with a QPointer are the same as those available with a normal pointer, except for the pointer (+, -, + + and -) arithmetic operators, which are usually only used with object arrays.
Now QSharedPointer:
The QSharedPointer class holds a strong reference to a shared pointer. QSharedPointer is an automatic pointer, shared in C ++. It behaves exactly like a normal pointer for normal purposes, including respect for constness. QSharedPointer will delete the pointer it is holding when it exits the scope, as long as no other QSharedPointer objects are referencing it. A QSharedPointer object can be created from a normal pointer, another QSharedPointer object, or by promoting a QWeakPointer object to a strong reference.
Note: The main goal of constness is to provide documentation and avoid programming errors. Const makes it clear to himself and others that something should not be changed.
Knowing this, we can then take this post into account: link
QPointer can only point to QObject cases. It will be automatically set to nullptr if the pointed object is destroyed. It is a weak pointer specialized for QObject. Consider this snippet:
QObject * obj = new QObject;
QPointer <QObject> pObj (obj);
delete obj;
Q_ASSERT (pObj.isNull ()); //PObj será agora nullptr
QSharedPointer A counted-reference 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 ainda está apontando para o pi, por isso não é eliminado
pI2.clear (); // Não há ponteiros compartilhados mais, PI é eliminado.
Note that while there is a shared pointer, the object will not be deleted!