Gauthier
Gauthier

Reputation: 41945

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.

Upvotes: 5

Views: 558

Answers (2)

Leon
Leon

Reputation: 32464

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.

It could be guaranteed for the exception-safe swap-based implementation of assignment:

struct SomeClass
{
    SomeClass(const SomeClass& other) { ... }
    SomeClass(SomeClass&& other) { ... }

    // Copy/move construction is performed while initializing the parameter
    void operator=(SomeClass other)
    {
        this->swap(other);
    }

    void swap(SomeClass& other) { ... }
};

The disadvantage of such an implementation of assignment is that - because of its generality - it is not the most optimal one (for example, it does unnecessary job in case of self assignment).

In general, if exception safety concerns can be rules out, copy assigning to an object can be done faster than destroying it and constructing an in-place copy of the source object. Therefore, you should expect that performance-seeking implementations would perform assignment of objects through assignment rather than copy-construction of their sub-objects wherever possible.

Upvotes: 0

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.

Upvotes: 5

Related Questions