| 1 |
//===----------------------------------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
// UNSUPPORTED: no-exceptions |
| 10 |
|
| 11 |
#include <typeinfo> |
| 12 |
|
| 13 |
// Test taken from 5.2.8.2 |
| 14 |
// When typeid is applied to a glvalue expression whose type is a polymorphic |
| 15 |
// class type, (10.3), the result refers to a std::type_info object |
| 16 |
// representing the type of the most derived object (1.8) (that is, the |
| 17 |
// dynamic type) to which the glvalue refers. If the glvalue expression is |
| 18 |
// obtained by applying the unary * operator to a pointer(68) and the pointer |
| 19 |
// is a null pointer value (4.10), the typeid expression throws the |
| 20 |
// std::bad_typeid exception (18.7.3). |
| 21 |
// |
| 22 |
// 68) If p is an expression of pointer type, then *p, (*p), *(p), |
| 23 |
// ((*p)), *((p)), and so on all meet this requirement. |
| 24 |
bool bad_typeid_test () { |
| 25 |
class A { virtual void f() {}}; |
| 26 |
class B { virtual void g() {}}; |
| 27 |
|
| 28 |
B* bp = nullptr; |
| 29 |
try { |
| 30 |
bool b = typeid(*bp) == typeid(A); |
| 31 |
((void)b); |
| 32 |
} catch (const std::bad_typeid&) { |
| 33 |
return true; |
| 34 |
} |
| 35 |
return false; |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
// The value of a failed cast to pointer type is the null pointer value of |
| 40 |
// the required result type. A failed cast to reference type throws |
| 41 |
// std::bad_cast (18.7.2). |
| 42 |
bool bad_cast_test () { |
| 43 |
class A { virtual void f() {}}; |
| 44 |
class B { virtual void g() {}}; |
| 45 |
class D : public virtual A, private B {}; |
| 46 |
|
| 47 |
D d; |
| 48 |
B *bp = (B*)&d; // cast needed to break protection |
| 49 |
try { D &dr = dynamic_cast<D&> (*bp); ((void)dr); } |
| 50 |
catch ( const std::bad_cast & ) { return true; } |
| 51 |
return false; |
| 52 |
} |
| 53 |
|
| 54 |
int main ( ) { |
| 55 |
int ret_val = 0; |
| 56 |
|
| 57 |
if ( !bad_typeid_test ()) { |
| 58 |
ret_val = 1; |
| 59 |
} |
| 60 |
|
| 61 |
if ( !bad_cast_test ()) { |
| 62 |
ret_val = 2; |
| 63 |
} |
| 64 |
|
| 65 |
return ret_val; |
| 66 |
} |