roscioli
roscioli

Reputation: 1230

How does std::swap work in terms of constructors, assignment operators, and destructors?

If I have T a and T b and I call std::swap(a, b), what is the order of copy constructors, assignment operators, and destructors that are called?

Upvotes: 1

Views: 418

Answers (2)

Niall
Niall

Reputation: 30605

There is no specific order that is "mandated", it would all depend on the implementation provided by the Standard Library being used.

A C++03 variation of std::swap would be:

template<typename T>
void swap(T& a, T& b) {
    T temp(a); // copy
    a = b;     // assign
    b = temp;  // assign
}

A C++11 implementation would be:

template<typename T>
void swap(T& a, T& b) {
    T temp = std::move(a); // move copy or normal copy (moves if moveable)
    a = std::move(b);      // move or assign
    b = std::move(temp);   // move or assign
}

Several std containers etc. do specialise on swap because they can offer better or more efficient implementations; custom types could do the same. In these specialisations, even more variation could or would occur.

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254431

If there is no specialisation for T, then the generic version will do something along the lines of

{
    T t = std::move(a);  // move construction
    a = std::move(b);    // move assignment
    b = std::move(t);    // move assignment
}                        // destruction of t

Some types (such as containers) might have specialisations which will swap internal pointers etc., with no temporary object and no object assignment.

Upvotes: 3

Related Questions