Namespaces
Variants

std:: bad_cast

From cppreference.net
Utilities library
定义于头文件 <typeinfo>
class bad_cast : public std:: exception

dynamic_cast 对引用类型的运行时检查失败时(例如由于类型间不存在继承关系),会抛出此类型的异常;同时当 std::use_facet 请求的区域设置中不存在所需facet时也会抛出该异常。

cpp/error/exception std-bad cast-inheritance.svg

继承关系图

目录

成员函数

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

std::bad_cast:: bad_cast

(1)
bad_cast ( ) throw ( ) ;
(until C++11)
bad_cast ( ) noexcept ;
(since C++11)
(constexpr since C++26)
(2)
bad_cast ( const bad_cast & other ) throw ( ) ;
(until C++11)
bad_cast ( const bad_cast & other ) noexcept ;
(since C++11)
(constexpr since C++26)

构造一个新的 bad_cast 对象,其中包含一个实现定义的以空字符结尾的字节字符串,可通过 what() 访问。

1) 默认构造函数。
2) 拷贝构造函数。 如果 * this other 都具有动态类型 std::bad_cast ,则 std:: strcmp ( what ( ) , other. what ( ) ) == 0 (since C++11)

参数

other - 要拷贝的另一个异常对象

std::bad_cast:: operator=

bad_cast & operator = ( const bad_cast & other ) throw ( ) ;
(C++11前)
bad_cast & operator = ( const bad_cast & other ) noexcept ;
(C++11起)
(C++26起为constexpr)

将内容赋值为 other 的内容。 如果 * this other 都具有动态类型 std::bad_cast ,则赋值后满足 std:: strcmp ( what ( ) , other. what ( ) ) == 0 (C++11起)

参数

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

返回值

* this

std::bad_cast:: what

virtual const char * what ( ) const throw ( ) ;
(until C++11)
virtual const char * what ( ) const noexcept ;
(since C++11)
(constexpr since C++26)

返回解释性字符串。

返回值

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

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

(since C++26)

注解

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

继承自 std:: exception

成员函数

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

注释

功能测试 标准 功能
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr for exception types

示例

#include <iostream>
#include <typeinfo>
struct Foo { virtual ~Foo() {} };
struct Bar { virtual ~Bar() { std::cout << "~Bar\n"; } };
struct Pub : Bar { ~Pub() override { std::cout << "~Pub\n"; } };
int main()
{
    Pub pub;
    try
    {
        [[maybe_unused]]
        Bar& r1 = dynamic_cast<Bar&>(pub); // 正常,向上转型
        [[maybe_unused]]
        Foo& r2 = dynamic_cast<Foo&>(pub); // 抛出异常
    }
    catch (const std::bad_cast& e)
    {
        std::cout << "e.what(): " << e.what() << '\n';
    }
}

可能的输出:

e.what(): std::bad_cast
~Pub
~Bar