Shelef
Shelef

Reputation: 3827

How to call to the copy constructor from the copy-assignment operator?

I'm implementing a linked list. I wrote a copy constructor:

        // --- 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();
        }
    }

As I understand, my copy-assignment operator (operator=) should have 2 goals:

I can achieve this 2 goals by calling the destructor which I already wrote and then call the copy constructor. How can I do it?

Upvotes: 0

Views: 525

Answers (2)

gx_
gx_

Reputation: 4760

For your copy assignment operator, you can use the copy-and-swap idiom.

For example in your case, you could add this into your IntList class definition (given the code of your copy constructor, I'm assuming that your only data member is 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")
    }

Actually, this may be better style:

        // --- 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;
    }

The /* no-fail */ comment can be replaced with throw() (or maybe just a /* throw() */ comment) in C++98/03, noexcept in C++11.

(Note: Don't forget to beforehand include the right header for std::swap, that is, <algorithm> in C++98/03, <utility> in C++11 (you can as well include both).)

Remark: Here the swap function is defined in the class body but it is nevertheless a non-member function because it is a friend.

See the linked post for the whole story.

(Of course, you must also provide a correct destructor definition in addition to your copy constructor (see What is The Rule of Three?).)

Upvotes: 9

HeywoodFloyd
HeywoodFloyd

Reputation: 176

Put the functionality you need in separate functions called by the destructor and the copy constructor and the assignment operator.

Upvotes: 1

Related Questions