Search code examples
c++vectorcopy-constructorcopy-assignment

C++ vector copy assignment, calling which copy mechanism of its elements?


My class A explicitly implements both its copy constructor and its copy assignment.

Which copy mechanism is used when copy assigning a vector of such elements?

Is this:

vector<A> a1, a2(5);
a1 = a2;

going to use A's copy constructor for all new elements of a1, with the elements of a2 as input?

Or is it going to make room in a1 for the elements, then use A's operator= with the elements of a2 as input?

What if a1 isn't empty before the assignment?

Is it even specified?

My class's copy constructor and operator= don't exactly do the same thing (is it bad practice? Mainly testing stuff so far). It looks like the copy constructor is called, but I wonder if it is guaranteed to be that way or if it just happens to be so in this very case.


Solution

  • In this context it will call the copy constructor 5 times. Since a1 is empty, there aren't any elements to assign to. So they need to be copy-constructed.

    Generally, it will call whatever mixture of copy/move construction/assignment or deletion is appropriate. All depending on the sizes of the vectors in question, the particular vector operation you are performing, and the value categories of the operands.