c++ - 字节交换方面的一般交换实现

标签 c++ c++14 swap c++-standard-library

标准库中通用交换的当前实现类似于

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/

相关文章:

c++ - 创建非 odr 使用的文字类型

c - 在 C 中的节点之间交换字符串

java - 将二维矩阵对角线与中线交换

c++ - 如何确定模板中函数的返回类型

C++ 映射大括号初始化和唯一指针

c++ - 为什么C++优化器在删除同一个指针时使用不同的delete

javascript - 使用 Javascript 交换两个样式表 CSS 文件

c++ - 在 C++ 中通过指针设置/获取值

java - 以C/C++和其他语言重现Java原语hashCode逻辑的库

c++ - 整数除法算法