std::bad_variant_access
来自 cppreference.cn
定义于头文件 <variant> |
||
class bad_variant_access : public std::exception |
(自 C++17 起) | |
std::bad_variant_access
是在以下情况中抛出的异常类型
- std::get(std::variant) 当使用索引或类型与当前活动候选项不匹配时调用。
-
std::visit
被调用以访问一个valueless_by_exception
的变体。
|
(自 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) 复制构造函数。如果 *this 和 other 都具有动态类型
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 的内容。如果 *this 和 other 都具有动态类型 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
成员函数
[virtual] |
销毁异常对象 ( 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) |
读取变体的值,给定索引或类型(如果类型是唯一的),错误时抛出异常 (函数模板) |
(C++17) |
使用一个或多个 variant 保存的参数调用提供的函数对象(函数模板) |
(C++26) |
使用 variant 保存的参数调用提供的函数对象(公共成员函数) |