shy*_*cha 6 c++ memory templates swap xor
使用这种swap实现的最大威胁是什么?除了线程安全和差的优化.什么时候失败(反例)?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
对不起语法错误和拼写错误(=
如果T包含的成员是指向其另一个成员的指针或引用,则这将失败(假设目的是让指针/引用成员始终指向/引用属于该实例的数据成员)。
struct foo
{
foo() : i(), ref_i(i), ptr_i(&i) {}
int i;
int& ref_i;
int *ptr_i;
};
Run Code Online (Sandbox Code Playgroud)
如果两个foo对象,例如f1& ,在交换后使用 ,f2进行交换,并且将引用/指向,反之亦然。另外,对于引用成员,这会调用未定义的行为,因为重新定位引用是非法的。swapViaMemoryf1.ref_if1.ptr_if2.i
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |