命名空间
变体
操作

std::bad_variant_access

来自 cppreference.cn
< 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 对象,其中包含实现定义的空终止字节字符串,该字符串可通过 what() 访问。

1) 默认构造函数。
2) 复制构造函数。如果 *thisother 都具有动态类型 std::bad_variant_access,则 std::strcmp(what(), other.what()) == 0

参数

other - 另一个要复制的异常对象

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

参数

other - 另一个要赋值的异常对象

返回值

*this

std::bad_variant_access::what

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

返回解释性字符串。

返回值

指向实现定义的空终止字符串的指针,其中包含解释性信息。该字符串适合转换为 std::wstring 并显示。指针保证有效,至少在从中获取它的异常对象被销毁之前,或者直到调用异常对象上的非 const 成员函数(例如,复制赋值运算符)为止。

返回的字符串在常量求值期间使用普通文字编码进行编码。

(自 C++26 起)

注释

允许但不是必须实现 what() 的重写。

继承自 std::exception

成员函数

销毁异常对象
(std::exception 的虚公共成员函数) [编辑]
[virtual]
返回解释性字符串
(std::exception 的虚公共成员函数) [编辑]

[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] 参见

读取变体的值,给定索引或类型(如果类型是唯一的),错误时抛出异常
(函数模板) [编辑]
(C++17)
使用一个或多个 variant 保存的参数调用提供的函数对象
(函数模板) [编辑]
(C++26)
使用 variant 保存的参数调用提供的函数对象
(公共成员函数) [编辑]