<typeinfo>

std::bad_cast

class bad_cast;
在動態轉換失敗時丟擲異常

當對多型類型別的引用執行執行時檢查失敗時,由 dynamic_cast 丟擲的異常的型別。

如果物件將成為目標型別的某個不完整物件,則執行時檢查會失敗。

其成員 what 返回一個標識異常的以 null 結尾的字元序列

標準庫中的某些函式也可能丟擲此異常以指示型別轉換錯誤。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// bad_cast example
#include <iostream>       // std::cout
#include <typeinfo>       // std::bad_cast

class Base {virtual void member(){}};
class Derived : Base {};

int main () {
  try
  {
    Base b;
    Derived& rd = dynamic_cast<Derived&>(b);
  }
  catch (std::bad_cast& bc)
  {
     std::cerr << "bad_cast caught: " << bc.what() << '\n';
  }
  return 0;
}

可能的輸出

bad_cast caught: St8bad_cast


異常安全

無異常保證:成員不丟擲異常。

另見