| 1 | // { dg-do run { target c++14 } } |
| 2 | |
| 3 | // Copyright (C) 2013-2025 Free Software Foundation, Inc. |
| 4 | // |
| 5 | // This file is part of the GNU ISO C++ Library. This library is free |
| 6 | // software; you can redistribute it and/or modify it under the |
| 7 | // terms of the GNU General Public License as published by the |
| 8 | // Free Software Foundation; either version 3, or (at your option) |
| 9 | // any later version. |
| 10 | |
| 11 | // This library is distributed in the hope that it will be useful, |
| 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | // GNU General Public License for more details. |
| 15 | |
| 16 | // You should have received a copy of the GNU General Public License along |
| 17 | // with this library; see the file COPYING3. If not see |
| 18 | // <http://www.gnu.org/licenses/>. |
| 19 | |
| 20 | // 20.2.3 exchange [utility.exchange] |
| 21 | |
| 22 | #include <utility> |
| 23 | #include <type_traits> |
| 24 | #include <testsuite_hooks.h> |
| 25 | |
| 26 | void |
| 27 | test01() |
| 28 | { |
| 29 | const unsigned val = 4; |
| 30 | int i = 1; |
| 31 | auto prev = std::exchange(i, val); |
| 32 | static_assert( std::is_same<decltype(prev), int>::value, "return type" ); |
| 33 | VERIFY( i == 4 ); |
| 34 | VERIFY( prev == 1 ); |
| 35 | prev = std::exchange(i, 3); |
| 36 | VERIFY( i == 3 ); |
| 37 | VERIFY( prev == 4 ); |
| 38 | } |
| 39 | |
| 40 | // Default construction from empty braces |
| 41 | void |
| 42 | test02() |
| 43 | { |
| 44 | struct DefaultConstructible |
| 45 | { |
| 46 | DefaultConstructible(int i = 0) : value(i) { } |
| 47 | int value; |
| 48 | }; |
| 49 | |
| 50 | DefaultConstructible x = 1; |
| 51 | auto old = std::exchange(x, {}); |
| 52 | VERIFY( x.value == 0 ); |
| 53 | VERIFY( old.value == 1 ); |
| 54 | } |
| 55 | |
| 56 | int f(int) { return 0; } |
| 57 | |
| 58 | double f(double) { return 0; } |
| 59 | |
| 60 | // Deduce type of overloaded function |
| 61 | void |
| 62 | test03() |
| 63 | { |
| 64 | int (*fp)(int); |
| 65 | std::exchange(fp, &f); |
| 66 | VERIFY( fp != nullptr ); |
| 67 | } |
| 68 | |
| 69 | void test04() |
| 70 | { |
| 71 | struct From { }; |
| 72 | struct To { |
| 73 | int value = 0; |
| 74 | To() = default; |
| 75 | To(const To&) = default; |
| 76 | To(const From&) = delete; |
| 77 | To& operator=(const From&) { value = 1; return *this; } |
| 78 | To& operator=(From&&) { value = 2; return *this; } |
| 79 | }; |
| 80 | |
| 81 | To t; |
| 82 | From f; |
| 83 | |
| 84 | auto prev = std::exchange(t, f); |
| 85 | VERIFY( t.value == 1 ); |
| 86 | VERIFY( prev.value == 0 ); |
| 87 | |
| 88 | prev = std::exchange(t, From{}); |
| 89 | VERIFY( t.value == 2 ); |
| 90 | VERIFY( prev.value == 1 ); |
| 91 | } |
| 92 | |
| 93 | int |
| 94 | main() |
| 95 | { |
| 96 | test01(); |
| 97 | test02(); |
| 98 | test03(); |
| 99 | test04(); |
| 100 | return 0; |
| 101 | } |