Paolo M Paolo M - 3 months ago 15
C++ Question

Adapting std::swap interface to swap n bytes

I have a C function to swap an arbitrary number of bytes:

void my_swap(void* a, void* b, long n);


I've done a little benchmark with several types and I've seen that
std::swap
outperform
my_swap
.

So, I'd like to wrap
std::swap
with
my_swap
interface, but I can't figure out how to tell
std::swap
to behave as if it was swapping two variables of a type
T
, for which
sizeof(T)==n
.

Can anybody wrap
std::swap
in a function with same signature (and same semantic, of course) as
my_swap
?

Answer

Not possible because std::swap must know exactly the type of the passed variables.

There may be several reasons as to why your my_swap is slower than std::swap, like:

  • Your function transfers byte-by-byte, which usually results in being 4* (or more) slower than doing the same operation done on ints
  • The compiler generates slower code because it cannot be sure that these two void* variables point to an "unaliased" memory (in particular, that the operation you're going to do with the pointed memory will not reach the area of one that may overlap with the other). Compilers are not allowed to generate fast code for that cases because in case of overlaps it will result in wrong data operation.

This is why it is impossible to write an implementation of my_swap that would be that fast as std::swap because this void* as argument is the reason.