xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-nodiscard.rst (revision 6e566bc5523f743bc34a7e26f050f1f2b4d699a8)
1.. title:: clang-tidy - modernize-use-nodiscard
2
3modernize-use-nodiscard
4=======================
5
6Adds ``[[nodiscard]]`` attributes (introduced in C++17) to member functions in
7order to highlight at compile time which return values should not be ignored.
8
9Member functions need to satisfy the following conditions to be considered by
10this check:
11
12 - no ``[[nodiscard]]``, ``[[noreturn]]``,
13   ``__attribute__((warn_unused_result))``,
14   ``[[clang::warn_unused_result]]`` nor ``[[gcc::warn_unused_result]]``
15   attribute,
16 - non-void return type,
17 - non-template return types,
18 - const member function,
19 - non-variadic functions,
20 - no non-const reference parameters,
21 - no pointer parameters,
22 - no template parameters,
23 - no template function parameters,
24 - not be a member of a class with mutable member variables,
25 - no Lambdas,
26 - no conversion functions.
27
28Such functions have no means of altering any state or passing values other than
29via the return type. Unless the member functions are altering state via some
30external call (e.g. I/O).
31
32Example
33-------
34
35.. code-block:: c++
36
37    bool empty() const;
38    bool empty(int i) const;
39
40transforms to:
41
42.. code-block:: c++
43
44    [[nodiscard]] bool empty() const;
45    [[nodiscard]] bool empty(int i) const;
46
47Options
48-------
49
50.. option:: ReplacementString
51
52    Specifies a macro to use instead of ``[[nodiscard]]``. This is useful when
53    maintaining source code that needs to compile with a pre-C++17 compiler.
54
55Example
56^^^^^^^
57
58.. code-block:: c++
59
60    bool empty() const;
61    bool empty(int i) const;
62
63transforms to:
64
65.. code-block:: c++
66
67    NO_DISCARD bool empty() const;
68    NO_DISCARD bool empty(int i) const;
69
70if the :option:`ReplacementString` option is set to `NO_DISCARD`.
71
72.. note::
73
74    If the :option:`ReplacementString` is not a C++ attribute, but instead a
75    macro, then that macro must be defined in scope or the fix-it will not be
76    applied.
77
78.. note::
79
80    For alternative ``__attribute__`` syntax options to mark functions as
81    ``[[nodiscard]]`` in non-c++17 source code.
82    See https://clang.llvm.org/docs/AttributeReference.html#nodiscard-warn-unused-result
83