簡體   English   中英

在派生類中使用基類Copy CTOR

[英]Use base class Copy CTOR in derived class

我知道這個主題有很多帖子,但我找不到任何完全回答我的問題。

假設我有一個Base類和一個Derived類,我為它實現了CCtor和賦值運算符,如下所示:

class Base {
    char * name;
    ....
    Base(const Base& other) :name(nullptr) { *this = other }
    void operator=(const Base& other) { ... Deep copy of name } 
}


class Derived : public Base {
.... 
    Derived(const Derived& other) { *this = other ; }
    void operator=(const Derived& other) {
        Base::operator=(other);
        .....
    }

現在我對這個設計有一些疑問。

  1. 這是適合這種情況的合適設計嗎?
  2. 如果我有一個第三類,在基類和派生類之間,但它只包含原始類型,我在哪里復制它們? EG使用第二類的默認賦值運算符? 建立一個新的? 只在第三級復制它們?
  3. 我可以類似地在派生類CCtor中調用基類CCtor,而不是賦值運算符。 有什么不同? 如果我將它們放在兩種方法中,它會嘗試將值復制兩次嗎?

編輯:只是為了澄清,設計是我在項目中給出的。我有指針所以我必須使用深層復制。

這是適合這種情況的合適設計嗎?

不,通常不會。 更慣用的方法是停止手動管理內存,如char* name並使用std::string或其他類型做正確的事情:

Class Base {
    std::string name;
    ....
    Base(const Base& other) = default;
    Base& operator=(const Base& other) = default;
};

(請注意,賦值運算符應該返回對類的引用,而不是void )。

或者將內存管理封裝在專門為此目的的類設計中(但std::string已經是那種類型)。

如果你真的真的需要做啞容易出錯,然后實現你的拷貝構造函數做復印:

    Base(const Base& other) { / * deep copy of name */ }

然后將賦值實現為copy-and-swap:

    Base& operator=(const Base& other)
    {
      Base tmp(other);
      this->swap(tmp);
      return *this;
    }

這意味着您需要一個廉價的,非投擲swap(Base&)成員函數。

在任何情況下,派生類型的復制構造函數都是愚蠢的。 你有一個正確的基類復制構造函數,所以它應該是:

Derived(const Derived& other) : Base(other) { }

賦值可以使用基本賦值:

Derived& operator=(const Derived& other)
{
   Base::operator=(other);
   return *this;
}

但是手動編寫這些是不必要的,你可以默認它的復制操作,無論如何都會做正確的事情:

class Derived : public Base {
public:
    Derived(const Derived&) = default;
    Derived& operator=(const Derived& ) = default;

如果我有一個第三類,在基類和派生類之間,但它只包含原始類型,我在哪里復制它們? EG使用第二類的默認賦值運算符? 建立一個新的? 只在第三級復制它們?

您應該使用= default定義該類的復制構造函數和賦值運算符。 一旦你使Base安全地以正確的行為進行復制,組成其他類來使用它是微不足道的。 默認行為將是正確的事情。 如果您需要對RAII類型未正確管理的動態分配內存等特殊處理,則只需手動定義這些操作。

我可以類似地在派生類CCtor中調用基類CCtor,而不是賦值運算符。 有什么不同?

如果要復制構造,則使用復制構造函數,而不是賦值。 使用正確的功能來完成工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM