Skip to content

Commit 2684a09

Browse files
authored
[libc++] Document guidelines for applying [[nodiscard]] (#84000)
We've been applying ``[[nodiscard]]`` more liberally recently, but we don't have any documented guidance on when it's correct to add it. This patch adds that guidance. Follow-up patches will gradually apply it to the code base.
1 parent beaff78 commit 2684a09

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
===================================================
2+
Guidelines for applying ``[[nodiscard]]`` in libc++
3+
===================================================
4+
5+
Libc++ adds ``[[nodiscard]]`` to functions in a lot of places. The standards
6+
committee has decided to not have a recommended practice where to put them, so
7+
this document lists where ``[[nodiscard]]`` should be applied in libc++.
8+
9+
When should ``[[nodiscard]]`` be added to functions?
10+
====================================================
11+
12+
``[[nodiscard]]`` should be applied to functions
13+
14+
- where discarding the return value is most likely a correctness issue.
15+
For example a locking constructor in ``unique_lock``.
16+
17+
- where discarding the return value likely points to the user wanting to do
18+
something different. For example ``vector::empty()``, which probably should
19+
have been ``vector::clear()``.
20+
21+
This can help spotting bugs easily which otherwise may take a very long time
22+
to find.
23+
24+
- which return a constant. For example ``numeric_limits::min()``.
25+
- which only observe a value. For example ``string::size()``.
26+
27+
Code that discards values from these kinds of functions is dead code. It can
28+
either be removed, or the programmer meant to do something different.
29+
30+
- where discarding the value is most likely a misuse of the function. For
31+
example ``find``.
32+
33+
This protects programmers from assuming too much about how the internals of
34+
a function work, making code more robust in the presence of future
35+
optimizations.
36+
37+
What should be done when adding ``[[nodiscard]]`` to a function?
38+
================================================================
39+
40+
Applications of ``[[nodiscard]]`` are code like any other code, so we aim to
41+
test them. This can be done with a ``.verify.cpp`` test. Many examples are
42+
available. Just look for tests with the suffix ``.nodiscard.verify.cpp``.

libcxx/docs/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ Design Documents
189189
DesignDocs/FeatureTestMacros
190190
DesignDocs/FileTimeType
191191
DesignDocs/HeaderRemovalPolicy
192+
DesignDocs/NodiscardPolicy
192193
DesignDocs/NoexceptPolicy
193194
DesignDocs/PSTLIntegration
194195
DesignDocs/ThreadingSupportAPI

0 commit comments

Comments
 (0)