1 .. title:: clang-tidy - bugprone-unchecked-optional-access
3 bugprone-unchecked-optional-access
4 ==================================
6 *Note*: This check uses a flow-sensitive static analysis to produce its
7 results. Therefore, it may be more resource intensive (RAM, CPU) than the
8 average clang-tidy check.
10 This check identifies unsafe accesses to values contained in
11 ``std::optional<T>``, ``absl::optional<T>``, ``base::Optional<T>``, or
12 ``folly::Optional<T>`` objects. Below we will refer to all these types
13 collectively as ``optional<T>``.
15 An access to the value of an ``optional<T>`` occurs when one of its ``value``,
16 ``operator*``, or ``operator->`` member functions is invoked. To align with
17 common misconceptions, the check considers these member functions as equivalent,
18 even though there are subtle differences related to exceptions versus undefined
19 behavior. See *Additional notes*, below, for more information on this topic.
21 An access to the value of an ``optional<T>`` is considered safe if and only if
22 code in the local scope (for example, a function body) ensures that the
23 ``optional<T>`` has a value in all possible execution paths that can reach the
24 access. That should happen either through an explicit check, using the
25 ``optional<T>::has_value`` member function, or by constructing the
26 ``optional<T>`` in a way that shows that it unambiguously holds a value (e.g
27 using ``std::make_optional`` which always returns a populated
28 ``std::optional<T>``).
30 Below we list some examples, starting with unsafe optional access patterns,
31 followed by safe access patterns.
33 Unsafe access patterns
34 ~~~~~~~~~~~~~~~~~~~~~~
36 Access the value without checking if it exists
37 ----------------------------------------------
39 The check flags accesses to the value that are not locally guarded by
44 void f(std::optional<int> opt) {
45 use(*opt); // unsafe: it is unclear whether `opt` has a value.
48 Access the value in the wrong branch
49 ------------------------------------
51 The check is aware of the state of an optional object in different
52 branches of the code. For example:
56 void f(std::optional<int> opt) {
57 if (opt.has_value()) {
59 use(opt.value()); // unsafe: it is clear that `opt` does *not* have a value.
63 Assume a function result to be stable
64 -------------------------------------
66 The check is aware that function results might not be stable. That is,
67 consecutive calls to the same function might return different values.
73 if (foo.opt().has_value()) {
74 use(*foo.opt()); // unsafe: it is unclear whether `foo.opt()` has a value.
78 Rely on invariants of uncommon APIs
79 -----------------------------------
81 The check is unaware of invariants of uncommon APIs. For example:
86 if (foo.HasProperty("bar")) {
87 use(*foo.GetProperty("bar")); // unsafe: it is unclear whether `foo.GetProperty("bar")` has a value.
91 Check if a value exists, then pass the optional to another function
92 -------------------------------------------------------------------
94 The check relies on local reasoning. The check and value access must
95 both happen in the same function. An access is considered unsafe even if
96 the caller of the function performing the access ensures that the
97 optional has a value. For example:
101 void g(std::optional<int> opt) {
102 use(*opt); // unsafe: it is unclear whether `opt` has a value.
105 void f(std::optional<int> opt) {
106 if (opt.has_value()) {
114 Check if a value exists, then access the value
115 ----------------------------------------------
117 The check recognizes all straightforward ways for checking if a value
118 exists and accessing the value contained in an optional object. For
123 void f(std::optional<int> opt) {
124 if (opt.has_value()) {
130 Check if a value exists, then access the value from a copy
131 ----------------------------------------------------------
133 The criteria that the check uses is semantic, not syntactic. It
134 recognizes when a copy of the optional object being accessed is known to
135 have a value. For example:
139 void f(std::optional<int> opt1) {
140 if (opt1.has_value()) {
141 std::optional<int> opt2 = opt1;
147 Ensure that a value exists using common macros
148 ----------------------------------------------
150 The check is aware of common macros like ``CHECK`` and ``DCHECK``. Those can be
151 used to ensure that an optional object has a value. For example:
155 void f(std::optional<int> opt) {
156 DCHECK(opt.has_value());
160 Ensure that a value exists, then access the value in a correlated branch
161 ------------------------------------------------------------------------
163 The check is aware of correlated branches in the code and can figure out
164 when an optional object is ensured to have a value on all execution
165 paths that lead to an access. For example:
169 void f(std::optional<int> opt) {
171 if (opt.has_value() && SomeOtherCondition()) {
180 Stabilize function results
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~
183 Since function results are not assumed to be stable across calls, it is best to
184 store the result of the function call in a local variable and use that variable
185 to access the value. For example:
190 if (const auto& foo_opt = foo.opt(); foo_opt.has_value()) {
195 Do not rely on uncommon-API invariants
196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 When uncommon APIs guarantee that an optional has contents, do not rely on it --
199 instead, check explicitly that the optional object has a value. For example:
204 if (const auto& property = foo.GetProperty("bar")) {
209 instead of the `HasProperty`, `GetProperty` pairing we saw above.
211 Do not rely on caller-performed checks
212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214 If you know that all of a function's callers have checked that an optional
215 argument has a value, either change the function to take the value directly or
216 check the optional again in the local scope of the callee. For example:
224 void f(std::optional<int> opt) {
225 if (opt.has_value()) {
235 std::optional<int> opt;
240 if (s.opt.has_value() && s.x > 10) {
245 if (s.opt.has_value()) {
253 Aliases created via ``using`` declarations
254 ------------------------------------------
256 The check is aware of aliases of optional types that are created via
257 ``using`` declarations. For example:
261 using OptionalInt = std::optional<int>;
263 void f(OptionalInt opt) {
264 use(opt.value()); // unsafe: it is unclear whether `opt` has a value.
270 The check does not currently report unsafe optional accesses in lambdas.
271 A future version will expand the scope to lambdas, following the rules
272 outlined above. It is best to follow the same principles when using
273 optionals in lambdas.
275 Access with ``operator*()`` vs. ``value()``
276 -------------------------------------------
278 Given that ``value()`` has well-defined behavior (either throwing an exception
279 or terminating the program), why treat it the same as ``operator*()`` which
280 causes undefined behavior (UB)? That is, why is it considered unsafe to access
281 an optional with ``value()``, if it's not provably populated with a value? For
282 that matter, why is ``CHECK()`` followed by ``operator*()`` any better than
283 ``value()``, given that they are semantically equivalent (on configurations that
286 The answer is that we assume most users do not realize the difference between
287 ``value()`` and ``operator*()``. Shifting to ``operator*()`` and some form of
288 explicit value-presence check or explicit program termination has two
291 * Readability. The check, and any potential side effects like program
292 shutdown, are very clear in the code. Separating access from checks can
293 actually make the checks more obvious.
295 * Performance. A single check can cover many or even all accesses within
296 scope. This gives the user the best of both worlds -- the safety of a
297 dynamic check, but without incurring redundant costs.