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#include <QSharedPointer>
5#include <QWeakPointer>
6#include <QObject>
7#include <QDebug>
8
9//! [0]
10 class Y: public QEnableSharedFromThis<Y>
11 {
12 public:
14 {
15 return sharedFromThis();
16 }
17 };
18
19 int main()
20 {
21 QSharedPointer<Y> p(new Y());
22 QSharedPointer<Y> y = p->f();
23 Q_ASSERT(p == y); // p and q must share ownership
24 }
25//! [0]
26
27//! [1]
28 class ScriptInterface : public QObject
29 {
31
32 // ...
33
34 public slots:
36 {
38 // Some other code unrelated to scripts that expects a QSharedPointer<Y> ...
39 }
40 };
41//! [1]
42
43class MyObject : public QObject
44{
46 public:
47 MyObject() { /* ... */ }
48 ~MyObject() { /* ... */ }
49
50//! [2]
52{
54}
55
57{
60
61 // continue using obj
62 obj.clear(); // calls obj->deleteLater();
63}
64//! [2]
65
66 template <typename T>
67 void someFunc()
68 {
69 T *t = new T;
70 auto deleter = [](T *p) { delete p; };
71 {
72 //! [6]
73 QSharedPointer<T> other(t); this->swap(other);
74 //! [6]
75 }
76
77 {
78 //! [7]
80 //! [7]
81 }
82 }
83
84 template <typename T>
86};
87
89{
90 QSharedPointer<int> sharedptr;
91 QWeakPointer<int> weakref;
92
93 {
94 //! [2]
95 QSharedPointer<int> sharedptr(new int(42));
96 //! [2]
97 }
98
99 {
100 //! [1]
101 QSharedPointer<int> sharedptr(new int(42), [](int *p) { delete p; });
102 //! [1]
103 }
104
105 {
106 //! [3]
107 QSharedPointer<MyObject> obj =
108 QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);
109 //! [3]
110 }
111
112 {
113 //! [4]
114 if (sharedptr) { /*...*/ }
115 //! [4]
116 }
117
118 {
119 //! [5]
120 if (!sharedptr) { /*...*/ }
121 //! [5]
122 }
123
124 {
125 //! [8]
126 if (weakref) { /*...*/ }
127 //! [8]
128 }
129
130 {
131 //! [9]
132 if (!weakref) { /*...*/ }
133 //! [9]
134 }
135
136 {
137 //! [12]
138 QWeakPointer<int> weakref;
139
140 // ...
141
142 QSharedPointer<int> strong = weakref.toStrongRef();
143 if (strong)
144 qDebug() << "The value is:" << *strong;
145 else
146 qDebug() << "The value has already been deleted";
147 //! [12]
148 }
149}
QSharedPointer< Y > f()
int main()
[open]
bool examples()
[3]