Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/modernize/use-nodiscard.rst

raw
1 .. title:: clang-tidy - modernize-use-nodiscard
2
3 modernize-use-nodiscard
4 =======================
5
6 Adds ``[[nodiscard]]`` attributes (introduced in C++17) to member functions in
7 order to highlight at compile time which return values should not be ignored.
8
9 Member functions need to satisfy the following conditions to be considered by
10 this 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
28 Such functions have no means of altering any state or passing values other than
29 via the return type. Unless the member functions are altering state via some
30 external call (e.g. I/O).
31
32 Example
33 -------
34
35 .. code-block:: c++
36
37 bool empty() const;
38 bool empty(int i) const;
39
40 transforms to:
41
42 .. code-block:: c++
43
44 [[nodiscard]] bool empty() const;
45 [[nodiscard]] bool empty(int i) const;
46
47 Options
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
55 Example
56 ^^^^^^^
57
58 .. code-block:: c++
59
60 bool empty() const;
61 bool empty(int i) const;
62
63 transforms to:
64
65 .. code-block:: c++
66
67 NO_DISCARD bool empty() const;
68 NO_DISCARD bool empty(int i) const;
69
70 if 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