可以在生产代码中安全删除dynamic_casts吗? [英] Are dynamic_casts safe to remove in production code?
问题描述
dynamic_cast
s较慢,但比 static_cast
s更安全(当然,与对象层次结构一起使用时) )。我的问题是,在确保我的调试代码中所有(动态)强制转换正确之后,是否有任何理由让我不将其更改为 static_cast
s?
dynamic_cast
s are slower, but they are safer than static_cast
s (when used with object hierarchies, of course). My question is, after I've ensured in my debug code that all (dynamic) casts are correct, is there any reason for me not to change them to static_cast
s?
我计划使用以下结构进行此操作。 (顺便说一句,您能想到比 assert_cast
更好的名字吗?也许是 debug_cast
?)
I plan on doing this with the following construct. (Btw, can you think of a better name than assert_cast
? Maybe debug_cast
?)
#if defined(NDEBUG)
template<typename T, typename U>
T assert_cast(U other) {
return static_cast<T>(other);
}
#else
template<typename T, typename U>
T assert_cast(U other) {
return dynamic_cast<T>(other);
}
#endif
编辑: Boost已经为此提供了一些帮助: polymorphic_downcast
。感谢PlasmaHH指出了这一点。
Boost already has something for this: polymorphic_downcast
. Thanks to PlasmaHH for pointing that out.
推荐答案
在我确保调试代码中所有(动态)强制类型转换都是正确的
,我是否有任何理由不将其更改为
static_casts?
after I've ensured in my debug code that all (dynamic) casts are correct, is there any reason for me not to change them to static_casts?
恕我直言,如果您100%确保所有 dynamic_cast<>
是正确的,则没有任何理由 >,而不将其更改为 static_cast<>
。您可以更改。
IMHO, If you are 100% sure that all dynamic_cast<>
are correct, then there is no reason for not changing them to static_cast<>
. You can change them.
这篇关于可以在生产代码中安全删除dynamic_casts吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!