C++核心準則C.130:多態類深拷貝因該使用clone

C++核心準則C.130:多態類深拷貝因該使用clone

C.130: For making deep copies of polymorphic classes prefer a virtual clone function instead of copy construction/assignment

C.130:實現多態類的深拷貝時,虛clone函數要比拷貝構造函數/賦值運算符好。

Reason(原因)

Copying a polymorphic class is discouraged due to the slicing problem, see C.67. If you really need copy semantics, copy deeply: Provide a virtual clone function that will copy the actual most-derived type and return an owning pointer to the new object, and then in derived classes return the derived type (use a covariant return type).

由於會發生切片問題,多態類的複製是不推薦的。如果你真的需要複製語義,就進行深拷貝:提供一個虛的克隆函數,這個函數可以複製實際的派生類型並返回一個指向新對象的所有權指針,同時在派生類中返回派生類型(使用共變量返回類型)

切片問題(slicing problerm):由派生類實例向基類實例賦值時發生的信息丟失。

​共變量返回類型(covariant return type):當基類的虛函數被派生類覆蓋時,如果基類的虛函數返回某個類,而派生類返回該類的派生類,也看做是成功的覆蓋。

Example(示例)

<code>classB{public:       virtualownerclone()=0;       virtual~B()=default;       B(constB&)=delete;       B&operator=(constB&)=delete;};classD:publicB{      public:owner 
clone()override; ~D()override;};
/<code>

Generally, it is recommended to use smart pointers to represent ownership (see R.20). However, because of language rules, the covariant return type cannot be a smart pointer: D::clone can't return a unique_ptr while B::clone returns unique_ptr. Therefore, you either need to consistently return unique_ptr in all overrides, or use owner<> utility from the Guidelines Support Library.

一般情況下,推薦使用智能指針表現所有權(參見R.20)。但是因為語言規則,共變量返回類型不能是智能指針:當B::clone返回unique_ptr時,D::clone不能返回unique_ptr。因此,你要麼在所有的覆蓋都返回unique_ptr,要麼使用準則支持庫中的onwer<>。

原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c130-for-making-deep-copies-of-polymorphic-classes-prefer-a-virtual-clone-function-instead-of-copy-constructionassignment


覺得本文有幫助?請分享給更多人。

更多精彩文章請關注微信公眾號【面向對象思考】!

面向對象開發,面向對象思考!


分享到:


相關文章: