optional 클래스는 명시적으로(즉, 주석 없이) NULL이 있을 가능성을 전달할 수 있다. 이는 오류 발생을 줄일 수 있다.
포인터보다 더 강하게 NULL에 대한 가능성을 시사한다는 것이 이 클래스의 의의라고 생각한다.
c++17부터 지원된다.
using namespace std;
optional<string> do_something()
{
string s;
// do something...
if(no_problem)
return s;
return {}; // empty optional
}
...
if(optional<string> s = do_something())
cout << *s;
else {...}
int sum(optional<int> a, optional<int> b)
{
int res = 0;
if(a) res += *a;
if(b) res += *b;
return res;
}
int sum2(optional<int> a, optional<int> b)
{
return *a + *b;
}
optional 객체가 값을 갖고 있지 않을 때, 위와 같은 연산은 정의되어 있지 않다. 따라서 항상 객체에 값이 있는지 확인해야 한다.
A Tour of C++ 3rd, p. 210