命名空间
变体
操作

std::bad_cast

来自 cppreference.cn
< cpp‎ | types
 
 
 
类型支持
基本类型
固定宽度整数类型 (C++11)
固定宽度浮点类型 (C++23)
(C++11)    
(C++17)
数值限制
C 数值限制接口
运行时类型信息
bad_cast
 
定义于头文件 <typeinfo>
class bad_cast : public std::exception;

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

cpp/error/exceptionstd-bad cast-inheritance.svg

继承关系图

目录

[编辑] 成员函数

(构造函数)
构造一个新的 bad_cast 对象
(公共成员函数)
operator=
替换 bad_cast 对象
(公共成员函数)
what
返回说明字符串
(公共成员函数)

std::bad_cast::bad_cast

(1)
bad_cast() throw();
(C++11 之前)
bad_cast() noexcept;
(C++11 起)
(2)
bad_cast( const bad_cast& other ) throw();
(C++11 之前)
bad_cast( const bad_cast& other ) noexcept;
(C++11 起)

构造一个新的 bad_cast 对象,该对象带有一个实现定义的空终止字节字符串,可以通过 what() 访问。

1) 默认构造函数。
2) 复制构造函数。 如果 *thisother 都有动态类型 std::bad_cast,则 std::strcmp(what(), other.what()) == 0(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 的内容。 如果 *thisother 都有动态类型 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 起)
(constexpr,C++26 起)

返回说明字符串。

返回值

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

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

(C++26 起)

注意

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

继承自 std::exception

成员函数

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

[编辑] 注意

特性测试 Std 特性
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr 用于异常类型

[编辑] 示例

#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); // OK, upcast
 
        [[maybe_unused]]
        Foo& r2 = dynamic_cast<Foo&>(pub); // throws
    }
    catch (const std::bad_cast& e)
    {
        std::cout << "e.what(): " << e.what() << '\n';
    }
}

可能的输出

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