Abseil C++

An open-source collection of C++ library code designed to augment the C++ standard library

  • Tip of the Week #181: Accessing the value of a StatusOr
    https://abseil.io/tips/181

    Originally posted as TotW #181 on July 9, 2020

    By Michael Sheely

    Updated 2020-09-02

    Quicklink: abseil.io/tips/181

    StatusOr: you don’t have to choose!

    When the time comes to access the value inside an absl::StatusOr object, we should strive to make that access safe, clear, and efficient.

    Recommendation

    Accessing the value held by a StatusOr should be performed via operator* or operator->, after a call to ok() has verified that the value is present.

    // The same pattern used when handling a unique_ptr... std::unique_ptr foo = TryAllocateFoo(); if (foo != nullptr) foo->DoBar(); // use the value object

    // ...or an optional value... absl::optional foo = MaybeFindFoo(); if (foo.has_value()) foo->DoBar();

    // ...is also ideal for handling a StatusOr. absl::StatusOr foo = (...)