Default assignment operator= in c++ is a shallow copy?

前端 未结 8 2151
挽巷
挽巷 2020-12-14 05:42

Just a simple quick question which I couldn\'t find a solid answer to anywhere else. Is the default operator= just a shallow copy of all the class\' members on the right ha

8条回答
  •  一生所求
    2020-12-14 06:25

    I personally like the explanation in Accelerated c++. The text (page 201) says:

    If the class author does not specify the assignment operator, the compiler synthesizes a default version. The default version is defined to operate recursively - assigning each data element according to the appropriate rules for the type of that element. Each member of a class type is assigned by calling that member's assignment operator. Members that are of built-in type are assigned by assigning their values.

    As the members in the question are integers, I understand that they are deep copied. The following adaptation of your example illustrates this:

    #include
    class foo {
    public:
      int a, b, c;
    };
    
    int main() {
        foo f1, f2;
        f1 = f2;
        std::cout << "f1.a and f2.a are: " << f1.a << " and " << f2.a << std::endl;
        f2.a = 0;
        std::cout << "now, f1.a and f2.a are: " << f1.a << " and " << f2.a << std::endl;
    }
    

    which prints:

    f1.a and f2.a are: 21861 and 21861
    now, f1.a and f2.a are: 21861 and 0
    

提交回复
热议问题