1+ #include < cstdint>
2+
3+ struct S {
4+ int m1;
5+ };
6+
7+ class C {
8+ public:
9+ int m1;
10+ };
11+
12+ void test_pointer_to_integral_casts () {
13+ S s;
14+ S *s_ptr = &s;
15+ C c;
16+ C *c_ptr = &c;
17+ int l1 =42 ;
18+ int *int_ptr = &l1;
19+ void *void_ptr = &l1;
20+
21+ // Non-compliant cases - pointer to integral type casts
22+ std::intptr_t l2 =reinterpret_cast <std::intptr_t >(s_ptr);// NON_COMPLIANT
23+ std::uintptr_t l3 =reinterpret_cast <std::uintptr_t >(s_ptr);// NON_COMPLIANT
24+ std::int8_t l4 =reinterpret_cast <std::int8_t >(s_ptr);// NON_COMPLIANT
25+ std::uint8_t l5 =reinterpret_cast <std::uint8_t >(s_ptr);// NON_COMPLIANT
26+ std::int16_t l6 =reinterpret_cast <std::int16_t >(c_ptr);// NON_COMPLIANT
27+ std::uint16_t l7 =reinterpret_cast <std::uint16_t >(c_ptr);// NON_COMPLIANT
28+ std::int32_t l8 =reinterpret_cast <std::int32_t >(int_ptr);// NON_COMPLIANT
29+ std::uint32_t l9 =reinterpret_cast <std::uint32_t >(int_ptr);// NON_COMPLIANT
30+ std::int64_t l10 =reinterpret_cast <std::int64_t >(void_ptr);// NON_COMPLIANT
31+ std::uint64_t l11 =
32+ reinterpret_cast <std::uint64_t >(void_ptr);// NON_COMPLIANT
33+ long l12 =reinterpret_cast <long >(s_ptr);// NON_COMPLIANT
34+ unsigned long l13 =reinterpret_cast <unsigned long >(s_ptr);// NON_COMPLIANT
35+ int l14 =reinterpret_cast <int >(s_ptr);// NON_COMPLIANT
36+ unsigned int l15 =reinterpret_cast <unsigned int >(s_ptr);// NON_COMPLIANT
37+ }
38+
39+ void test_compliant_pointer_operations () {
40+ S s;
41+ S *s_ptr = &s;
42+ C c;
43+ C *c_ptr = &c;
44+ int l1 =42 ;
45+ int *int_ptr = &l1;
46+
47+ // Compliant cases - pointer to pointer casts
48+ void *l16 =static_cast <void *>(s_ptr);// COMPLIANT
49+ S *l17 =static_cast <S *>(static_cast <void *>(s_ptr));// COMPLIANT
50+ C *l18 =reinterpret_cast <C *>(s_ptr);// COMPLIANT
51+
52+ // Compliant cases - using pointers without casting to integral
53+ S *l19 = s_ptr;// COMPLIANT
54+ if (s_ptr !=nullptr ) {// COMPLIANT
55+ s_ptr->m1 =10 ;// COMPLIANT
56+ }
57+ }
58+
59+ void test_function_pointer_to_integral () {
60+ void (*func_ptr)() =nullptr ;
61+
62+ // Non-compliant cases - function pointer to integral type casts
63+ std::intptr_t l20 =
64+ reinterpret_cast <std::intptr_t >(func_ptr);// NON_COMPLIANT
65+ std::uintptr_t l21 =
66+ reinterpret_cast <std::uintptr_t >(func_ptr);// NON_COMPLIANT
67+ long l22 =reinterpret_cast <long >(func_ptr);// NON_COMPLIANT
68+ }
69+
70+ void test_member_pointer_to_integral () {
71+ // Member pointer to integral type casts are forbidden by the rule, but also
72+ // prohibited by the compiler, e.g.
73+ // int S::*member_ptr = &S::m1;
74+ // std::intptr_t l23 = reinterpret_cast<std::intptr_t>(member_ptr);
75+ // std::uintptr_t l24 = reinterpret_cast<std::uintptr_t>(member_ptr);
76+ }