如何在引用中正确使用 dynamic_cast 中的 return 值?
How to use the return value from a dynamic_cast on references properly?
我们使用 dynamic_cast
运算符将指针或对基类型的引用安全地转换为指针或对派生类型的引用。
struct Foo{
void f() const{
std::cout << "Foo::f()\n";
}
virtual ~Foo() = default;
};
struct Bar : Foo{
void f() const {
std::cout << "Bar::f()\n";
}
};
int main(){
Foo* pf = new Foo{};
Bar* pb = dynamic_cast<Bar*>(pf);
if(pb)
pb->f();
delete pf;
pf = new Bar{};
pb = dynamic_cast<Bar*>(pf);
if(pb)
pb->f();
delete pf;
Bar b{};
Foo& rf = b;
Bar& rb = dynamic_cast<Bar&>(rf);
// if(rb) // ?
rb.f();
}
- 那么如何检查
dynamic_cast
returns 是有效还是无效的引用呢? - 对于指针,只要我们将指针与 nullptr
值进行比较就可以了,但是对于参考如何?
用作@1201ProgramAlarm 评论的占位符。
简单地说,
A failed dynamic cast for a reference throws an exception. – 1201ProgramAlarm
来自IBM docs:
You cannot verify the success of a dynamic cast using reference types by comparing the result (the reference that results from the dynamic cast) with zero because there is no such thing as a zero reference. A failing dynamic cast to a reference type throws a bad_cast exception.
因此,要验证转换是否成功,只需确保它没有抛出异常即可。
我们使用 dynamic_cast
运算符将指针或对基类型的引用安全地转换为指针或对派生类型的引用。
struct Foo{
void f() const{
std::cout << "Foo::f()\n";
}
virtual ~Foo() = default;
};
struct Bar : Foo{
void f() const {
std::cout << "Bar::f()\n";
}
};
int main(){
Foo* pf = new Foo{};
Bar* pb = dynamic_cast<Bar*>(pf);
if(pb)
pb->f();
delete pf;
pf = new Bar{};
pb = dynamic_cast<Bar*>(pf);
if(pb)
pb->f();
delete pf;
Bar b{};
Foo& rf = b;
Bar& rb = dynamic_cast<Bar&>(rf);
// if(rb) // ?
rb.f();
}
- 那么如何检查
dynamic_cast
returns 是有效还是无效的引用呢? - 对于指针,只要我们将指针与nullptr
值进行比较就可以了,但是对于参考如何?
用作@1201ProgramAlarm 评论的占位符。
简单地说,
A failed dynamic cast for a reference throws an exception. – 1201ProgramAlarm
来自IBM docs:
You cannot verify the success of a dynamic cast using reference types by comparing the result (the reference that results from the dynamic cast) with zero because there is no such thing as a zero reference. A failing dynamic cast to a reference type throws a bad_cast exception.
因此,要验证转换是否成功,只需确保它没有抛出异常即可。