名稱空間
變體
操作

std::bad_variant_access

來自 cppreference.com
< cpp‎ | utility‎ | variant
 
 
 
 
定義於標頭檔案 <variant>
class bad_variant_access : public std::exception
(C++17 起)

std::bad_variant_access 是在以下情況丟擲的異常型別:

(C++26 起)

目錄

[edit] 成員函式

(建構函式)
構造新的 bad_variant_access 物件
(公開成員函式)
operator=
替換 bad_variant_access 物件
(公開成員函式)
what
返回解釋字串
(公開成員函式)

std::bad_variant_access::bad_variant_access

bad_variant_access() noexcept;
(1) (C++17 起)
bad_variant_access( const bad_variant_access& other ) noexcept;
(2) (C++17 起)

構造一個新的 bad_variant_access 物件,其包含一個實現定義的以 null 結尾的位元組字串,該字串可透過 what() 訪問。

1) 預設建構函式。
2) 複製建構函式。如果 *thisother 都具有動態型別 std::bad_variant_access,則 std::strcmp(what(), other.what()) == 0

引數

其他 - 要複製的另一個異常物件

std::bad_variant_access::operator=

bad_variant_access& operator=( const bad_variant_access& other ) noexcept;
(C++17 起)

將內容賦為 other 的內容。如果 *thisother 都具有動態型別 std::bad_variant_access,則賦值後 std::strcmp(what(), other.what()) == 0

引數

其他 - 用於賦值的另一個異常物件

返回值

*this

std::bad_variant_access::what

virtual const char* what() const noexcept;
(C++17 起)

返回解釋字串。

返回值

指向一個實現定義的以 null 結尾的字串,其中包含解釋性資訊。該字串適合轉換為 std::wstring 並顯示。保證該指標至少在獲取它的異常物件被銷燬之前或在對異常物件呼叫非 const 成員函式(例如複製賦值運算子)之前有效。

在常量求值期間,返回的字串使用普通字面量編碼進行編碼。

(C++26 起)

注意

允許但不要求實現重寫 what()

繼承自 std::exception

成員函式

銷燬異常物件
(std::exception 的虛公共成員函式) [edit]
[virtual]
返回解釋字串
(std::exception 的虛公共成員函式) [edit]

[edit] 示例

#include <iostream>
#include <variant>
 
int main()
{
    std::variant<int, float> v;
    v = 12;
    try
    {
        std::get<float>(v);
    }
    catch (const std::bad_variant_access& e)
    {
        std::cout << e.what() << '\n';
    }
}

可能的輸出

bad_variant_access

[edit] 參閱

根據索引或型別(如果型別唯一)讀取變體的值,出錯時丟擲異常
(函式模板) [edit]
(C++17)
用一個或多個 variant 所持有的引數呼叫所提供的函式物件
(函式模板) [edit]
(C++26)
使用 variant 持有的引數呼叫提供的函式物件
(公共成員函式) [edit]