简体   繁体   English

简单检查dynamic_cast c ++

[英]simple check for dynamic_cast c++

I do a dynamic_cast and want to check if the cast succeeds. 我进行了dynamic_cast并想检查投射是否成功。

I am doing a basic null pointer check now. 我正在做一个基本的空指针检查。 It like this: 像这样:

A *temp_ptr = dynamic_cast<A *>(obj_ptr);
if( (temp_ptr) && (temp_ptr->some_function()))
{
      // do something if the function returns true
}
else
{
      // cast failed or function returns false
      // continue with normal execution
}

Is this fine or do I need to use assert ? 这样很好还是我需要使用assert? All I care about is that particular function. 我只关心该特定功能。 Is there any other check that I should use ? 还有其他我应该使用的支票吗?

Would it pass a code review ? 它会通过代码审查吗?

The check of the results of the dynamic_cast protect the code from doing things incorrectly. dynamic_cast结果的检查可防止代码错误地处理。 An assert protects the program from programmers writing things incorrectly. 断言保护程序免受程序员错误编写内容的侵害。

Whether you should assert depends on whether it is a mistake for an object to not be of the target type of your dynamic_cast . 是否应该断言取决于对象是否不是dynamic_cast的目标类型是错误的。 If coming into this code you expect a mix of objects, some of which are and some of which are not of type A , then an assert would fire for legitimate usage. 如果进入此代码,您期望混合使用对象,其中一些是对象,而某些不是A类型A ,则断言将触发合法使用。 If every object at this point is expected to be of type A and an object not of that type indicates a programming error, then an assert makes sense, at least in debug builds. 如果此时的每个对象都应为A类型A而不是该类型的对象表明存在编程错误,则至少在调试版本中,断言才有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM