QEnableSharedFromThis Class▲
-
Header: QEnableSharedFromThis
-
Since: Qt 5.4
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Inherited By:
Detailed Description▲
You can inherit this class when you need to create a QSharedPointer from any instance of a class; for instance, from within the object itself. The key point is that the technique of just returning QSharedPointer<T>(this) cannot be used, because this winds up creating multiple distinct QSharedPointer objects with separate reference counts. For this reason you must never create more than one QSharedPointer from the same raw pointer.
QEnableSharedFromThis defines two member functions called sharedFromThis() that return a QSharedPointer<T> and QSharedPointer<const T>, depending on constness, to this:
class
Y: public
QEnableSharedFromThis&
lt;Y&
gt;
{
public
:
QSharedPointer&
lt;Y&
gt; f()
{
return
sharedFromThis();
}
}
;
int
main()
{
QSharedPointer&
lt;Y&
gt; p(new
Y());
QSharedPointer&
lt;Y&
gt; y =
p-&
gt;f();
Q_ASSERT(p ==
y); // p and q must share ownership
}
It is also possible to get a shared pointer from an object outside of the class itself. This is especially useful in code that provides an interface to scripts, where it is currently not possible to use shared pointers. For example:
class
ScriptInterface : public
QObject
{
Q_OBJECT
// ...
public
slots:
void
slotCalledByScript(Y *
managedBySharedPointer)
{
QSharedPointer&
lt;Y&
gt; yPtr =
managedBySharedPointer-&
gt;sharedFromThis();
// Some other code unrelated to scripts that expects a QSharedPointer<Y> ...
}
}
;
Member Function Documentation▲
[since 5.4] QSharedPointer<T> QEnableSharedFromThis::sharedFromThis()▲
This function was introduced in Qt 5.4.
[since 5.4] QSharedPointer<const T> QEnableSharedFromThis::sharedFromThis() const▲
Const overload of sharedFromThis().
This function was introduced in Qt 5.4.