C++ Optional: Complete Usage Guide

The std::optional class template was introduced in the C++17 standard, it is a generic class template that can be used to wrap a value, indicating that the value may or may not exist.

Here is how to use std::optional:

  1. Create an std::optional object and initialize it:
std::optional<int> opt1; // 未初始化,值不存在
std::optional<int> opt2 = 42; // 初始化为42
  1. Check if the value exists:
if (opt1.has_value()) {
    // 值存在
} else {
    // 值不存在
}
  1. Access value:
if (opt2.has_value()) {
    int value = opt2.value(); // 获取值
    // 或者
    int value = *opt2; // 通过解引用获取值
}
  1. Retrieve value or default value:
int value = opt1.value_or(0); // 如果值存在,获取值;否则返回默认值0
  1. Reset the value of the optional object:
opt1.reset(); // 重置值,使其不存在

The use of std::optional can help avoid the possibility of null pointer exceptions when using pointers or references, increasing the safety and readability of the code.

bannerAds