Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
src_corelib_tools_qsharedpointer.cpp
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
5 class Y: public QEnableSharedFromThis<Y>
6 {
7 public:
8 QSharedPointer<Y> f()
9 {
10 return sharedFromThis();
11 }
12 };
13
14 int main()
15 {
16 QSharedPointer<Y> p(new Y());
17 QSharedPointer<Y> y = p->f();
18 Q_ASSERT(p == y); // p and q must share ownership
19 }
21
23 class ScriptInterface : public QObject
24 {
26
27 // ...
28
29 public slots:
30 void slotCalledByScript(Y *managedBySharedPointer)
31 {
32 QSharedPointer<Y> yPtr = managedBySharedPointer->sharedFromThis();
33 // Some other code unrelated to scripts that expects a QSharedPointer<Y> ...
34 }
35 };
37
40 {
41 obj->deleteLater();
42 }
43
45 {
46 QSharedPointer<MyObject> obj =
47 QSharedPointer<MyObject>(new MyObject, doDeleteLater);
48
49 // continue using obj
50 obj.clear(); // calls obj->deleteLater();
51 }
53
55 QSharedPointer<MyObject> obj =
56 QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);
58
60 if (sharedptr) { ... }
62
64 if (!sharedptr) { ... }
66
68 QSharedPointer<T> other(t); this->swap(other);
70
72 QSharedPointer<T> other(t, deleter); this->swap(other);
74
76 if (weakref) { ... }
78
80 if (!weakref) { ... }
82
84 qDebug("Tracking %p", weakref.data());
86
88 // this pointer cannot be used in another thread
89 // so other threads cannot delete it
90 QWeakPointer<int> weakref = obtainReference();
91
92 Object *obj = weakref.data();
93 if (obj) {
94 // if the pointer wasn't deleted yet, we know it can't get
95 // deleted by our own code here nor the functions we call
97 }
99
101 QWeakPointer<int> weakref;
102
103 // ...
104
105 QSharedPointer<int> strong = weakref.toStrongRef();
106 if (strong)
107 qDebug() << "The value is:" << *strong;
108 else
109 qDebug() << "The value has already been deleted";
Definition main.cpp:8
QSharedPointer< Y > sharedFromThis()
\inmodule QtCore
Definition qobject.h:103
void deleteLater()
\threadsafe
Definition qobject.cpp:2435
void slotCalledByScript(Y *managedBySharedPointer)
QSharedPointer< Y > f()
#define qDebug
[1]
Definition qlogging.h:164
GLint y
GLhandleARB obj
[2]
GLdouble GLdouble t
Definition qopenglext.h:243
GLfloat GLfloat p
[1]
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
#define Q_OBJECT
#define slots
QWeakPointer< int > weakref
[10]
QSharedPointer< T > other(t)
[5]
QSharedPointer< int > strong
this swap(other)
static void doDeleteLater(MyObject *obj)
[1]