swap_noexcept.pass.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. // <string>
  10. // void swap(basic_string& c)
  11. // noexcept(!allocator_type::propagate_on_container_swap::value ||
  12. // __is_nothrow_swappable<allocator_type>::value);
  13. //
  14. // In C++17, the standard says that swap shall have:
  15. // noexcept(allocator_traits<Allocator>::propagate_on_container_swap::value ||
  16. // allocator_traits<Allocator>::is_always_equal::value);
  17. // This tests a conforming extension
  18. #include <string>
  19. #include <cassert>
  20. #include "test_allocator.h"
  21. template <class T>
  22. struct some_alloc
  23. {
  24. typedef T value_type;
  25. some_alloc() {}
  26. some_alloc(const some_alloc&);
  27. void deallocate(void*, unsigned) {}
  28. typedef std::true_type propagate_on_container_swap;
  29. };
  30. template <class T>
  31. struct some_alloc2
  32. {
  33. typedef T value_type;
  34. some_alloc2() {}
  35. some_alloc2(const some_alloc2&);
  36. void deallocate(void*, unsigned) {}
  37. typedef std::false_type propagate_on_container_swap;
  38. typedef std::true_type is_always_equal;
  39. };
  40. int main()
  41. {
  42. #if __has_feature(cxx_noexcept)
  43. {
  44. typedef std::string C;
  45. C c1, c2;
  46. static_assert(noexcept(swap(c1, c2)), "");
  47. }
  48. {
  49. typedef std::basic_string<char, std::char_traits<char>, test_allocator<char>> C;
  50. C c1, c2;
  51. static_assert(noexcept(swap(c1, c2)), "");
  52. }
  53. {
  54. typedef std::basic_string<char, std::char_traits<char>, some_alloc<char>> C;
  55. C c1, c2;
  56. #if TEST_STD_VER >= 14
  57. // In c++14, if POCS is set, swapping the allocator is required not to throw
  58. static_assert( noexcept(swap(c1, c2)), "");
  59. #else
  60. static_assert(!noexcept(swap(c1, c2)), "");
  61. #endif
  62. }
  63. #if TEST_STD_VER >= 14
  64. {
  65. typedef std::basic_string<char, std::char_traits<char>, some_alloc2<char>> C;
  66. C c1, c2;
  67. // if the allocators are always equal, then the swap can be noexcept
  68. static_assert( noexcept(swap(c1, c2)), "");
  69. }
  70. #endif
  71. #endif
  72. }