| 1 |
.. title:: clang-tidy - bugprone-optional-value-conversion |
| 2 |
|
| 3 |
bugprone-optional-value-conversion |
| 4 |
================================== |
| 5 |
|
| 6 |
Detects potentially unintentional and redundant conversions where a value is |
| 7 |
extracted from an optional-like type and then used to create a new instance of |
| 8 |
the same optional-like type. |
| 9 |
|
| 10 |
These conversions might be the result of developer oversight, leftovers from |
| 11 |
code refactoring, or other situations that could lead to unintended exceptions |
| 12 |
or cases where the resulting optional is always initialized, which might be |
| 13 |
unexpected behavior. |
| 14 |
|
| 15 |
To illustrate, consider the following problematic code snippet: |
| 16 |
|
| 17 |
.. code-block:: c++ |
| 18 |
|
| 19 |
#include <optional> |
| 20 |
|
| 21 |
void print(std::optional<int>); |
| 22 |
|
| 23 |
int main() |
| 24 |
{ |
| 25 |
std::optional<int> opt; |
| 26 |
// ... |
| 27 |
|
| 28 |
// Unintentional conversion from std::optional<int> to int and back to |
| 29 |
// std::optional<int>: |
| 30 |
print(opt.value()); |
| 31 |
|
| 32 |
// ... |
| 33 |
} |
| 34 |
|
| 35 |
A better approach would be to directly pass ``opt`` to the ``print`` function |
| 36 |
without extracting its value: |
| 37 |
|
| 38 |
.. code-block:: c++ |
| 39 |
|
| 40 |
#include <optional> |
| 41 |
|
| 42 |
void print(std::optional<int>); |
| 43 |
|
| 44 |
int main() |
| 45 |
{ |
| 46 |
std::optional<int> opt; |
| 47 |
// ... |
| 48 |
|
| 49 |
// Proposed code: Directly pass the std::optional<int> to the print |
| 50 |
// function. |
| 51 |
print(opt); |
| 52 |
|
| 53 |
// ... |
| 54 |
} |
| 55 |
|
| 56 |
By passing ``opt`` directly to the print function, unnecessary conversions are |
| 57 |
avoided, and potential unintended behavior or exceptions are minimized. |
| 58 |
|
| 59 |
Value extraction using ``operator *`` is matched by default. |
| 60 |
The support for non-standard optional types such as ``boost::optional`` or |
| 61 |
``absl::optional`` may be limited. |
| 62 |
|
| 63 |
Options: |
| 64 |
-------- |
| 65 |
|
| 66 |
.. option:: OptionalTypes |
| 67 |
|
| 68 |
Semicolon-separated list of (fully qualified) optional type names or regular |
| 69 |
expressions that match the optional types. |
| 70 |
Default value is `::std::optional;::absl::optional;::boost::optional`. |
| 71 |
|
| 72 |
.. option:: ValueMethods |
| 73 |
|
| 74 |
Semicolon-separated list of (fully qualified) method names or regular |
| 75 |
expressions that match the methods. |
| 76 |
Default value is `::value$;::get$`. |