C++ Optional Value Extraction Guide

In C++, to retrieve the value stored in an optional object, you can use the value() method. This method will return a reference and throw a std::bad_optional_access exception if the optional object is empty. Alternatively, you can use operator* and operator-> to retrieve the value, but be cautious as these methods may lead to undefined behavior when the object is empty. An example is shown below:

std::optional<int> opt = 42;

// 使用value()方法获取值
int value = opt.value();
std::cout << "Value: " << value << std::endl;

// 使用operator*获取值
int value2 = *opt;
std::cout << "Value: " << value2 << std::endl;

// 使用operator->获取值
int value3 = opt->value();
std::cout << "Value: " << value3 << std::endl;
bannerAds