cast
static_cast
- static_cast<type>(expr)
- static_castはexprの型からtypeへの暗黙の型変換
- typeからexprへの暗黙の型変換が存在する場合
- キャスト不可能でコンパイルエラー
// int から long へ
int ival;
long lval = static_cast<long>(ival);
reinterpret_cast
- reinterpret_cast<type>(expr)
- reinterpret_castはtype(expr)が許されるなら、exprをtypeに単にキャスト
- reinterpret_castは単なる型変更
- たとえ派生関係があってもポインタのアドレス自体はキャスト前と変わらん
- reinterpret_castは非常に危険なキャスト
// long から int* へ
long lval;
int* iptr = reinterpret_cast<int*>(lval);
const_cast
-
const_cast<type>(expr)
- const_castはconstおよびvolatile修飾子を無効にするだけのキャスト
- そのほかのときはコンパイルエラー
// const int* から int* へ
const int* ciptr;
int* iptr = const_cast<int*>(ciptr);
dynamic_cast
-
dynamic_cast<type>(expr)
-
dynamic_castは基底クラスへのポインタ(or 参照)から派生クラスへのポインタ(or 参照)への型保証キャスト
- dynamic_castは実行時に型の検査、変換不可能で0を返す
class Base { ... };
class Derived : public Base { ... };
Base base;
Derived derived;
Derived* pd1 = dynamic_cast<Derived*>(&base); // 失敗 pd1 == 0
Derived* pd2 = dynamic_cast<Derived*>(&derived);
参照のキャストに失敗すると、std::bad_cast例外がthrowされます。
try {
Derived& rd1 = dynamic_cast<Derived&>(base);
} catch ( const std::bad_cast& e ) {
std::cout << e.what() << std::endl;
};