C++核心准则C.148:使用dynamic_cast进行指针类型转换时,将不能发现目标类看作是有效的选项

C.148: Use dynamic_cast to a pointer type when failure to find the required class is considered a valid alternative

C.148:使用dynamic_cast进行指针类型转换时,将不能发现目标类看作是有效的选项

Reason(原因)

The dynamic_cast conversion allows to test whether a pointer is pointing at a polymorphic object that has a given class in its hierarchy. Since failure to find the class merely returns a null value, it can be tested during run time. This allows writing code that can choose alternative paths depending on the results.

dynamic_cast转换允许检查是否指针指向一个在其继承结构中包含给定类的多态对象。由于转换失败的结果仅仅是返回一个空值,这个结果可以在执行时检查。这个特性允许根据结果选择不同的路径。

Contrast with C.147, where failure is an error, and should not be used for conditional execution.

和C.147不同,那里的失败是错误,而且不应该被用于条件执行。

Example(示例)

The example below describes the add function of a Shape_owner that takes ownership of constructed Shape objects. The objects are also sorted into views, according to their geometric attributes. In this example, Shape does not inherit from Geometric_attributes. Only its subclasses do.

下面的例子描述的是Shape_owner的增加函数,它接受构造出来的Shape对象的所有权。对象也会在根据它们的几何属性有序加入views容器。在这个例子中,图形没有从几何属性继承。只有它的子类这么做了。

void add(Shape* const item)
{
  // Ownership is always taken
  owned_shapes.emplace_back(item);

  // Check the Geometric_attributes and add the shape to none/one/some/all of the views

  if (auto even = dynamic_cast<Even_sided*>(item))
  {
    view_of_evens.emplace_back(even);
  }

  if (auto trisym = dynamic_cast<Trilaterally_symmetrical*>(item))
  {
    view_of_trisyms.emplace_back(trisym);
  }
}

Notes(注意)

A failure to find the required class will cause dynamic_cast to return a null value, and de-referencing a null-valued pointer will lead to undefined behavior. Therefore the result of the dynamic_cast should always be treated as if it may contain a null value, and tested.

寻找所需类的失败会导致dynamic_cast返回一个空值,而解引用一个空指针会引起无定义的行为。因此应该总是认为dynamic_cast的结果可能为空并进行检查。

Enforcement(实施建议)

  • (Complex) Unless there is a null test on the result of a dynamic_cast of a pointer type, warn upon dereference of the pointer.

  • (复杂) 如果在dynamic_cast执行之后,没有对结果指针进行空判断,那么对使用这个指针的代码报警。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c148-use-dynamic_cast-to-a-pointer-type-when-failure-to-find-the-required-class-is-considered-a-valid-alternative


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

原创文章 414 获赞 724 访问量 35万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/105541516