https://gcc.gnu.org/g:300f170835d3d34c22c1c15dfb8df42aa5ebebff

commit r16-7875-g300f170835d3d34c22c1c15dfb8df42aa5ebebff
Author: Arthur O'Dwyer <[email protected]>
Date:   Mon Mar 2 10:59:29 2026 -0500

    libstdc++: Make `std::expected` nodiscard [PR119197]
    
    The new test includes two lines that currently do not warn because of
    GCC compiler bug PR85973; the lines that do warn are the more
    important cases.
    
            PR libstdc++/119197
    
    libstdc++-v3/ChangeLog:
    
            * include/std/expected (expected, expected<void, E>): Add
            [[nodiscard]] to class.
            * testsuite/20_util/expected/119197.cc: New test.
    
    Signed-off-by: Arthur O'Dwyer <[email protected]>
    Reviewed-by: Nathan Myers <[email protected]>

Diff:
---
 libstdc++-v3/include/std/expected                 |  4 ++--
 libstdc++-v3/testsuite/20_util/expected/119197.cc | 20 ++++++++++++++++++++
 2 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/libstdc++-v3/include/std/expected 
b/libstdc++-v3/include/std/expected
index 7ab4e4595fac..21522850d7ae 100644
--- a/libstdc++-v3/include/std/expected
+++ b/libstdc++-v3/include/std/expected
@@ -367,7 +367,7 @@ namespace __expected
 /// @endcond
 
   template<typename _Tp, typename _Er>
-    class expected
+    class [[nodiscard]] expected
     {
       static_assert( ! is_reference_v<_Tp> );
       static_assert( ! is_function_v<_Tp> );
@@ -1360,7 +1360,7 @@ namespace __expected
 
   // Partial specialization for std::expected<cv void, E>
   template<typename _Tp, typename _Er> requires is_void_v<_Tp>
-    class expected<_Tp, _Er>
+    class [[nodiscard]] expected<_Tp, _Er>
     {
       static_assert( __expected::__can_be_unexpected<_Er> );
 
diff --git a/libstdc++-v3/testsuite/20_util/expected/119197.cc 
b/libstdc++-v3/testsuite/20_util/expected/119197.cc
new file mode 100644
index 000000000000..0f8ecf48cbd0
--- /dev/null
+++ b/libstdc++-v3/testsuite/20_util/expected/119197.cc
@@ -0,0 +1,20 @@
+// { dg-do compile { target c++23 } }
+
+// PR libstdc++/119197 - std::expected should be nodiscard
+
+#include <expected>
+
+std::expected<int, int> f();
+std::expected<void, int> g();
+
+void
+test_nodiscard()
+{
+  f();                         // { dg-warning "ignoring return" }
+  std::expected<int, int>(42); // PR c++/85973: should warn "ignoring 
temporary"
+  (void)f();                   // OK
+
+  g();                         // { dg-warning "ignoring return" }
+  std::expected<void, int>();  // PR c++/85973: should warn "ignoring 
temporary"
+  (void)g();                   // OK
+}

Reply via email to