What are the most threats of using such implementation of swap? Besides thread safety and poor optimisation. When does it fail (counterexample)?
template<typename T>
void swapViaMemory(T& left, T& right) {
if(&left == &right) { return ; }
unsigned int tSize = sizeof(T);
unsigned char* lPtr = reinterpret_cast<unsigned char*>(&left);
unsigned char* rPtr = reinterpret_cast<unsigned char*>(&right);
for(unsigned int i = 0; i < tSize; ++i) {
*(lPtr + i) ^= *(rPtr + i);
*(rPtr + i) ^= *(lPtr + i);
*(lPtr + i) ^= *(rPtr + i);
}
}
Sorry for grammar mistakes, and misspellings (=
It invokes undefined behavior if T is not a trivially copyable type.
If T
contains a member which is a pointer or reference to another of its members this will fail (assuming the intent is for the pointer / reference member to always point / refer to the data member belonging to that instance).
struct foo
{
foo() : i(), ref_i(i), ptr_i(&i) {}
int i;
int& ref_i;
int *ptr_i;
};
If two foo
objects, say f1
& f2
are swapped using swapViaMemory
, after swapping, f1.ref_i
and f1.ptr_i
will refer / point to f2.i
and vice versa. Also, in case of the reference member, this invokes undefined behavior since it's illegal to re-seat a reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With