Namespaces
Variants

std:: bad_variant_access

From cppreference.net
Utilities library
定义于头文件 <variant>
class bad_variant_access : public std:: exception
(C++17 起)

std::bad_variant_access 是在以下情形中抛出的异常类型:

(since C++26)

std::bad_variant_access 的所有成员函数均为 constexpr :可以在常量表达式求值过程中创建和使用 std::bad_variant_access 对象。

std::bad_variant_access 对象通常不能是 constexpr 的,因为任何动态分配的存储必须在同一常量表达式求值期间释放。

(since C++26)

目录

成员函数

(constructor)
构造新的 bad_variant_access 对象
(公开成员函数)
operator=
替换 bad_variant_access 对象
(公开成员函数)
what
返回说明性字符串
(公开成员函数)

std::bad_variant_access:: bad_variant_access

bad_variant_access ( ) noexcept ;
(1) (since C++17)
(constexpr since C++26)
bad_variant_access ( const bad_variant_access & other ) noexcept ;
(2) (since C++17)
(constexpr since C++26)

构造一个新的 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 ;
(since C++17)
(constexpr since C++26)

使用 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 ;
(since C++17)
(constexpr since C++26)

返回解释性字符串。

返回值

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

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

(since C++26)

注解

实现允许但不要求重写 what()

继承自 std:: exception

成员函数

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

注释

功能测试 标准 功能特性
__cpp_lib_constexpr_exceptions 202502L (C++26) constexpr std::bad_variant_access

示例

#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

参见

通过索引或类型(若类型唯一)读取 variant 的值,错误时抛出异常
(函数模板)
(C++17)
以一个或多个 variant 持有的参数调用提供的函数对象
(函数模板)
(C++26)
variant 持有的参数调用提供的函数对象
(公开成员函数)
指示对不包含值的 optional 进行受检访问的异常
(类)
指示对包含非预期值的 expected 进行受检访问的异常
(类模板)