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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章