标准库中通用交换的当前实现类似于
template <class T>
void swap(T& a, T& b) {
T c(move(a));
a = move(b);
b = move(c);
}
我想知道我是否可以改为执行以下操作。
template <class T>
void swap(T& a, T& b) {
unsigned char x;
auto pa = reintepret_cast<unsigned char*>(&a);
auto pb = reintepret_cast<unsigned char*>(&b);
auto pc = pa + sizeof(a);
while (pa != pc) {
x = *pa;
*pa = *pb;
*pb = x;
++pa, ++pb;
}
}
我认为这种实现在空间使用方面更好,因为它只占用一个字节。
最佳答案
交换类(class)时需要考虑许多注意事项。对于 POD 类型,交换字节可以正常工作。然而,更复杂的类可能依赖字节交换不考虑的不变量。例如,考虑对成员变量的引用:
struct Foo {
Foo() : bar{}, barRef{bar} {};
int bar;
int& barRef; // Expected to refer to the neighboring `bar`
};
int main()
{
Foo f{};
{
Foo g{};
byte_swap(f, g);
}
// `f` is now invalid: `f.barRef` is pointing to garbage
}
关于c++ - 字节交换方面的一般交换实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835027/