iter_swap() versus swap() — what's the difference?

后端 未结 6 2000
陌清茗
陌清茗 2020-12-03 00:24

MSDN says:

swap should be used in preference to iter_swap, which was included in the C++ Standard for backward compatibility

6条回答
  •  悲哀的现实
    2020-12-03 01:06

    This seems to be one of those scenarios in which the internet produces a host of conflicting information.

    • cplusplus.com says that iter_swap is identical to swap and, by that logic, MSDN would be correct in saying that one ought to simply stick to swap.

    • cppreference.com tells us that calling swap is merely a possible implementation for iter_swap, opening the door for possible optimisations in iter_swap for certain specialisations, as long as the function's constant complexity guarantee is upheld.

    The standard, under [C++11: 25.3.3/5], says only that iter_swap(a,b) has the result swap(*a,*b) (and requires that "a and b shall be dereferenceable", and that "*a shall be swappable with *b") which would at first glance correlate with MSDN's interpretation.

    However, I believe Microsoft have neglected to consider the as-if rule, which should allow an implementation to make iter_swap faster than swap in certain cases (e.g. elements of a linked list).

    I would therefore trust that the comp.std.c++ quote is the more technically accurate of the two.

    That being said, there is a fairly strict limit on the optimisation that may be performed. Consider, for example, an implementation of iter_swap over linked list elements that simply re-links nodes rather than physically swapping the element values — this is not a valid implementation, because the requirement that iter_swap's observable behaviour match swap's is violated.

    I would therefore suggest that in practice there can be little if any benefit to preferring iter_swap over swap, and I'd recommend sticking to the latter for simplicity and consistency. C++11 move semantics ought to make swap a cinch in many cases anyway.

提交回复
热议问题