aboutsummaryrefslogtreecommitdiffstats
path: root/tests/unneeded-cast/main.cpp
blob: 808e1a878340e1e1c3ca1776866fcf7d5f9fc0e6 (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
#include <QtCore/QObject>















struct A
{
    virtual void foo() { }
};

struct B : public A
{

};

void test()
{
    A *a = new A();
    B *b = new B();

    dynamic_cast<A*>(b); // warning: Casting to base
    dynamic_cast<A*>(a); // warning: Casting to itself
    dynamic_cast<B*>(a); // OK
    dynamic_cast<B*>(b); // warning: Casting to itself
    static_cast<A*>(b); // warning: Casting to base
    static_cast<A*>(a); // warning: Casting to itself
    static_cast<B*>(a); // OK
    static_cast<B*>(b); // warning: Casting to itself
}

class MyObj : public QObject
{
    Q_OBJECT
public:
};

void testQObjectCast(QObject *o)
{
    dynamic_cast<MyObj*>(o); // Warn
    qobject_cast<QObject*>(o); // Warn
    MyObj myobj;
    qobject_cast<QObject*>(&myobj); // Warn
    qobject_cast<MyObj*>(o); // OK
}

class FwdDeclared;

class MyObj2 : public QObject
{
public:
    Q_DECLARE_PUBLIC(QObject) // OK, in macro
    MyObj2 *q_ptr;
};

struct Base2 {};
class Base1 : public QObject {};

class Derived : public Base1, public Base2
{
public:
    void test()
    {
        static_cast<Base1*>(this); // OK
        static_cast<Base2*>(this); // OK
    }
};

void test2()
{
    static_cast<MyObj*>(nullptr); // OK
    static_cast<MyObj*>(0); // OK

    MyObj *o1;
    MyObj2 *o2;
    true ? static_cast<QObject*>(o1)  : static_cast<QObject*>(o2); // Ok
}

class MyObj4 : public QObject
{
    Q_OBJECT
public:
    void test()
    {
        qobject_cast<MyObj4*>(sender()); // OK
    }
};