简体   繁体   中英

Should the copy constructor and copy assignment operator have the same statements?

The return type will be different of course, but the concept is the same: copying the data from one object to another, right?

The concepts are fundamentally different; the copy constructor creates a new object where one doesn't exist (and does not return anything – not even void ), and the assignment operator updates an object that already exists.

No. While the copy assignment operator does copy data to another object, the copy constructor initializes a new object with the copied data. As such, it will use its member initializer list to invoke its member's copy constructors recursively, while the copy-assignment operator will invoke other copy-assignment operators.

struct Foo {

    Foo(Foo const &orig)
    : data{oring.data} { }

    Foo &operator = (Foo const &orig) {
        data = orig.data;
        return *this;
    }

private:
    std::string data;
};

The copy constructor initializes the new object with an already existing object.

The copy assignment assigns the value of one object to another object both of which are already in existence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM