Bug 109941 - [feat req] Add an option to mark STL types as nodiscard
Summary: [feat req] Add an option to mark STL types as nodiscard
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: libstdc++ (show other bugs)
Version: unknown
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on: 85973
Blocks:
  Show dependency treegraph
 
Reported: 2023-05-23 12:15 UTC by Roy Jacobson
Modified: 2024-12-16 11:47 UTC (History)
4 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2024-12-16 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Roy Jacobson 2023-05-23 12:15:01 UTC
I would find it useful if there was a macro or some other option to mark types like std::error_code, std::errc, and std::expected as [[nodiscard]] so developers will be forced to handle the errors.
Comment 1 Jiang An 2023-05-23 12:36:07 UTC
FYI MSVC STL currently applies [[nodiscard]] to std::lock_guard and std::scoped_lock.
Comment 2 Roy Jacobson 2023-05-23 12:39:59 UTC
Right, libc++ do that as well since 2019 - https://reviews.llvm.org/D65900?id=213975.

Although with the RAII classes I think you need to [[nodiscard]] the constructor which I think (?) is a compiler extension. And you're also much less likely to have false positives with that so you can actually do that unconditionally :)
Comment 3 Jonathan Wakely 2023-05-23 13:24:07 UTC
That doesn't currently work with GCC, so there's not much point doing it.
Comment 4 Roy Jacobson 2023-05-23 13:31:45 UTC
The linked bug is about nodiscard applied to the class together with ignoring temporary objects. But GCC will when the type is the return value or when the nodiscard is applied to the constructor:

class [[nodiscard]] err {};
err f();

void g() {
    f(); // Warning emitted
}

struct RAII {
    [[nodiscard]] RAII(int x);
};

void h() {
    RAII(0); // Warning emitted
}
Comment 5 Arthur O'Dwyer 2024-12-15 18:20:13 UTC
https://quuxplusone.github.io/blog/2024/12/08/should-expected-be-nodiscard/
https://github.com/microsoft/STL/pull/5174

As of this past Friday, Microsoft STL's std::expected is finally marked nodiscard.
LLVM/Clang's own `llvm::Expected` type has been marked nodiscard since 2016.
I encourage libstdc++ to follow suit, for `expected` specifically.

(Personally I'm less sure that nodiscard belongs at all on `error_code` or `errc`; Microsoft doesn't mark those yet. And on the exception hierarchy, which Microsoft also marked last Friday, I think it's harmless and in keeping with Microsoft's aggressive marking strategy, but perhaps not super helpful either.)
Comment 6 Roy Jacobson 2024-12-15 19:36:33 UTC
Also worth mentioning that clang-tidy diagnoses this under bugprone-unused-return-value since May 23.