[libc++][utility] Test [[nodiscard]] std::exchange (#195807)

1. `[[nodiscard]]` was applied in https://llvm.org/PR187953
2. Also use `[[__nodiscard__]]` in pre-C++17 code.

Towards https://github.com/llvm/llvm-project/issues/172124

References:
-
https://libcxx.llvm.org/CodingGuidelines.html#apply-nodiscard-where-relevant
- https://wg21.link/utility.exchange

Co-authored-by: Hristo Hristov <zingam@outlook.com>
This commit is contained in:
Hristo Hristov 2026-05-06 21:57:01 +03:00 committed by GitHub
parent 8ac8e6fc16
commit cdf745a9f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 6 additions and 2 deletions

View file

@ -28,7 +28,7 @@ _LIBCPP_PUSH_MACROS
_LIBCPP_BEGIN_NAMESPACE_STD
template <class _T1, class _T2 = _T1>
[[nodiscard]] _LIBCPP_ALWAYS_INLINE _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _T1
[[__nodiscard__]] _LIBCPP_ALWAYS_INLINE _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _T1
__exchange(_T1& __obj, _T2&& __new_value)
_NOEXCEPT_(is_nothrow_move_constructible<_T1>::value&& is_nothrow_assignable<_T1&, _T2>::value) {
_T1 __old_value = std::move(__obj);
@ -38,7 +38,8 @@ __exchange(_T1& __obj, _T2&& __new_value)
#if _LIBCPP_STD_VER >= 14
template <class _T1, class _T2 = _T1>
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _T1 exchange(_T1& __obj, _T2&& __new_value) noexcept(
[[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI
_LIBCPP_CONSTEXPR_SINCE_CXX20 _T1 exchange(_T1& __obj, _T2&& __new_value) noexcept(
is_nothrow_move_constructible<_T1>::value && is_nothrow_assignable<_T1&, _T2>::value) {
return std::__exchange(__obj, std::forward<_T2>(__new_value));
}

View file

@ -15,6 +15,9 @@
void test() {
int i = 0;
#if TEST_STD_VER >= 14
std::exchange(i, 1); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
#endif
std::forward<int>(i); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
std::forward<int>(1); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
std::move(i); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}