1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // UNSUPPORTED: c++03, c++11
14 // template<class T, class U=T>
15 // constexpr T // constexpr after C++17
16 // exchange(T& obj, U&& new_value)
17 // noexcept(is_nothrow_move_constructible<T>::value && is_nothrow_assignable<T&, U>::value);
23 #include "test_macros.h"
26 TEST_CONSTEXPR
bool test_constexpr() {
29 if (12 != std::exchange(v
,23) || v
!= 23)
32 if (23 != std::exchange(v
,static_cast<short>(67)) || v
!= 67)
35 if (67 != std::exchange
<int, short>(v
, {}) || v
!= 0)
41 template<bool Move
, bool Assign
>
43 TestNoexcept() = default;
44 TestNoexcept(const TestNoexcept
&);
45 TestNoexcept(TestNoexcept
&&) noexcept(Move
);
46 TestNoexcept
& operator=(const TestNoexcept
&);
47 TestNoexcept
& operator=(TestNoexcept
&&) noexcept(Assign
);
50 constexpr bool test_noexcept() {
53 ASSERT_NOEXCEPT(std::exchange(x
, 42));
56 TestNoexcept
<true, true> x
;
57 ASSERT_NOEXCEPT(std::exchange(x
, std::move(x
)));
58 ASSERT_NOT_NOEXCEPT(std::exchange(x
, x
)); // copy-assignment is not noexcept
61 TestNoexcept
<true, false> x
;
62 ASSERT_NOT_NOEXCEPT(std::exchange(x
, std::move(x
)));
65 TestNoexcept
<false, true> x
;
66 ASSERT_NOT_NOEXCEPT(std::exchange(x
, std::move(x
)));
76 assert ( std::exchange ( v
, 23 ) == 12 );
78 assert ( std::exchange ( v
, static_cast<short>(67) ) == 23 );
81 assert ((std::exchange
<int, short> ( v
, {} )) == 67 );
88 assert ( !std::exchange ( b
, true ));
93 const std::string
s1 ( "Hi Mom!" );
94 const std::string
s2 ( "Yo Dad!" );
95 std::string s3
= s1
; // Mom
96 assert ( std::exchange ( s3
, s2
) == s1
);
98 assert ( std::exchange ( s3
, "Hi Mom!" ) == s2
);
102 assert ( std::exchange ( s3
, {} ) == s2
);
103 assert ( s3
.size () == 0 );
106 assert ( std::exchange ( s3
, "" ) == s2
);
107 assert ( s3
.size () == 0 );
110 #if TEST_STD_VER > 17
111 static_assert(test_constexpr());
114 static_assert(test_noexcept(), "");