基類允許獲取 QSharedPointer for an object already managed by a shared pointer 更多...
| 頭: | #include <QEnableSharedFromThis> |
| qmake: | QT += core |
| Since: | Qt 5.4 |
| QSharedPointer<T> | sharedFromThis () |
| QSharedPointer<const T> | sharedFromThis () const |
基類允許獲取 QSharedPointer for an object already managed by a shared pointer
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) can not 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> ... } };
若
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
QSharedPointer
holding a null pointer.
該函數在 Qt 5.4 引入。
這是重載函數。
Const overload of sharedFromThis ().
該函數在 Qt 5.4 引入。