copy.pass.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // UNSUPPORTED: c++98, c++03, c++11, c++14
  9. // <optional>
  10. // optional<T>& operator=(const optional<T>& rhs); // constexpr in C++20
  11. #include <optional>
  12. #include <type_traits>
  13. #include <cassert>
  14. #include "test_macros.h"
  15. #include "archetypes.h"
  16. using std::optional;
  17. struct X
  18. {
  19. static bool throw_now;
  20. X() = default;
  21. X(const X&)
  22. {
  23. if (throw_now)
  24. TEST_THROW(6);
  25. }
  26. };
  27. bool X::throw_now = false;
  28. template <class Tp>
  29. constexpr bool assign_empty(optional<Tp>&& lhs) {
  30. const optional<Tp> rhs;
  31. lhs = rhs;
  32. return !lhs.has_value() && !rhs.has_value();
  33. }
  34. template <class Tp>
  35. constexpr bool assign_value(optional<Tp>&& lhs) {
  36. const optional<Tp> rhs(101);
  37. lhs = rhs;
  38. return lhs.has_value() && rhs.has_value() && *lhs == *rhs;
  39. }
  40. int main(int, char**)
  41. {
  42. {
  43. using O = optional<int>;
  44. #if TEST_STD_VER > 17
  45. LIBCPP_STATIC_ASSERT(assign_empty(O{42}), "");
  46. LIBCPP_STATIC_ASSERT(assign_value(O{42}), "");
  47. #endif
  48. assert(assign_empty(O{42}));
  49. assert(assign_value(O{42}));
  50. }
  51. {
  52. using O = optional<TrivialTestTypes::TestType>;
  53. #if TEST_STD_VER > 17
  54. LIBCPP_STATIC_ASSERT(assign_empty(O{42}), "");
  55. LIBCPP_STATIC_ASSERT(assign_value(O{42}), "");
  56. #endif
  57. assert(assign_empty(O{42}));
  58. assert(assign_value(O{42}));
  59. }
  60. {
  61. using O = optional<TestTypes::TestType>;
  62. assert(assign_empty(O{42}));
  63. assert(assign_value(O{42}));
  64. }
  65. {
  66. using T = TestTypes::TestType;
  67. T::reset();
  68. optional<T> opt(3);
  69. const optional<T> opt2;
  70. assert(T::alive == 1);
  71. opt = opt2;
  72. assert(T::alive == 0);
  73. assert(!opt2.has_value());
  74. assert(!opt.has_value());
  75. }
  76. #ifndef TEST_HAS_NO_EXCEPTIONS
  77. {
  78. optional<X> opt;
  79. optional<X> opt2(X{});
  80. assert(static_cast<bool>(opt2) == true);
  81. try
  82. {
  83. X::throw_now = true;
  84. opt = opt2;
  85. assert(false);
  86. }
  87. catch (int i)
  88. {
  89. assert(i == 6);
  90. assert(static_cast<bool>(opt) == false);
  91. }
  92. }
  93. #endif
  94. return 0;
  95. }