• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===----------------------- cxa_bad_cast.pass.cpp ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // UNSUPPORTED: c++98, c++03
11 
12 #include <cxxabi.h>
13 #include <cassert>
14 #include <stdlib.h>
15 #include <exception>
16 #include <typeinfo>
17 
18 class Base {
foo()19   virtual void foo() {};
20 };
21 
22 class Derived : public Base {};
23 
test_bad_cast(Base & b)24 Derived &test_bad_cast(Base& b) {
25   return dynamic_cast<Derived&>(b);
26 }
27 
28 Base gB;
29 
my_terminate()30 void my_terminate() { exit(0); }
31 
main()32 int main ()
33 {
34     // swap-out the terminate handler
35     void (*default_handler)() = std::get_terminate();
36     std::set_terminate(my_terminate);
37 
38 #ifndef LIBCXXABI_HAS_NO_EXCEPTIONS
39     try {
40 #endif
41         Derived &d = test_bad_cast(gB);
42         assert(false);
43         ((void)d);
44 #ifndef LIBCXXABI_HAS_NO_EXCEPTIONS
45     } catch (std::bad_cast) {
46         // success
47         return 0;
48     } catch (...) {
49         assert(false);
50     }
51 #endif
52 
53     // failure, restore the default terminate handler and fire
54     std::set_terminate(default_handler);
55     std::terminate();
56 }
57