ポインタ型へのdynamic_castが失敗したときはNULLが返る
Javaからの類推で、キャストの失敗は例外が飛ぶのかなーと思っていたんですが、ポインタのdynamic_cast失敗はNULLが返ってくるだけでした。
MSDNリファレンス
The value of a failed cast to pointer type is the null pointer. A failed cast to reference type throws a bad_cast Exception.
http://msdn.microsoft.com/ja-jp/library/cby9kycs(VS.80).aspx#ctl00_contentContainer_ctl13other
訳
ポインタ型へのキャストが失敗した場合はnullポインタが値となる。参照型へのキャストが失敗した場合はstd::bad_cast例外が投げられる。
検証コード
#include <iostream> class A {virtual void f(){};}; class B : public A {}; class C : public A {}; int main(){ A* pa = &C(); B* pb = dynamic_cast<B*>(pa); if(pb){ std::cout << pb << std::endl; }else{ std::cout << "failed dynamic_cast to pointer returns NULL" << std::endl; } try{ B& rb = dynamic_cast<B&>(*pa); }catch(std::bad_cast){ std::cout << "failed dynamic_cast to reference throws bad_cast" << std::endl; } }
結果
failed dynamic_cast to pointer returns NULL
failed dynamic_cast to reference throws bad_cast