optimization potential in iter_swap()

Martin Reinecke martin@MPA-Garching.MPG.DE
Mon Oct 23 00:25:00 GMT 2000


Hi!

I think I found a situation where iter_swap() could be tuned
to make use of user-defined swap operations.

Consider the following code:

class A { ... };

template<> inline void swap (A &a, A &b) { ... }

int main()
  {
  vector<A> vec;
  ...
  sort (vec.begin(), vec.end());
  }


During the sort(), iter_swap() will be called very often.
However, iter_swap() as defined in stl_algobase.h only uses
the "vanilla" swap operation to exchange the values of its arguments;
the user-defined swap() is not called. I think this is because
iter_swap() does not require that its arguments have exactly the
same type; only their value types must be convertible.

But if we introduce the following specialization of iter_swap(),
the user-defined swap() would be called in the situation above:

template <class _ForwardIter>
inline void iter_swap(_ForwardIter __a, _ForwardIter __b) {
  __STL_REQUIRES(_ForwardIter, _Mutable_ForwardIterator);
  swap(*__a, *__b);
}

This is still not perfect, since it does not match calls like

iter_swap (ForwardIterator<A>, RandomAccessIterator<A>)

but it should cover a very large part of the situations where
swap() can be used. I have no idea how to implement the general case.

When working with large containers of smart pointers etc. this
specialization should produce a noticeable speedup.

What is your opinion?

Cheers,
  Martin


More information about the Libstdc++ mailing list