简体   繁体   中英

Class with no pointer data members- copy constructor == assignment operator?

If your class does not have any data members declared using pointers, does the copy constructor always contain the same code as the assignment operator? and if not, why not?

EDIT think I need some code to explain what I mean:

class A{
public:
    A();
    A(const A& a);
    A& operator=(const A& a);

private:
    int a;
    double b;
};

//Copy constructor
A::A(const A& src){
    a = src.a;
    b = src.b;
}

//Assignment operator
A& A::operator=(const A& src){
    //Because none of the data members are pointers- the code in here 
    //would be the same as the copy constructor?

    //Could I do:
    a = src.a;
    b = src.b;
    //?
}

No, the assignment operators of the members are involved:

#include <iostream>
#include <stdexcept>

struct X {
    X() { std::cout << "construct" << std::endl; }
    X(const X&) { std::cout << "copy construct" << std::endl;  }
    X& operator = (const X&) {
        throw std::logic_error("assignment");
    }
};

struct Y {
    X x;
};

int main() {
    Y y0;
    Y y1(y0);
    y1 = y0;
    return 0;
}

A copy constructor operates on raw memory. So if it references a member variable that has not been set yet, then it is referencing uninitialized memory.

An assignment operator operates on memory already containing a constructed object. So all member variables are initialized before the assignment operator starts.

If your assignment operator does not examine any member variables, then the copy ctor code would be the same. But note that using a member variable assignment operator in your assignment operator might reference data you don't know about.

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