tst-assert-c++.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Tests for interactions between C++ and assert.
  2. Copyright (C) 2017-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. /* Undefine NDEBUG to ensure the build system e.g. CFLAGS/CXXFLAGS
  16. does not disable the asserts we want to test. */
  17. #undef NDEBUG
  18. #include <assert.h>
  19. #if __GNUC_PREREQ (5, 0)
  20. /* The C++ standard requires that if the assert argument is a constant
  21. subexpression, then the assert itself is one, too. */
  22. constexpr int
  23. check_constexpr ()
  24. {
  25. return (assert (true), 1);
  26. }
  27. /* Objects of this class can be contextually converted to bool, but
  28. cannot be compared to int. */
  29. struct no_int
  30. {
  31. no_int () = default;
  32. no_int (const no_int &) = delete;
  33. explicit operator bool () const
  34. {
  35. return true;
  36. }
  37. bool operator! () const; /* No definition. */
  38. template <class T> bool operator== (T) const; /* No definition. */
  39. template <class T> bool operator!= (T) const; /* No definition. */
  40. };
  41. /* This class tests that operator== is not used by assert. */
  42. struct bool_and_int
  43. {
  44. bool_and_int () = default;
  45. bool_and_int (const no_int &) = delete;
  46. explicit operator bool () const
  47. {
  48. return true;
  49. }
  50. bool operator! () const; /* No definition. */
  51. template <class T> bool operator== (T) const; /* No definition. */
  52. template <class T> bool operator!= (T) const; /* No definition. */
  53. };
  54. static int
  55. do_test ()
  56. {
  57. {
  58. no_int value;
  59. assert (value);
  60. }
  61. {
  62. bool_and_int value;
  63. assert (value);
  64. }
  65. return 0;
  66. }
  67. #else
  68. #include <support/test-driver.h>
  69. static int
  70. do_test ()
  71. {
  72. return EXIT_UNSUPPORTED;
  73. }
  74. #endif
  75. #include <support/test-driver.c>