命名空间
变体
操作

std::optional<T>::operator->, std::optional<T>::operator*

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
constexpr const T* operator->() const noexcept;
(1) (C++17 起)
constexpr T* operator->() noexcept;
(1) (C++17 起)
constexpr const T& operator*() const& noexcept;
(2) (C++17 起)
constexpr T& operator*() & noexcept;
(2) (C++17 起)
constexpr const T&& operator*() const&& noexcept;
(2) (C++17 起)
constexpr T&& operator*() && noexcept;
(2) (C++17 起)

访问所包含的值。

1) 返回指向所包含值的指针。
2) 返回对所包含值的引用。

如果 *this 不包含值,则行为未定义。

目录

[编辑] 参数

(无)

[编辑] 返回值

指向所包含值的指针或引用。

[编辑] 注意

此运算符不检查 optional 是否包含值!您可以通过使用 has_value() 或简单地使用 operator bool() 来手动检查。另外,如果需要检查访问,可以使用 value()value_or()

[编辑] 示例

#include <iomanip>
#include <iostream>
#include <optional>
#include <string>
 
int main()
{
    using namespace std::string_literals;
 
    std::optional<int> opt1 = 1;
    std::cout << "opt1: " << *opt1 << '\n';
 
    *opt1 = 2;
    std::cout << "opt1: " << *opt1 << '\n';
 
    std::optional<std::string> opt2 = "abc"s;
    std::cout << "opt2: " << std::quoted(*opt2) << ", size: " << opt2->size() << '\n';
 
    // You can "take" the contained value by calling operator* on an rvalue to optional
 
    auto taken = *std::move(opt2);
    std::cout << "taken: " << std::quoted(taken) << "\n"
                 "opt2: " << std::quoted(*opt2) << ", size: " << opt2->size()  << '\n';
}

输出

opt1: 1
opt1: 2
opt2: "abc", size: 3
taken: "abc"
opt2: "", size: 0

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2762 C++17 operator->operator* 可能抛出异常 已改为 noexcept

[编辑] 参阅

返回所包含的值
(public member function) [编辑]
如果可用,返回包含的值,否则返回另一个值
(public member function) [编辑]