C ++ dynamic_cast错误处理 [英] c++ dynamic_cast error handling

查看:81
本文介绍了C ++ dynamic_cast错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何与dynamic_cast错误处理相关的良好做法(除非不需要时不使用它)?我想知道我应该如何处理NULL并可能抛出bad_cast.我应该同时检查两者吗?如果我发现bad_cast或检测到NULL,我可能还是无法恢复...现在,我正在使用assert来检查dynamic_cast是否返回了非NULL值.您会在代码审查中接受此解决方案吗?

Is there any good practice related to dynamic_cast error handling (except not using it when you don't have to)? I'm wondering how should I go about NULL and bad_cast it can throw. Should I check for both? And if I catch bad_cast or detect NULL I probably can't recover anyway... For now, I'm using assert to check if dynamic_cast returned not NULL value. Would you accept this solution on a code review?

推荐答案

如果 dynamic_cast 应该成功,则最好使用 boost ::改为polymorphic_downcast ,它有点像这样:

If the dynamic_cast should succeed, it would be good practice to use boost::polymorphic_downcast instead, which goes a little something like this:

assert(dynamic_cast<T*>(o) == static_cast<T*>(o));
return static_cast<T*>(o);

这样,您将在调试版本中检测到错误,同时避免了发行版本中的运行时开销.

This way, you will detect errors in the debug build while at the same time avoiding the runtime overhead in a release build.

如果怀疑强制转换可能失败并且想要检测到它,请使用 dynamic_cast 并将其强制转换为引用类型.如果发生错误,此强制转换将抛出 bad_cast ,并会关闭您的程序.(如果您说过,无论如何都不会恢复,那就很好了)

If you suspect the cast might fail and you want to detect it, use dynamic_cast and cast to a reference type. This cast will throw bad_cast in case of error, and will take down your program. (This is good if, as you say, you are not going to recover anyway)

T& t = dynamic_cast<T&>(o);
t.func(); //< Use t here, no extra check required

仅在上下文中使用0指针时,才将 dynamic_cast 用作指针类型.您可能希望在 if 中使用它,如下所示:

Use dynamic_cast to a pointer type only if the 0-pointer makes sense in the context. You might want to use it in an if like this:

if (T* t = dynamic_cast<T*>(o)) {
    t->func(); //< Use t here, it is valid
}
// consider having an else-clause

使用最后一个选项,如果 dynamic_cast 返回0,则需要确保执行路径有意义.

With this last option you need to make sure that the execution path makes sense if the dynamic_cast returns 0.

直接回答您的问题:我希望我提供的两个第一种选择之一是在代码中具有显式的 assert :)

To answer your question directly: I would prefer one of the two first alternatives I have given to having an explicit assert in the code :)

这篇关于C ++ dynamic_cast错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆