简体   繁体   中英

Questions regarding performance of swap

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 (eg, 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!

  1. The global swap template is specialized for each of the standard library types that supports swap ; the specialization calls the member swap .

  2. 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).

  3. No, std::swap typically doesn't check for equality. In many cases that would be slower than just doing the swap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM