簡體   English   中英

如何從復制分配運算符調用復制構造函數?

[英]How to call to the copy constructor from the copy-assignment operator?

我正在實現一個鏈表。 我寫了一個拷貝構造函數:

        // --- copy constructor ---
    IntList(const IntList& last_list) {
        first = new IntNode(last_list.getFirst()->getData());
        cout << "copy first " << first->getData() << endl;

        IntNode* last_node = first;
        IntNode* node = last_list.getFirst()->getNext();
        while(node!=NULL) {
            IntNode* new_node = new IntNode(node->getData());
            last_node->setNext(new_node);
            cout << "copy " << new_node->getData()<< endl;
            last_node = new_node;
            node = node->getNext();
        }
    }

據我了解,我的副本分配運算符( operator= )應該有兩個目標:

  • 刪除當前列表。
  • 復制新列表。

通過調用我已經編寫的析構函數,然后調用副本構造函數,可以實現這2個目標。 我該怎么做?

對於您的副本分配運算符 ,您可以使用“ 復制和交換”習慣用法

例如,在您的情況下,可以將其添加到IntList類定義中(考慮到復制構造函數的代碼,我假設您唯一的數據成員IntNode* first;IntNode* first; ):

        // --- swap non-member function ---
    friend void swap(IntList& a, IntList& b) /* no-fail */ {
        // swap data members one by one
        std::swap(a.first, b.first);
    }

        // --- (copy) assignment operator ---
    IntList& operator=(const IntList& other) {
        IntList temp(other); // copy construction
        swap(*this, temp);   // swap
        return *this;
                             // destruction of temp ("old *this")
    }

實際上,這可能是更好的樣式:

        // --- swap non-member function ---
    friend void swap(IntList& a, IntList& b) /* no-fail */ {
        using std::swap; // enable ADL
        // swap data members one by one
        swap(a.first, b.first);
    }

        // --- (copy) assignment operator ---
    IntList& operator=(IntList other) { // note: take by value
        swap(*this, other);
        return *this;
    }

在C ++ noexcept中, /* no-fail */注釋可以用throw() (或者可能只是/* throw() */注釋) noexcept在C ++ 11中則noexcept

(注意:不要忘記事先為std::swap包含正確的頭文件,即C ++ 98/03中的<algorithm> <utility>和C ++ 11中的<utility> (您也可以同時包含兩者)。 )

備注:這里swap函數是在類主體中定義的,但是它仍然是非成員函數,因為它是friend

有關整個故事,請參見鏈接的帖子。

(當然,除了復制構造函數之外,還必須提供正確的析構函數定義(請參閱什么是三規則 )。)

將所需的功能放在析構函數,復制構造函數和賦值運算符調用的單獨函數中。

暫無
暫無

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

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