CppCoreGuidelines C.147 用 dynamic_cast 转换引用的时候,如果无法转换,就会认为出错了,抛出异常
04 January 2023
C.147: Use dynamic_cast
to a reference type when failure to find the
required class is considered an error
理由
把一个对象转换成引用,表明你希望最终得到一个有效的对象,所以类型转换必须成功。如果失败,dynamic_cast
就应该抛出一个异常。
例子
class Base { public: virtual string to_string() { return "Derived"; } }; class Derived : public Base { public: string to_string() { return "Derived"; } }; std::string f(Base& b) { return dynamic_cast<Derived&>(b).to_string(); }
以下代码,在 f
函数中, d
被成功转换成了 Derived
本身,所以正确执行。
$$classes$$ int main() { Derived d; cout << f(d); }
Derived
以下代码,因为无法将 Base
转换成 Derived
,所以抛出异常 std::bad_cast
$$classes$$ int main() { Base b; cout << f(b); }
terminate called after throwing an instance of 'std::bad_cast'