utility_optional

utility_optional (std::optional)

이 페이지는 C++17에서 도입된 std::optional 클래스 템플릿에 대해 설명해요. std::optional은 값을 가질 수도 있고 가지지 않을 수도 있는 선택적 contained value를 관리하는 타입이에요. 함수가 실패할 수 있는 경우 반환 타입으로 자주 사용돼요.

출처: cppreference

본문

<optional> 헤더에 정의되어 있어요.

Defined in header
template < class T > class optional ; (since C++17)

std::optional 클래스 템플릿은 선택적 contained value, 즉 존재할 수도 있고 존재하지 않을 수도 있는 값을 관리해요.

optional의 일반적인 사용 사례는 실패할 수 있는 함수의 반환 값이에요. std::pair<T, bool> 같은 다른 접근 방식과 달리 optional은 생성 비용이 큰 객체를 잘 처리하고, 의도가 명시적으로 표현되므로 더 읽기 쉬워요.

어느 시점에서든 optional 인스턴스는 값을 포함하거나 포함하지 않아요.

optional이 값을 포함하면, 그 값은 optional 객체 내부에 중첩되어 보장돼요. 따라서 operator*()operator->()가 정의되어 있음에도 optional 객체는 포인터가 아니라 객체를 모델로 해요.

optional<T> 타입 객체가 문맥적으로 bool로 변환될 때, 객체가 값을 포함하면 true를, 포함하지 않으면 false를 반환해요.

optional 객체는 다음 조건에서 값을 포함해요:

  • 객체가 T 타입의 값이나 값을 포함하는 다른 optional로 초기화되거나 할당된 경우.

optional 객체는 다음 조건에서 값을 포함하지 않아요:

  • 객체가 기본 초기화된 경우.
  • 객체가 std::nullopt_t 타입의 값이나 값을 포함하지 않는 optional 객체로 초기화되거나 할당된 경우.
  • reset() 멤버 함수가 호출된 경우.

optional 객체는 값을 포함하면 요소 하나를, 포함하지 않으면 요소가 없는 뷰로 간주돼요. contained element의 수명은 객체에 묶여 있어요. (since C++26)

optional 참조, 함수, 배열, (cv-qualified 가능한) void는 존재하지 않아요. 이러한 타입으로 optional을 인스턴스화하면 프로그램이 ill-formed예요. 또한 (cv-qualified 가능한) 태그 타입 std::nullopt_tstd::in_place_toptional을 인스턴스화해도 ill-formed예요.

템플릿 매개변수

T - 초기화 상태를 관리할 값의 타입. 이 타입은 Destructible 요구 사항을 충족해야 해요 (특히 배열과 참조 타입은 허용되지 않아요).

중첩 타입

Type Definition
value_type T
iterator (since C++26) 구현 정의된 LegacyRandomAccessIterator, ConstexprIterator, contiguous_iterator로, value_type은 std::remove_cv_t<T>, reference는 T&예요.
const_iterator (since C++26) 구현 정의된 LegacyRandomAccessIterator, ConstexprIterator, contiguous_iterator로, value_type은 std::remove_cv_t<T>, reference는 const T&예요.

Container의 iterator 타입에 대한 모든 요구 사항은 optional의 iterator 타입에도 적용돼요.

데이터 멤버

T* val contained object를 가리키는 포인터 (존재하는 경우) ( exposition-only member object* )

멤버 함수

(constructor) optional 객체를 생성해요 (public member function)
(destructor) 값이 있으면 contained value를 파괴해요 (public member function)
operator= 내용을 할당해요 (public member function)
Iterators
begin (C++26) 시작을 가리키는 iterator를 반환해요 (public member function)
end (C++26) 끝을 가리키는 iterator를 반환해요 (public member function)
Observers
operator-> operator* contained value에 접근해요 (public member function)
operator bool has_value 객체가 값을 포함하는지 확인해요 (public member function)
value contained value를 반환해요 (public member function)
value_or 값이 있으면 contained value를, 없으면 다른 값을 반환해요 (public member function)
Monadic operations
and_then (C++23) 값이 있으면 주어진 함수를 contained value에 적용한 결과를, 없으면 빈 optional을 반환해요 (public member function)
transform (C++23) 값이 있으면 변환된 contained value를 담은 optional을, 없으면 빈 optional을 반환해요 (public member function)
or_else (C++23) 값이 있으면 optional 자신을, 없으면 주어진 함수의 결과를 반환해요 (public member function)
Modifiers
swap 내용을 교환해요 (public member function)
reset contained value를 파괴해요 (public member function)
emplace contained value를 제자리에서 생성해요 (public member function)

비멤버 함수

operator== operator!= operator< operator<= operator> operator>= operator<=> (C++17) (C++17) (C++17) (C++17) (C++17) (C++17) (C++20) optional 객체를 비교해요 (function template)
make_optional (C++17) optional 객체를 생성해요 (function template)
std::swap (std::optional) (C++17) std::swap 알고리즘을 특수화해요 (function template)

헬퍼 클래스

std::hash std::optional (C++17) std::optional에 대한 hash 지원 (class template specialization)
nullopt_t (C++17) 값을 포함하지 않는 std::optional을 나타내는 표시 (class)
bad_optional_access (C++17) 값을 포함하지 않는 optional에 대한 checked access를 나타내는 예외 (class)

헬퍼

nullopt (C++17) nullopt_t 타입의 객체 (constant)
in_place in_place_type in_place_index in_place_t in_place_type_t in_place_index_t (C++17) in-place 생성 태그 (tag)

헬퍼 특수화

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

ranges::enable_view 특수화는 optionalview를 만족하도록 만들어요.

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

format_kind 특수화는 optional의 range formatting 지원을 비활성화해요.

추론 가이드

Notes

Feature-test macro Value Std Feature
__cpp_lib_optional 201606L (C++17) std::optional
202106L (C++23) (DR20) Fully constexpr
202110L (C++23) Monadic operations
__cpp_lib_optional_range_support 202406L (C++26) Range support for std::optional

Example

#include <iostream>
#include <optional>
#include <string>
 
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
    if (b)
        return "Godzilla";
    return {};
}

// std::nullopt can be used to create any (empty) std::optional
auto 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 if
    if (auto str = create2(true))
        std::cout << "create2(true) returned " << *str << '\n';
}

Output:

create(false) returned empty
create2(true) returned Godzilla

결함 보고서

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.

DR Applied to Behavior as published Correct behavior
LWG 4141 C++17 저장소 할당 요구 사항이 혼란스러웠음 contained object는 optional 객체 내부에 중첩되어야 함

같이 보기

variant (C++17) 타입 안전한 구분 합집합 (class template)
any (C++17) 임의의 CopyConstructible 타입 인스턴스를 보관하는 객체 (class)
expected (C++23) 기대값 또는 오류값 중 하나를 포함하는 래퍼 (class template)
ranges::single_view views::single (C++20) 지정된 값의 단일 요소를 포함하는 뷰 (class template) (customization point object)
ranges::empty_view views::empty (C++20) 요소가 없는 빈 뷰 (class template) (variable template)

더 알아보기 (Learn more)

cppreference