| 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``. |