이름공간
변수
행위

std::optional

cppreference.com
< cpp‎ | utility
 
 
 
 
<optional> 에 정의되어 있음.
template<class T >
class optional;
(since C++14)

std::optional 클래스 템플릿은 선택사항이 될 수 있는 값을 관리한다. 글자 그대로 그 값이 선택사항이라 특정 값이 아닐 수 있다.

함수의 실패값을 반환하고자 할 때 {{tt|optional}을 많이 활용한다. std::pair<T,bool> 을 사용하는 등의 다른 접근 방식과 반대로 optional은 명시적으로 의도를 나타내기 위하여 비용이 많이 들더라도 객체를 생성하여 더 높은 가독성을 제공한다.

값은 optional 객체 자체에 할당되기 때문에 동적 메모리 할당은 발생하지 않는다. 즉, optionaloperator*()operator->() 가 정의되어 있더라도 포인터가 아니라 객체를 모델링한다.

optional 객체 내부의 값은 초기화될 수도 있고 안된 상태일 수 있다. 초기화상태에서 optional 객체가 값을 가지체 되면 engaged라 하고, 초기화되지 않은 상태에 있을 때는 disengaged라 부른다.

optional객체는 다음 경우에 engaged상태가 된다.:

  • 객체가 T의 값으로 초기화될 때
  • 객체에 engagedoptional 가 할당될 때


객체는 다음 경우 disengaged상태가 된다.:

  • 기본 초기화된 객체
  • std::nullopt_t 값으로 초기화되거나 disengagedoptional로 초기화될 때
  • 객체에 std::nullopt_t 값이나 disengagedoptional로 할당될 때


목차

[편집]템플릿 인자

T - 초기화 상태를 관리하기 위한 값의 형식. 이 형식은 반드시Destructible의 요구조건을 만족해야 한다.

[편집]멤버 형식

Member type Definition
value_typeT

[편집]멤버함수

constructs the optional object
(public member function)[edit]
if engaged, destroys the contained value
(public member function)[edit]
assigns contents
(public member function)[edit]
Observers
accesses the contained value
(public member function)[edit]
checks whether the object is in engaged state
(public member function)[edit]
returns the contained value
(public member function)[edit]
returns the contained value if engaged, another value otherwise
(public member function)[edit]
Modifiers
exchanges the contents
(public member function)[edit]
constructs the contained value in-place
(public member function)[edit]

[편집]Non-member functions

compares optional objects
(function template)[edit]
creates an optional object
(function template)[edit]
specializes the std::swap algorithm
(function)[edit]

[편집]도움 클래스

specializes the std::hash algorithm
(class template specialization)[edit]
close