命名空间
变体
操作

std::bad_typeid

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

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

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

继承图

目录

[编辑] 成员函数

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

std::bad_typeid::bad_typeid

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

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

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

参数

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

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 的内容。 如果 *thisother 都具有动态类型 std::bad_typeid,则在赋值后 std::strcmp(what(), other.what()) == 0(C++11 起)

参数

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

返回值

*this

std::bad_typeid::what

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

返回解释字符串。

返回值

指向实现定义的以 null 结尾的字符串的指针,其中包含解释信息。该字符串适合转换为 std::wstring 并显示。该指针保证在异常对象被销毁或对异常对象调用非常量成员函数(例如,拷贝赋值运算符)之前一直有效。

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

(C++26 起)

注意

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

继承自 std::exception

成员函数

[虚函数]
销毁异常对象
(std::exception 的虚公共成员函数) [编辑]
[虚函数]
返回解释字符串
(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!