scope_exit.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Range v3 library
  2. //
  3. // Copyright Eric Niebler 2017-present
  4. //
  5. // Use, modification and distribution is subject to the
  6. // Boost Software License, Version 1.0. (See accompanying
  7. // file LICENSE_1_0.txt or copy at
  8. // http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. // Project home: https://github.com/ericniebler/range-v3
  11. #include <range/v3/utility/scope_exit.hpp>
  12. #include "../simple_test.hpp"
  13. #include "../test_utils.hpp"
  14. RANGES_DIAGNOSTIC_IGNORE_UNNEEDED_MEMBER
  15. namespace
  16. {
  17. int i = 0;
  18. struct NoexceptFalse
  19. {
  20. NoexceptFalse() {}
  21. NoexceptFalse(NoexceptFalse const &) noexcept(false)
  22. {}
  23. NoexceptFalse(NoexceptFalse &&) noexcept(false)
  24. {
  25. CHECK(false);
  26. }
  27. void operator()() const
  28. {
  29. ++i;
  30. }
  31. };
  32. struct ThrowingCopy
  33. {
  34. ThrowingCopy() {}
  35. [[noreturn]] ThrowingCopy(ThrowingCopy const &) noexcept(false)
  36. {
  37. throw 42;
  38. }
  39. ThrowingCopy(ThrowingCopy &&) noexcept(false)
  40. {
  41. CHECK(false);
  42. }
  43. void operator()() const
  44. {
  45. ++i;
  46. }
  47. };
  48. }
  49. int main()
  50. {
  51. std::cout << "\nTesting scope_exit\n";
  52. {
  53. auto guard = ranges::make_scope_exit([&]{++i;});
  54. CHECK(i == 0);
  55. }
  56. CHECK(i == 1);
  57. {
  58. auto guard = ranges::make_scope_exit(NoexceptFalse{});
  59. CHECK(i == 1);
  60. }
  61. CHECK(i == 2);
  62. try
  63. {
  64. auto guard = ranges::make_scope_exit(ThrowingCopy{});
  65. CHECK(false);
  66. }
  67. catch(int)
  68. {}
  69. CHECK(i == 3);
  70. return ::test_result();
  71. }