From e69c53afae1900365ddd848414b49daa64acdde7 Mon Sep 17 00:00:00 2001 From: Hristo Hristov Date: Tue, 25 Nov 2025 09:42:41 +0200 Subject: [PATCH] [libc++][stack] Applied `[[nodiscard]]` `[[nodiscard]]` should be applied to functions where discarding the return value is most likely a correctness issue. - https://libcxx.llvm.org/CodingGuidelines.html#apply-nodiscard-where-relevant --- libcxx/include/stack | 6 +++--- .../test/libcxx/diagnostics/stack.nodiscard.verify.cpp | 9 +++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/libcxx/include/stack b/libcxx/include/stack index a2f285c1994b9..537b82210b9d4 100644 --- a/libcxx/include/stack +++ b/libcxx/include/stack @@ -235,9 +235,9 @@ public: # endif [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI bool empty() const { return c.empty(); } - _LIBCPP_HIDE_FROM_ABI size_type size() const { return c.size(); } - _LIBCPP_HIDE_FROM_ABI reference top() { return c.back(); } - _LIBCPP_HIDE_FROM_ABI const_reference top() const { return c.back(); } + [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI size_type size() const { return c.size(); } + [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI reference top() { return c.back(); } + [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI const_reference top() const { return c.back(); } _LIBCPP_HIDE_FROM_ABI void push(const value_type& __v) { c.push_back(__v); } # ifndef _LIBCPP_CXX03_LANG diff --git a/libcxx/test/libcxx/diagnostics/stack.nodiscard.verify.cpp b/libcxx/test/libcxx/diagnostics/stack.nodiscard.verify.cpp index 861852ae07247..a0a5b3c898a8c 100644 --- a/libcxx/test/libcxx/diagnostics/stack.nodiscard.verify.cpp +++ b/libcxx/test/libcxx/diagnostics/stack.nodiscard.verify.cpp @@ -13,6 +13,11 @@ #include void test() { - std::stack stack; - stack.empty(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}} + std::stack st; + const std::stack cst; + + st.empty(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}} + st.size(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}} + st.top(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}} + cst.top(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}} }