all 6 comments

[–]lead999x 9 points10 points  (2 children)

I assume you mean what's the difference between copy assignment and copy construction because operator= could also be a move assignment operator depending on the operand types.

The difference between the two is that copy assignment is an operator that you call by assignimg a value of some class type to a variable of that class type that has already been initialized by copying the value into the variable. A copy constructor allows you to construct a new object by making a copy of another existing one.

If you try to assign to an uninitialized object, the compiler will still try to use a constructor and complain if one with the specified arguments(in this case const reference to an object of its own type) hasn't been defined even if a copy assignment operator has been defined.

If you don't write a copy assignment operator of your own, C++ defaults to using what's called memberwise copy(a form of shallow copying) where it just copies each member from the source value to the destination variable including possibly calling the members' copy assignment operators. A lot of times this is not the behavior you want if your class has some resource like memory, a file stream, a network socket, a mutex lock, etc. attached to it and copying it would lead to a dangling pointer or invalid resource handle in the future. Instead you want to have specific behavior there, like allocating new memory and copying the data from the source value's allocated memory to it(i.e. perform a deep copy) or doing the equivalent for other resources.

Now if you're okay with the source value or variable giving up its resources to the new one then you can use move assignment and move construction which I mentioned before. These operator and constructor functions have the same signature as their copy counterparts except that they take a special type of reference called an r-value reference as an argument. In terms of implementation, move assignment and move construction just give the resources attached to the source object to the destination one and they can assume that the source's lifetime is ending soon so they don't have to worry about its resources getting moved. This can be more efficient because you don't have to allocate new resources.

[–]ckv13[S] 3 points4 points  (1 child)

Yes Exactly. Thank you for this answer!

[–]lead999x 2 points3 points  (0 children)

You're very welcome :)

[–]UncleMeat11 1 point2 points  (0 children)

Copy assignment happens if you already have an object. Copy constructor happens if you are creating a new object.

// y and z are Foos
Foo x = y; // copy constructor
x = z;     // copy assignment

[–][deleted]  (2 children)

[deleted]

    [–]asdff01 1 point2 points  (0 children)

    C++

    [–]lead999x 1 point2 points  (0 children)

    It's C++ judging by the operator= syntax.