Paolo M Paolo M - 1 year ago 104
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

So, I'd like to wrap
interface, but I can't figure out how to tell
to behave as if it was swapping two variables of a type
, for which

Can anybody wrap
in a function with same signature (and same semantic, of course) as

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download