04 January 2023

C++ 核心指南目录

“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 本身,所以正确执行。

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();
}
int main()
{
    Derived d;
    cout << f(d);
}
Derived

以下代码,因为无法将 Base 转换成 Derived,所以抛出异常 std::bad_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();
}
int main()
{
    Base b;
    cout << f(b);
}
terminate called after throwing an instance of 'std::bad_cast'