C++核心準(zhǔn)則C.148:使用dynamic_cast進行指針類型轉(zhuǎn)換時,將不能...

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進行指針類型轉(zhuǎn)換時,將不能發(fā)現(xiàn)目標(biāo)類看作是有效的選項
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轉(zhuǎn)換允許檢查是否指針指向一個在其繼承結(jié)構(gòu)中包含給定類的多態(tài)對象。由于轉(zhuǎn)換失敗的結(jié)果僅僅是返回一個空值,這個結(jié)果可以在執(zhí)行時檢查。這個特性允許根據(jù)結(jié)果選擇不同的路徑。
Contrast with?C.147, where failure is an error, and should not be used for conditional execution.
和C.147不同,那里的失敗是錯誤,而且不應(yīng)該被用于條件執(zhí)行。
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的增加函數(shù),它接受構(gòu)造出來的Shape對象的所有權(quán)。對象也會在根據(jù)它們的幾何屬性有序加入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(item))
{
view_of_evens.emplace_back(even);
}
if (auto trisym = dynamic_cast(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.
尋找所需類的失敗會導(dǎo)致dynamic_cast返回一個空值,而解引用一個空指針會引起無定義的行為。因此應(yīng)該總是認(rèn)為dynamic_cast的結(jié)果可能為空并進行檢查。
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.
(復(fù)雜)?如果在dynamic_cast執(zhí)行之后,沒有對結(jié)果指針進行空判斷,那么對使用這個指針的代碼報警。
原文鏈接:
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
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
