Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

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

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

In which context is each one called?

I mean, if I have the following:

Person *p1 = new Person("Oscar", "Mederos");
Person *p2 = p1;

Which one is used? And then when the other one is used?

Edit:
Just to clarify a little bit:

I already know that if we explicitly call the copy constructor Person p1(p2), the copy constructor will be used. What I wanted to know is when each one is used, but using the = operator instead, as @Martin pointed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...