Namespaces
Variants

std::bad_cast

从 zh.cppreference.net
 
 
 
类型支持
基本类型
定宽整数类型 (C++11)
定宽浮点类型 (C++23)
(C++11)    
(C++17)
数值极限
C 数值极限接口
运行时类型信息
 
定义于头文件 <typeinfo>
class bad_cast : public std::exception;

当 dynamic_cast 到引用类型失败于运行时检查时(例如因为类型之间没有继承关系),以及从 std::use_facet 当请求的 facet 在 locale 中不存在时,会抛出此类型的异常。

cpp/error/exception

继承关系图

成员函数

(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 起)

将 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();
(C++11 前)
virtual const char* what() const noexcept;
(C++11 起)
(C++26 起为 constexpr)

返回解释性字符串。

返回值

指向实现定义的以空字符结尾的字符串的指针,该字符串包含解释性信息。该字符串适合转换并显示为 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