名稱空間
變體
操作

std::bad_typeid

來自 cppreference.com
< 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!