命名空间
变体
操作

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 不包含值,则行为未定义。

目录

[edit] 参数

(无)

[edit] 返回值

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

[edit] 注解

此运算符不检查 optional 是否包含值! 您可以使用 has_value() 或简单的 operator bool() 手动执行此操作。 或者,如果需要检查访问,可以使用 value()value_or()

[edit] 示例

#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

[edit] 缺陷报告

以下行为变更缺陷报告已追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 2762 C++17 operator->operator* 可能是潜在抛出异常的 改为 noexcept

[edit] 参见

返回包含的值
(公共成员函数) [编辑]
如果可用,则返回包含的值,否则返回另一个值
(公共成员函数) [编辑]