What is the difference between overloading operator= and overloading the copy constructor?

后端 未结 3 592
我寻月下人不归
我寻月下人不归 2020-12-20 15:29

What is the difference between overloading the operator = in a class and the copy constructor?

In which context is each one called?

I m

3条回答
  •  没有蜡笔的小新
    2020-12-20 15:51

    In your case neither is used as you are copying a pointer.

    Person p1("Oscar", "Mdderos");
    Person extra;
    

    The copy constructor

    Person P2(p1);      // A copy is made using the copy constructor
    Person P3  = p2;    // Another form of copy construction.
                        // P3 is being-initialized and it uses copy construction here
                        // NOT the assignment operator
    

    An assignment:

    extra = P2;         // An already existing object (extra)
                        // is assigned to.
    

    It is worth mentioning that that the assignment operator can be written in terms of the copy constructor using the Copy and Swap idium:

    class Person
    {
        Person(std::string const& f, std::string const& s);
        Person(Person const& copy);
    
        // Note: Do not use reference here.
        //       Thus getting you an implicit copy (using the copy constructor)
        //       and thus you just need to the swap
        Person& operator=(Person copy)
        {
            copy.swap(*this);
            return *this;
        }
    
        void swap(Person& other) throws()
        {
              // Swap members of other and *this;
        }
    };
    

提交回复
热议问题