std::optional<T>::operator->, std::optional<T>::operator*
來自 cppreference.com
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) |