Reputation: 2885
Let's suppose I have the following code:
std::vector<myclass> v1;
v1.push_back (x1);
v1.push_back (x2);
std::vector<myclass> v2(v1);
When I run the code above, the copy constructors of both x1 and x2 are called to build the vector v2, which seems the right thing to do.
But if I rewrite the code in this way:
std::vector<myclass> v1, v2;
v1.push_back (x1);
v1.push_back (x2);
v2 = v1;
the copy constructors of x1 and x2 are called again. Is it the right behaviour? Why is not the assignment operator called? Wouldn't it be more consistent to call the assignment operator of x1 and x2? It seems that a copy assignation of a vector doesn't mean a copy assignment of its elements.
What if I have a class where copy construction and copy assignation must have different semantics?
EDIT. v2 is empty before the call to v2=v1, but shouldn't the copy assignment be called after creating a vector with 2 elements? It would seem more consistent to me... BTW, the compiler forces the definition of a myclass copy assignment operator when I try to call v2=v1, even when it isn't using it.
Upvotes: 0
Views: 3501
Reputation: 3542
It doesn't make sense to call the assignment operator for x1
and x2
because you aren't assigning to either of them. v2
's assignment operator will make its internal array large enough for all the elements of v1
and then copy all of the elements of v1
into v2
.
Upvotes: 1