[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>
diff --git a/libcxx/include/__utility/exchange.h b/libcxx/include/__utility/exchange.h
index 368818c..c8af46f 100644
--- a/libcxx/include/__utility/exchange.h
+++ b/libcxx/include/__utility/exchange.h
@@ -28,7 +28,7 @@
_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 @@
#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));
}
diff --git a/libcxx/test/libcxx/utilities/utility/nodiscard.verify.cpp b/libcxx/test/libcxx/utilities/utility/nodiscard.verify.cpp
index 3d6ff423..1de9c17 100644
--- a/libcxx/test/libcxx/utilities/utility/nodiscard.verify.cpp
+++ b/libcxx/test/libcxx/utilities/utility/nodiscard.verify.cpp
@@ -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}}