Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
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
4//! [0]
5 class Y: public QEnableSharedFromThis<Y>
6 {
7 public:
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 }
20//! [0]
21
22//! [1]
23 class ScriptInterface : public QObject
24 {
26
27 // ...
28
29 public slots:
31 {
33 // Some other code unrelated to scripts that expects a QSharedPointer<Y> ...
34 }
35 };
36//! [1]
37
38//! [2]
39 static void doDeleteLater(MyObject *obj)
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 }
52//! [2]
53
54//! [3]
56 QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);
57//! [3]
58
59//! [4]
60 if (sharedptr) { ... }
61//! [4]
62
63//! [5]
64 if (!sharedptr) { ... }
65//! [5]
66
67//! [6]
68 QSharedPointer<T> other(t); this->swap(other);
69//! [6]
70
71//! [7]
72 QSharedPointer<T> other(t, deleter); this->swap(other);
73//! [7]
74
75//! [8]
76 if (weakref) { ... }
77//! [8]
78
79//! [9]
80 if (!weakref) { ... }
81//! [9]
82
83//! [10]
84 qDebug("Tracking %p", weakref.data());
85//! [10]
86
87//! [11]
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
96 otherFunction(obj);
97 }
98//! [11]
99
100//! [12]
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";
110//! [12]
QSharedPointer< Y > f()
int main()
[0]
qDebug("Items in list: %d", myList.size())
[23]
QObject * obj
[1]
QSharedPointer< int > strong
QSharedPointer< T > other(t, deleter)
[6]
QWeakPointer< int > weakref
[10]
QSharedPointer< T > other(t)
[5]
static void doDeleteLater(MyObject *obj)
[1]