1 //===-------------------------- test_aux_runtime.cpp ----------------------===// 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 #include <iostream> 13 14 // Test taken from 5.2.8.2 15 // When typeid is applied to a glvalue expression whose type is a polymorphic 16 // class type, (10.3), the result refers to a std::type_info object 17 // representing the type of the most derived object (1.8) (that is, the 18 // dynamic type) to which the glvalue refers. If the glvalue expression is 19 // obtained by applying the unary * operator to a pointer(68) and the pointer 20 // is a null pointer value (4.10), the typeid expression throws the 21 // std::bad_typeid exception (18.7.3). 22 // 23 // 68) If p is an expression of pointer type, then *p, (*p), *(p), 24 // ((*p)), *((p)), and so on all meet this requirement. 25 bool bad_typeid_test () { 26 class A { virtual void f() {}}; 27 class B { virtual void g() {}}; 28 29 B *bp = NULL; 30 try {bool b = typeid(*bp) == typeid (A); ((void)b); } 31 catch ( const std::bad_typeid &) { return true; } 32 return false; 33 } 34 35 36 // The value of a failed cast to pointer type is the null pointer value of 37 // the required result type. A failed cast to reference type throws 38 // std::bad_cast (18.7.2). 39 bool bad_cast_test () { 40 class A { virtual void f() {}}; 41 class B { virtual void g() {}}; 42 class D : public virtual A, private B {}; 43 44 D d; 45 B *bp = (B*)&d; // cast needed to break protection 46 try { D &dr = dynamic_cast<D&> (*bp); ((void)dr); } 47 catch ( const std::bad_cast & ) { return true; } 48 return false; 49 } 50 51 int main ( ) { 52 int ret_val = 0; 53 54 if ( !bad_typeid_test ()) { 55 std::cerr << "TypeID test failed!" << std::endl; 56 ret_val = 1; 57 } 58 59 if ( !bad_cast_test ()) { 60 std::cerr << "Bad cast test failed!" << std::endl; 61 ret_val = 1; 62 } 63 64 return ret_val; 65 } 66