Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very brutal swap using template, xor and pointers to to the memory

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 (=

like image 624
shycha Avatar asked Dec 05 '12 00:12

shycha


2 Answers

It invokes undefined behavior if T is not a trivially copyable type.

like image 66
Pubby Avatar answered Sep 28 '22 08:09

Pubby


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.

like image 24
Praetorian Avatar answered Sep 28 '22 07:09

Praetorian