Questions tagged [nodiscard]

[[nodiscard]] is C++17 attribute, which was extended in C++20; its purpose is to warn about discarded return value. Tag questions directly related to usage of this attribute and entities marked with this attribute.

Starting in C++17 [[nodiscard]] encourages the compiler to emit a warning when the return value of a function is discarded. It can be applied to a function, or a type.

There's a defect report that makes [[nodiscard]] work with constructors too, and it is incorporated in C++20.

Starting in C++20, nodiscard can provide a message: [[nodiscard("message")]]

To suppress the warning, cast the result to void; see How can I intentionally discard a [[nodiscard]] return value?

36 questions
1
vote
1 answer

Trying out [[nodiscard]] with no success

I am trying to test a little C++17. I am trying to do: [[nodiscard]] int get_value1() { return 42; } inline void start() { // Should generate warning get_value1(); } However, it does not. I am using Visual studio 2017. Warning level…
Alex
  • 365
  • 4
  • 17
0
votes
0 answers

Fixing compiler warning C4834 - discarding return value of std::async function

I am fixing warnings in C++ codebase. There is this function that uses std::async, but the return std::future object is not captured, so the compiler is raising C4834 warning. The function is as below: LONG WINAPI VexHandler(PEXCEPTION_POINTERS…
StewieGGriffin
  • 349
  • 1
  • 4
  • 14
0
votes
1 answer

Add nodiscard attribute to functions in third party header

I'm using a library that I can't edit and don't want to fork, which has a bunch of functions of the int error return style: int libnamespace_dosomething(int, sometype*); I'd like the library to have [[nodiscard]] or…
Jon Chesterfield
  • 2,251
  • 1
  • 20
  • 30
0
votes
1 answer

[[nodiscard]] for constant getter functions

Is there a good reason why Clang-Tidy complains about missing [[nodiscard]] for a constant member function without parameters? Could the compiler not work that out itself and warn if the return value gets discarded? In my opinion this is redundant…
Henk
  • 826
  • 3
  • 14
0
votes
0 answers

Why are std::source_location's getters not marked as [[nodiscard]]?

According to: https://en.cppreference.com/w/cpp/utility/source_location the getters aren't marked as [[nodiscard]]. constexpr uint_least32_t line() const noexcept; constexpr uint_least32_t column() const noexcept; constexpr const char*…
0
votes
1 answer

Why does [[nodiscard]] only encourage compiler to issue a warning and does not require it?

The [[nodiscard]] attribute introduced in C++17 standard, and in case of the ... potentially-evaluated discarded-value expression,..., implementations are encouraged to issue a warning in such cases. Source: n4659, C++17 final working…
Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
1 2
3