brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.0 KiB · f139650 Raw
77 lines · plain
1.. title:: clang-tidy - bugprone-optional-value-conversion2 3bugprone-optional-value-conversion4==================================5 6Detects potentially unintentional and redundant conversions where a value is7extracted from an optional-like type and then used to create a new instance of8the same optional-like type.9 10These conversions might be the result of developer oversight, leftovers from11code refactoring, or other situations that could lead to unintended exceptions12or cases where the resulting optional is always initialized, which might be13unexpected behavior.14 15To 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 to29      // std::optional<int>:30      print(opt.value());31 32      // ...33    }34 35A better approach would be to directly pass ``opt`` to the ``print`` function36without 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 print50      // function.51      print(opt);52 53      // ...54    }55 56By passing ``opt`` directly to the print function, unnecessary conversions are57avoided, and potential unintended behavior or exceptions are minimized.58 59Value extraction using ``operator *`` is matched by default.60The support for non-standard optional types such as ``boost::optional`` or61``absl::optional`` may be limited.62 63Options:64--------65 66.. option:: OptionalTypes67 68    Semicolon-separated list of (fully qualified) optional type names or regular69    expressions that match the optional types.70    Default value is `::std::optional;::absl::optional;::boost::optional`.71 72.. option:: ValueMethods73 74    Semicolon-separated list of (fully qualified) method names or regular75    expressions that match the methods.76    Default value is `::value$;::get$`.77