test_rtti.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <typeinfo>
  7. #include "unity.h"
  8. #ifdef CONFIG_COMPILER_CXX_RTTI
  9. using namespace std;
  10. class Base {
  11. public:
  12. virtual ~Base() {} ;
  13. virtual char name() = 0;
  14. };
  15. class DerivedA : public Base {
  16. public:
  17. char name() override
  18. {
  19. return 'A';
  20. }
  21. };
  22. class DerivedB : public Base {
  23. public:
  24. char name() override
  25. {
  26. return 'B';
  27. }
  28. };
  29. TEST_CASE("unsuccessful dynamic cast on pointer returns nullptr", "[cxx]")
  30. {
  31. Base *base = new DerivedA();
  32. DerivedB *derived = dynamic_cast<DerivedB*>(base);
  33. TEST_ASSERT_EQUAL(derived, nullptr);
  34. delete base;
  35. derived = nullptr;
  36. }
  37. TEST_CASE("dynamic cast works", "[cxx]")
  38. {
  39. Base *base = new DerivedA();
  40. DerivedA *derived = dynamic_cast<DerivedA*>(base);
  41. TEST_ASSERT_EQUAL(derived, base);
  42. delete base;
  43. }
  44. TEST_CASE("typeid of dynamic objects works", "[cxx]")
  45. {
  46. Base *base = new DerivedA();
  47. DerivedA *derived = dynamic_cast<DerivedA*>(base);
  48. TEST_ASSERT_EQUAL(typeid(*derived).hash_code(), typeid(*base).hash_code());
  49. TEST_ASSERT_EQUAL(typeid(*derived).hash_code(), typeid(DerivedA).hash_code());
  50. delete base;
  51. derived = nullptr;
  52. }
  53. int dummy_function1(int arg1, double arg2);
  54. int dummy_function2(int arg1, double arg2);
  55. TEST_CASE("typeid of function works", "[cxx]")
  56. {
  57. TEST_ASSERT_EQUAL(typeid(dummy_function1).hash_code(), typeid(dummy_function2).hash_code());
  58. }
  59. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  60. TEST_CASE("unsuccessful dynamic cast on reference throws exception", "[cxx]")
  61. {
  62. bool thrown = false;
  63. DerivedA derived_a;
  64. Base &base = derived_a;
  65. try {
  66. DerivedB &derived_b = dynamic_cast<DerivedB&>(base);
  67. derived_b.name(); // suppress warning
  68. } catch (bad_cast &e) {
  69. thrown = true;
  70. }
  71. TEST_ASSERT(thrown);
  72. }
  73. TEST_CASE("typeid on nullptr throws bad_typeid", "[cxx]")
  74. {
  75. Base *base = nullptr;
  76. size_t hash = 0;
  77. bool thrown = false;
  78. try {
  79. hash = typeid(*base).hash_code();
  80. } catch (bad_typeid &e) {
  81. thrown = true;
  82. }
  83. TEST_ASSERT_EQUAL(0, hash);
  84. TEST_ASSERT(thrown);
  85. }
  86. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  87. #endif // CONFIG_COMPILER_CXX_RTTI