Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::optional

      From cppreference.com
      <cpp‎ |utility
       
       
      Utilities library
       
       
      Defined in header<optional>
      template<class T>
      class optional;
      (since C++17)

      The class templatestd::optional manages an optional contained value, i.e. a value that may or may not be present.

      A common use case foroptional is the return value of a function that may fail. As opposed to other approaches, such asstd::pair<T,bool>,optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.

      Any instance ofoptional at any given point in time eithercontains a value ordoes not contain a value.

      If anoptional contains a value, the value is guaranteed to benested within theoptional object. Thus, anoptional object models an object, not a pointer, even thoughoperator*() andoperator->() are defined.

      When an object of typeoptional<T> iscontextually converted tobool, the conversion returnstrue if the object contains a value andfalse if it does not contain a value.

      Theoptional object contains a value in the following conditions:

      • The object is initialized with/assigned from a value of typeT or anotheroptional that contains a value.

      The object does not contain a value in the following conditions:

      • The object is default-initialized.
      • The object is initialized with/assigned from a value of typestd::nullopt_t or anoptional object that does not contain a value.
      • The member functionreset() is called.

      Theoptional object is aview that contains either one element if itcontains a value, or otherwise zero elements if it does not contain a value. The lifetime of the contained element is bound to the object.

      (since C++26)

      There are no optional references, functions, arrays, or (possibly cv-qualified)void; a program is ill-formed if it instantiates anoptional with such a type. In addition, a program is ill-formed if it instantiates anoptional with the (possibly cv-qualified) tag typesstd::nullopt_t orstd::in_place_t.

      Contents

      [edit]Template parameters

      T - the type of the value to manage initialization state for. The type must meet the requirements ofDestructible (in particular, array and reference types are not allowed).

      [edit]Nested types

      Type Definition
      value_typeT
      iterator(since C++26) implementation-definedLegacyRandomAccessIterator,ConstexprIterator, andcontiguous_iterator whosevalue_type andreference arestd::remove_cv_t<T> andT&, respectively.
      const_iterator(since C++26) implementation-definedLegacyRandomAccessIterator,ConstexprIterator, andcontiguous_iterator whosevalue_type andreference arestd::remove_cv_t<T> andconst T&, respectively.

      All requirements on the iterator types of aContainer apply to theiterator type ofoptional as well.

      [edit]Data members

      T*val a pointer to the contained object (if exists)
      (exposition-only member object*)

      [edit]Member functions

      constructs theoptional object
      (public member function)[edit]
      destroys the contained value, if there is one
      (public member function)[edit]
      assigns contents
      (public member function)[edit]
      Iterators
      (C++26)
      returns an iterator to the beginning
      (public member function)[edit]
      (C++26)
      returns an iterator to the end
      (public member function)[edit]
      Observers
      accesses the contained value
      (public member function)[edit]
      checks whether the object contains a value
      (public member function)[edit]
      returns the contained value
      (public member function)[edit]
      returns the contained value if available, another value otherwise
      (public member function)[edit]
      Monadic operations
      (C++23)
      returns the result of the given function on the contained value if it exists, or an emptyoptional otherwise
      (public member function)[edit]
      (C++23)
      returns anoptional containing the transformed contained value if it exists, or an emptyoptional otherwise
      (public member function)[edit]
      (C++23)
      returns theoptional itself if it contains a value, or the result of the given function otherwise
      (public member function)[edit]
      Modifiers
      exchanges the contents
      (public member function)[edit]
      destroys any contained value
      (public member function)[edit]
      constructs the contained value in-place
      (public member function)[edit]

      [edit]Non-member functions

      (C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20)
      comparesoptional objects
      (function template)[edit]
      creates anoptional object
      (function template)[edit]
      specializes thestd::swap algorithm
      (function template)[edit]

      [edit]Helper classes

      hash support forstd::optional
      (class template specialization)[edit]
      (C++17)
      indicator of anstd::optional that does not contain a value
      (class)[edit]
      exception indicating checked access to an optional that doesn't contain a value
      (class)[edit]

      [edit]Helpers

      (C++17)
      an object of typenullopt_t
      (constant)[edit]
      in-place construction tag
      (tag)[edit]

      [edit]Helper specializations

      template<class T>
      constexprboolranges::enable_view<std::optional<T>>=true;
      (since C++26)

      This specialization ofranges::enable_view makesoptional satisfyview.

      template<class T>
      constexprauto format_kind<std::optional<T>>= range_format::disabled;
      (since C++26)

      This specialization offormat_kind disables therange formatting support ofoptional.

      [edit]Deduction guides

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_optional201606L(C++17)std::optional
      202106L(C++23)
      (DR20)
      Fullyconstexpr
      202110L(C++23)Monadic operations
      __cpp_lib_optional_range_support202406L(C++26)Range support forstd::optional

      [edit]Example

      Run this code
      #include <iostream>#include <optional>#include <string> // optional can be used as the return type of a factory that may failstd::optional<std::string> create(bool b){if(b)return"Godzilla";return{};} // std::nullopt can be used to create any (empty) std::optionalauto create2(bool b){return b? std::optional<std::string>{"Godzilla"}:std::nullopt;} int main(){std::cout<<"create(false) returned "<< create(false).value_or("empty")<<'\n'; // optional-returning factory functions are usable as conditions of while and ifif(auto str= create2(true))std::cout<<"create2(true) returned "<<*str<<'\n';}

      Output:

      create(false) returned emptycreate2(true) returned Godzilla

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 4141C++17the requirement of storage
      allocation was confusing
      the contained object must be
      nested within theoptional object

      [edit]See also

      (C++17)
      a type-safe discriminated union
      (class template)[edit]
      (C++17)
      objects that hold instances of anyCopyConstructible type
      (class)[edit]
      (C++23)
      a wrapper that contains either an expected or error value
      (class template)[edit]
      aview that contains a single element of a specified value
      (class template)(customization point object)[edit]
      an emptyview with no elements
      (class template)(variable template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional&oldid=180937"

      [8]ページ先頭

      ©2009-2025 Movatter.jp