基类允许获取 QSharedPointer 为已由共享指针管理的对象。 更多...
头: | #include <QEnableSharedFromThis> |
CMake: |
find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
Since: | Qt 5.4 |
QSharedPointer<T> | sharedFromThis () |
QSharedPointer<const T> | sharedFromThis () const |
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> 和
QSharedPointer
<const T>, depending on constness, to
this
:
class Y: public QEnableSharedFromThis<Y> { public: QSharedPointer<Y> f() { return sharedFromThis(); } }; int main() { QSharedPointer<Y> p(new Y()); QSharedPointer<Y> y = p->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<Y> yPtr = managedBySharedPointer->sharedFromThis(); // Some other code unrelated to scripts that expects a QSharedPointer<Y> ... } };
[since 5.4]
QSharedPointer
<
T
> QEnableSharedFromThis::
sharedFromThis
()
若
this
(that is, the subclass instance invoking this method) is being managed by a
QSharedPointer
, returns a shared pointer instance pointing to
this
; otherwise returns a null
QSharedPointer
.
该函数在 Qt 5.4 引入。
[since 5.4]
QSharedPointer
<const
T
> QEnableSharedFromThis::
sharedFromThis
() const
这是重载函数。
Const overload of sharedFromThis().
该函数在 Qt 5.4 引入。