以下代码无法正常工作。
#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;
}
例如,它打印 chicke boiled
而没有 n
。它也没有交换 x
和 y
,否则它会打印 boiled chicken
。
最佳答案
这不可能。交换的正确行为需要知道 union 包含哪种类型。这不是一个有区别的 union ,因此任何依赖于知道 union 包含哪种类型的操作都将失败,除非特别提供该信息。
我很想听听您认为这会如何运作,甚至是可以想象的。您认为 std::swap
有什么魔力?
关于c++ - 为什么 std::swap 不能在 std::aligned_union 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965533/