std::bad_cast
From cppreference.com
| ヘッダ <typeinfo> で定義 |
||
| class bad_cast : public std::exception; |
||
この型の例外は、参照型へのdynamic_castが実行時チェックに失敗した場合(例えば、型が継承によって関連していない場合)、および要求されたファセットがロケールに存在しない場合にstd::use_facetからスローされます。
継承図
目次 |
[編集] メンバ関数
| (コンストラクタ) |
新しいbad_castオブジェクトを構築する(public member function) |
| operator= |
bad_castオブジェクトを置き換える(public member function) |
| what |
説明文字列を返す (public member function) |
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以降) | |
what()を通じてアクセス可能な、実装定義のヌル終端バイト文字列を持つ新しいbad_castオブジェクトを構築する。
1) デフォルトコンストラクタ。
2) コピーコンストラクタ。*thisとotherの両方が動的型
std::bad_castを持つ場合、std::strcmp(what(), other.what()) == 0。(C++11以降)パラメータ
| その他 | - | コピーする別の例外オブジェクト |
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の内容を代入する。代入後、*thisとotherの両方が動的型std::bad_castを持つ場合、std::strcmp(what(), other.what()) == 0。(C++11以降)
パラメータ
| その他 | - | 割り当てる別の例外オブジェクト |
戻り値
*this
std::bad_cast::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 の仮想 public メンバー関数) |
| [virtual] |
説明文字列を返す ( std::exception の仮想 public メンバー関数) |
[編集] 備考
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_constexpr_exceptions |
202411L |
(C++26) | constexpr for exception types |
[編集] 例
このコードを実行
#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