xref: /llvm-project/libcxx/test/std/strings/basic.string/string.cons/move_alloc.pass.cpp (revision a40bada91aeda276a772acfbcae6e8de26755a11)
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 
9 // UNSUPPORTED: c++03
10 
11 // <string>
12 
13 // basic_string(basic_string&& str, const Allocator& alloc); // constexpr since C++20
14 
15 #include <string>
16 #include <cassert>
17 
18 #include "test_macros.h"
19 #include "test_allocator.h"
20 #include "min_allocator.h"
21 
22 template <class S>
23 TEST_CONSTEXPR_CXX20 void test(S s0, const typename S::allocator_type& a) {
24   S s1 = s0;
25   S s2(std::move(s0), a);
26   LIBCPP_ASSERT(s2.__invariants());
27   LIBCPP_ASSERT(s0.__invariants());
28   assert(s2 == s1);
29   assert(s2.capacity() >= s2.size());
30   assert(s2.get_allocator() == a);
31 }
32 
33 TEST_CONSTEXPR_CXX20 bool test() {
34   test_allocator_statistics alloc_stats;
35   {
36     typedef test_allocator<char> A;
37     typedef std::basic_string<char, std::char_traits<char>, A> S;
38 #if TEST_STD_VER > 14
39     static_assert((noexcept(S{})), "");
40 #elif TEST_STD_VER >= 11
41     static_assert((noexcept(S()) == std::is_nothrow_move_constructible<A>::value), "");
42 #endif
43     test(S(), A(3, &alloc_stats));
44     test(S("1"), A(5, &alloc_stats));
45     test(S("1234567890123456789012345678901234567890123456789012345678901234567890"), A(7, &alloc_stats));
46   }
47 
48   int alloc_count = alloc_stats.alloc_count;
49   {
50     typedef test_allocator<char> A;
51     typedef std::basic_string<char, std::char_traits<char>, A> S;
52 #if TEST_STD_VER > 14
53     static_assert((noexcept(S{})), "");
54 #elif TEST_STD_VER >= 11
55     static_assert((noexcept(S()) == std::is_nothrow_move_constructible<A>::value), "");
56 #endif
57     S s1("Twas brillig, and the slivy toves did gyre and gymbal in the wabe", A(&alloc_stats));
58     S s2(std::move(s1), A(1, &alloc_stats));
59   }
60   assert(alloc_stats.alloc_count == alloc_count);
61   {
62     typedef min_allocator<char> A;
63     typedef std::basic_string<char, std::char_traits<char>, A> S;
64 #if TEST_STD_VER > 14
65     static_assert((noexcept(S{})), "");
66 #elif TEST_STD_VER >= 11
67     static_assert((noexcept(S()) == std::is_nothrow_move_constructible<A>::value), "");
68 #endif
69     test(S(), A());
70     test(S("1"), A());
71     test(S("1234567890123456789012345678901234567890123456789012345678901234567890"), A());
72   }
73 
74   return true;
75 }
76 
77 int main(int, char**) {
78   test();
79 #if TEST_STD_VER > 17
80   static_assert(test());
81 #endif
82 
83   return 0;
84 }
85