为什么 std::swap 不适用于 std::aligned_union

Why doesn't std::swap work on std::aligned_union

本文关键字:std aligned union 不适用 swap 为什么 适用于      更新时间:2023-10-16

以下代码不太适用。

#include <type_traits>
#include <string>
#include <iostream>
template<std::size_t Len, class... Types>
using dataType = typename std::aligned_union<Len,Types...>::type;
int main()
{
    dataType<1,int,float,std::string,char,bool> x;
    dataType<1,int,float,std::string,char,bool> y;
    new (&x) std::string("chicken");
    new (&y) std::string("boiled");
    std::swap(x,y);
    std::cout << *reinterpret_cast<std::string*>(&x) << " " << *reinterpret_cast<std::string*>(&y) << std::endl;
}

例如它打印没有nchicke boiled。它也没有交换xy,否则它将打印boiled chicken

这不可能工作。交换的正确行为需要知道联合包含哪种类型。这不是一个有区别的并集,因此任何依赖于知道并集包含的类型的操作都将失败,除非专门提供了该信息。

我很想听听你是怎么想的,甚至可以想象。你认为std::swap有什么魔力?