QSharedPointer Class▲
-
Header: QSharedPointer
-
Since: Qt 4.5
-
qmake: QT += core
Detailed Description▲
The QSharedPointer is an automatic, shared pointer 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 goes out of scope, provided 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.
Thread-Safety▲
QSharedPointer and QWeakPointer are reentrant classes. This means that, in general, a given QSharedPointer or QWeakPointer object cannot be accessed by multiple threads at the same time without synchronization.
Different QSharedPointer and QWeakPointer objects can safely be accessed by multiple threads at the same time. This includes the case where they hold pointers to the same object; the reference counting mechanism is atomic, and no manual synchronization is required.
It should be noted that, while the pointer value can be accessed in this manner (that is, by multiple threads at the same time, without synchronization), QSharedPointer and QWeakPointer provide no guarantee about the object being pointed to. The specific thread-safety and reentrancy rules for that object still apply.
Other Pointer Classes▲
Qt also provides two other pointer wrapper classes: QPointer and QSharedDataPointer. They are incompatible with one another, since each has its very different use case.
QSharedPointer holds a shared pointer by means of an external reference count (i.e., a reference counter placed outside the object). Like its name indicates, the pointer value is shared among all instances of QSharedPointer and QWeakPointer. The contents of the object pointed to by the pointer should not be considered shared, however: there is only one object. For that reason, QSharedPointer does not provide a way to detach or make copies of the pointed object.
QSharedDataPointer, on the other hand, holds a pointer to shared data (i.e., a class derived from QSharedData). It does so by means of an internal reference count, placed in the QSharedData base class. This class can, therefore, detach based on the type of access made to the data being guarded: if it's a non-const access, it creates a copy atomically for the operation to complete.
QExplicitlySharedDataPointer is a variant of QSharedDataPointer, except that it only detaches if QExplicitlySharedDataPointer::detach() is explicitly called (hence the name).