Reputation: 177
I have three questions regarding swapping, most likely pretty basic to you.
(1) With regards to two same type STL containers a
and b
, both operations below would work
swap(a,b);
a.swap(b);
I understand that the second is specialized for the container (e.g., only involves a number of iterator swaps) while the first is a global algorithm meant to work with generic datatypes and performs an internal copy-construct.
My question is if I write the first, will the compiler use the second regardless, or do I have to be careful to check if an appropriate specialization exists?
(2) Would swap(a,b)
result in the same performance with swap(b,a)
? If a copy-construct is involved and the objects are of considerably different size, I suspect it may matter?
(3) In cases where the overloaded operator ==
exists and is relatively fast, checking for a == b
before swapping would make sense so as to avoid unnecessary operations. Does std::swap
apply this check first, or does it perform the operation regardless?
Thanks for your time!
Upvotes: 7
Views: 146
Reputation: 76295
The global swap
template is specialized for each of the standard library types that supports swap
; the specialization calls the member swap
.
There should be no difference between swap(a, b)
and swap(b, a)
. (I can imagine perverse types where it would matter, but that would never occur in practice).
No, std::swap
typically doesn't check for equality. In many cases that would be slower than just doing the swap.
Upvotes: 7