Namespaces
Variants

std::bad_typeid

来自 zh.cppreference.net
 
 
 
 
定义于头文件 <typeinfo>
class bad_typeid : public std::exception;

当对多态类型的空指针解引用值应用 typeid 运算符时,会抛出此类型的异常。

cpp/error/exception

继承关系图

成员函数

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

std::bad_typeid:: bad_typeid

(1)
bad_typeid ( ) throw ( ) ;
(C++11 前)
bad_typeid ( ) noexcept ;
(C++11 起)
(C++26 起为 constexpr)
(2)
bad_typeid ( const bad_typeid & other ) throw ( ) ;
(C++11 前)
bad_typeid ( const bad_typeid & other ) noexcept ;
(C++11 起)
(C++26 起为 constexpr)

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

1) 默认构造函数。
2) 复制构造函数。 若 * this 与 other 均拥有动态类型 std::bad_typeid ,则 std:: strcmp ( what ( ) , other. what ( ) ) == 0 。 (C++11 起)

参数

other - 要复制的另一异常对象

std::bad_typeid::operator=

bad_typeid& operator=( const bad_typeid& other ) throw();
(C++11 前)
bad_typeid& operator=( const bad_typeid& other ) noexcept;
(C++11 起)

以 other 的内容赋值给当前对象。 如果 *this 和 other 的动态类型均为 std::bad_typeid,则赋值后结果为 std::strcmp(what(), other.what()) == 0。(C++11 起)

参数

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

返回值

* this

std::bad_typeid::what

virtual const char* what() const throw();
(C++11 前)
virtual const char* what() const noexcept;
(C++11 起)
(自 C++26 起为 constexpr)

返回解释性字符串。

返回值

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

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

(C++26 起)

注解

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

继承自 std:: exception

成员函数

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

注释

功能测试 宏 值 标准 功能
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr 用于异常类型

示例

#include <iostream>
#include <typeinfo>

struct S // The type has to be polymorphic
{
    virtual void f();
};

int main()
{
    S* p = nullptr;
    try
    {
        std::cout << typeid(*p).name() << '\n';
    }
    catch (const std::bad_typeid& e)
    {
        std::cout << e.what() << '\n';
    }
}

可能的输出:

Attempted a typeid of NULL pointer!