throw_with_nested.pass.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. //===----------------------------------------------------------------------===//
  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. // XFAIL: libcpp-no-exceptions
  10. // <exception>
  11. // class nested_exception;
  12. // template<class T> void throw_with_nested [[noreturn]] (T&& t);
  13. #include <exception>
  14. #include <cstdlib>
  15. #include <cassert>
  16. class A
  17. {
  18. int data_;
  19. public:
  20. explicit A(int data) : data_(data) {}
  21. friend bool operator==(const A& x, const A& y) {return x.data_ == y.data_;}
  22. };
  23. class B
  24. : public std::nested_exception
  25. {
  26. int data_;
  27. public:
  28. explicit B(int data) : data_(data) {}
  29. friend bool operator==(const B& x, const B& y) {return x.data_ == y.data_;}
  30. };
  31. #if __cplusplus > 201103L
  32. struct Final final {};
  33. #endif
  34. int main()
  35. {
  36. {
  37. try
  38. {
  39. A a(3);
  40. std::throw_with_nested(a);
  41. assert(false);
  42. }
  43. catch (const A& a)
  44. {
  45. assert(a == A(3));
  46. }
  47. }
  48. {
  49. try
  50. {
  51. A a(4);
  52. std::throw_with_nested(a);
  53. assert(false);
  54. }
  55. catch (const std::nested_exception& e)
  56. {
  57. assert(e.nested_ptr() == nullptr);
  58. }
  59. }
  60. {
  61. try
  62. {
  63. B b(5);
  64. std::throw_with_nested(b);
  65. assert(false);
  66. }
  67. catch (const B& b)
  68. {
  69. assert(b == B(5));
  70. }
  71. }
  72. {
  73. try
  74. {
  75. B b(6);
  76. std::throw_with_nested(b);
  77. assert(false);
  78. }
  79. catch (const std::nested_exception& e)
  80. {
  81. assert(e.nested_ptr() == nullptr);
  82. const B& b = dynamic_cast<const B&>(e);
  83. assert(b == B(6));
  84. }
  85. }
  86. {
  87. try
  88. {
  89. int i = 7;
  90. std::throw_with_nested(i);
  91. assert(false);
  92. }
  93. catch (int i)
  94. {
  95. assert(i == 7);
  96. }
  97. }
  98. #if __cplusplus > 201103L
  99. {
  100. try
  101. {
  102. std::throw_with_nested(Final());
  103. assert(false);
  104. }
  105. catch (const Final &)
  106. {
  107. }
  108. }
  109. #endif
  110. }