summaryrefslogtreecommitdiffstats
path: root/src/corelib/doc/snippets/code/src_corelib_tools_qsharedpointer.cpp
blob: fd0612590e9e81e9db352f6712c1e2df97190371 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

//! [0]
    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
    }
//! [0]

//! [1]
    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> ...
        }
    };
//! [1]

//! [2]
    static void doDeleteLater(MyObject *obj)
    {
        obj->deleteLater();
    }

    void otherFunction()
    {
        QSharedPointer<MyObject> obj =
            QSharedPointer<MyObject>(new MyObject, doDeleteLater);

        // continue using obj
        obj.clear();    // calls obj->deleteLater();
    }
//! [2]

//! [3]
    QSharedPointer<MyObject> obj =
        QSharedPointer<MyObject>(new MyObject, &QObject::deleteLater);
//! [3]

//! [4]
    if (sharedptr) { ... }
//! [4]

//! [5]
    if (!sharedptr) { ... }
//! [5]

//! [6]
    QSharedPointer<T> other(t); this->swap(other);
//! [6]

//! [7]
    QSharedPointer<T> other(t, deleter); this->swap(other);
//! [7]

//! [8]
    if (weakref) { ... }
//! [8]

//! [9]
    if (!weakref) { ... }
//! [9]

//! [10]
    qDebug("Tracking %p", weakref.data());
//! [10]

//! [11]
    // this pointer cannot be used in another thread
    // so other threads cannot delete it
    QWeakPointer<int> weakref = obtainReference();

    Object *obj = weakref.data();
    if (obj) {
        // if the pointer wasn't deleted yet, we know it can't get
        // deleted by our own code here nor the functions we call
        otherFunction(obj);
    }
//! [11]

//! [12]
    QWeakPointer<int> weakref;

    // ...

    QSharedPointer<int> strong = weakref.toStrongRef();
    if (strong)
        qDebug() << "The value is:" << *strong;
    else
        qDebug() << "The value has already been deleted";
//! [12]