有没有 C++检测 static_cast、dynamic_cast 和 reinterpret_cast 滥用的工具?
以下问题的答案描述了 C++ 中 static_cast
、dynamic_cast
和 reinterpret_cast
的推荐用法:
什么时候应该使用static_cast、dynamic_cast、const_cast和reinterpret_cast?
你知道吗有什么工具可以用来检测此类强制转换的滥用吗?像 PC-Lint 或 Coverity Static Analysis 这样的静态分析工具可以做到这一点吗?
引发此问题的特殊情况是不恰当地使用static_cast
来向下转换指针,而编译器不会对此发出警告。我想使用工具来检测这种情况,而不是假设开发人员永远不会犯这种错误。
The answers to the following question describe the recommended usage of static_cast
, dynamic_cast
, and reinterpret_cast
in C++:
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Do you know of any tools that can be used to detect misuse of these kinds of cast? Would a static analysis tool like PC-Lint or Coverity Static Analysis do this?
The particular case that prompted this question was the inappropriate use of static_cast
to downcast a pointer, which the compiler does not warn about. I'd like to detect this case using a tool, and not assume that developers will never make this mistake.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Boost 提供了polymorphic_pointer_downcast() 和polymorphic_downcast() 函数,其作用类似于static_cast,但如果等效的dynamic_cast 失败,则会断言(通常仅在调试版本中)。
请参阅http://www.boost.org/doc/libs/ 1_61_0/libs/conversion/cast.htm 了解详细信息。
Boost offers polymorphic_pointer_downcast() and polymorphic_downcast() functions, which act like static_cast but will assert (typically only in debug builds) if the equivalent dynamic_cast fails.
See http://www.boost.org/doc/libs/1_61_0/libs/conversion/cast.htm for details.
Visual Studio 对其中一些有警告。例如,C4946。不过,它们大多默认关闭。
http://msdn.microsoft.com/en-us/library/23k5d385。 ASPX
Visual studio has warnings for some of these. C4946, for example. They're mostly turned off by default though.
http://msdn.microsoft.com/en-us/library/23k5d385.aspx
鉴于没有可靠的方法来告诉编译时指针指向什么类型,这是一个在编译时很难捕获的问题。
最简单的方法是在运行时进行捕获,使用宏“safe_cast”,该宏编译为在调试时带有断言的dynamic_cast,在发布时编译为static_cast。
现在,在调试过程中,如果转换不合适,动态转换将返回 NULL,并断言。发布期间也没有任何开销。
Given that there is no reliable way of telling what type the pointer points to at compile time, this is a pretty hard problem to catch at compile time.
The simplest method is to do the catch at run-time, using a macro "safe_cast" which compiles to a dynamic_cast with an assert in debug, and a static_cast in release.
Now, during debugging, if the cast is inappropriate, the dynamic cast will return NULL, and assert. There is also no overhead during release.