[libcxx-commits] [libcxx] [libc++][RFC] Document when to apply [[nodiscard]] (PR #84000)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Mar 28 08:45:20 PDT 2024


================
@@ -0,0 +1,34 @@
+======================================
+``[[nodiscard]]`` extensions in libc++
+======================================
+
+Libc++ adds ``[[nodiscard]]`` to functions in a lot more places than the
+standard does. Any applications of ``[[nodiscard]]`` that aren't required by the
+standard written as ``_LIBCPP_NODISCARD_EXT`` to make it possible to disable
+them. This can be done by defining ``_LIBCPP_DISABLE_NODISCARD_EXT``.
+
+When should ``[[nodiscard]]`` be added to functions?
+====================================================
+
+``[[nodiscard]]`` should be applied to functions
+
+- where it is most likely a correctness issue when discarding the return value.
+  For example a locking constructor in ``unique_lock``.
+- where most likely something similar was meant if the return value is
+  discarded. For example ``vector::empty()``, which probably should have
+  been ``clear()``.
+
+  This can help spotting bugs easily which otherwise may take a very long time
+  to find.
+
+- which return a constant. For example ``numeric_limits::min()``.
+- which only observe a value. For example ``string::size()``.
+
+  Code that discards values from these kinds of functions is dead code. It can
+  either be removed, or the programmer meant to do something different.
+
+- where discarding the value is most likely a misuse of the function. For
+  example ``find``.
----------------
ldionne wrote:

Not attached to this line: this document should touch on the testing expectations (and briefly how to do it without getting into any details). I'd expect something like

> Applications of `[[nodiscard]]` are code like any other code, so we aim to test them. This can be done with a `.verify.cpp` test and many examples are available (look for tests named `xxxxx.nodiscard.verify.cpp`)

https://github.com/llvm/llvm-project/pull/84000


More information about the libcxx-commits mailing list