copy.pass.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. // UNSUPPORTED: c++98, c++03, c++11, c++14
  10. // <optional>
  11. // optional<T>& operator=(const optional<T>& rhs);
  12. #include <optional>
  13. #include <type_traits>
  14. #include <cassert>
  15. #include "test_macros.h"
  16. #include "archetypes.hpp"
  17. using std::optional;
  18. struct X
  19. {
  20. static bool throw_now;
  21. X() = default;
  22. X(const X&)
  23. {
  24. if (throw_now)
  25. TEST_THROW(6);
  26. }
  27. };
  28. bool X::throw_now = false;
  29. template <class Tp>
  30. constexpr bool assign_empty(optional<Tp>&& lhs) {
  31. const optional<Tp> rhs;
  32. lhs = rhs;
  33. return !lhs.has_value() && !rhs.has_value();
  34. }
  35. template <class Tp>
  36. constexpr bool assign_value(optional<Tp>&& lhs) {
  37. const optional<Tp> rhs(101);
  38. lhs = rhs;
  39. return lhs.has_value() && rhs.has_value() && *lhs == *rhs;
  40. }
  41. int main()
  42. {
  43. {
  44. using O = optional<int>;
  45. LIBCPP_STATIC_ASSERT(assign_empty(O{42}), "");
  46. LIBCPP_STATIC_ASSERT(assign_value(O{42}), "");
  47. assert(assign_empty(O{42}));
  48. assert(assign_value(O{42}));
  49. }
  50. {
  51. using O = optional<TrivialTestTypes::TestType>;
  52. LIBCPP_STATIC_ASSERT(assign_empty(O{42}), "");
  53. LIBCPP_STATIC_ASSERT(assign_value(O{42}), "");
  54. assert(assign_empty(O{42}));
  55. assert(assign_value(O{42}));
  56. }
  57. {
  58. using O = optional<TestTypes::TestType>;
  59. assert(assign_empty(O{42}));
  60. assert(assign_value(O{42}));
  61. }
  62. {
  63. using T = TestTypes::TestType;
  64. T::reset();
  65. optional<T> opt(3);
  66. const optional<T> opt2;
  67. assert(T::alive == 1);
  68. opt = opt2;
  69. assert(T::alive == 0);
  70. assert(!opt2.has_value());
  71. assert(!opt.has_value());
  72. }
  73. #ifndef TEST_HAS_NO_EXCEPTIONS
  74. {
  75. optional<X> opt;
  76. optional<X> opt2(X{});
  77. assert(static_cast<bool>(opt2) == true);
  78. try
  79. {
  80. X::throw_now = true;
  81. opt = opt2;
  82. assert(false);
  83. }
  84. catch (int i)
  85. {
  86. assert(i == 6);
  87. assert(static_cast<bool>(opt) == false);
  88. }
  89. }
  90. #endif
  91. }