Qt 6.x
The Qt SDK
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
src_corelib_tools_qscopedpointer.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
5void myFunction(bool useSubClass)
6{
7 MyClass *p = useSubClass ? new MyClass() : new MySubClass;
8 QIODevice *device = handsOverOwnership();
9
10 if (m_value > 3) {
11 delete p;
12 delete device;
13 return;
14 }
15
16 try {
17 process(device);
18 }
19 catch (...) {
20 delete p;
21 delete device;
22 throw;
23 }
24
25 delete p;
26 delete device;
27}
29
31void myFunction(bool useSubClass)
32{
33 // assuming that MyClass has a virtual destructor
34 QScopedPointer<MyClass> p(useSubClass ? new MyClass() : new MySubClass);
35 QScopedPointer<QIODevice> device(handsOverOwnership());
36
37 if (m_value > 3)
38 return;
39
40 process(device);
41}
43
45 const QWidget *const p = new QWidget();
46 // is equivalent to:
48
49 QWidget *const p = new QWidget();
50 // is equivalent to:
52
53 const QWidget *p = new QWidget();
54 // is equivalent to:
57
59if (scopedPointer) {
60 ...
61}
63
65class MyPrivateClass; // forward declare MyPrivateClass
66
67class MyClass
68{
69private:
70 QScopedPointer<MyPrivateClass> privatePtr; // QScopedPointer to forward declared class
71
72public:
73 MyClass(); // OK
74 inline ~MyClass() {} // VIOLATION - Destructor must not be inline
75
76private:
77 Q_DISABLE_COPY(MyClass) // OK - copy constructor and assignment operators
78 // are now disabled, so the compiler won't implicitly
79 // generate them.
80};
82
84// this QScopedPointer deletes its data using the delete[] operator:
86
87// this QScopedPointer frees its data using free():
88QScopedPointer<int, QScopedPointerPodDeleter> podPointer(reinterpret_cast<int *>(malloc(42)));
89
90// this struct calls "myCustomDeallocator" to delete the pointer
92{
93 static inline void cleanup(MyCustomClass *pointer)
94 {
95 myCustomDeallocator(pointer);
96 }
97};
98
99// QScopedPointer using a custom deleter:
IOBluetoothDevice * device
\inmodule QtCore \reentrant
Definition qiodevice.h:34
\inmodule QtCore
The QWidget class is the base class of all user interface objects.
Definition qwidget.h:99
GLsizei const void * pointer
Definition qopenglext.h:384
GLfloat GLfloat p
[1]
MyPrototype myFunction
[0]
const QWidget *const p
[1]
QScopedPointer< int, QScopedPointerArrayDeleter< int > > arrayPointer(new int[42])
[4]
QScopedPointer< int, QScopedPointerPodDeleter > podPointer(reinterpret_cast< int * >(malloc(42)))
QScopedPointer< MyCustomClass, ScopedPointerCustomDeleter > customPointer(new MyCustomClass)
static void cleanup(MyCustomClass *pointer)