1.. title:: clang-tidy - bugprone-optional-value-conversion 2 3bugprone-optional-value-conversion 4================================== 5 6Detects potentially unintentional and redundant conversions where a value is 7extracted from an optional-like type and then used to create a new instance of 8the same optional-like type. 9 10These conversions might be the result of developer oversight, leftovers from 11code refactoring, or other situations that could lead to unintended exceptions 12or cases where the resulting optional is always initialized, which might be 13unexpected 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 to 29 // std::optional<int>: 30 print(opt.value()); 31 32 // ... 33 } 34 35A better approach would be to directly pass ``opt`` to the ``print`` function 36without 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 56By passing ``opt`` directly to the print function, unnecessary conversions are 57avoided, 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`` or 61``absl::optional`` may be limited. 62 63Options: 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$`. 77